• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright (C) 2010-2014 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 /******************************************************************************
20  *
21  *  This file contains the implementation for Type 3 tag in Card Emulation
22  *  mode.
23  *
24  ******************************************************************************/
25 #include <string.h>
26 
27 #include <android-base/stringprintf.h>
28 #include <base/logging.h>
29 #include <log/log.h>
30 
31 #include "nfc_target.h"
32 
33 #include "bt_types.h"
34 #include "ce_api.h"
35 #include "ce_int.h"
36 
37 using android::base::StringPrintf;
38 
39 extern bool nfc_debug_enabled;
40 
41 enum {
42   CE_T3T_COMMAND_INVALID,
43   CE_T3T_COMMAND_NFC_FORUM,
44   CE_T3T_COMMAND_FELICA
45 };
46 
47 /* T3T CE states */
48 enum { CE_T3T_STATE_NOT_ACTIVATED, CE_T3T_STATE_IDLE, CE_T3T_STATE_UPDATING };
49 
50 /* Bitmasks to indicate type of UPDATE */
51 #define CE_T3T_UPDATE_FL_NDEF_UPDATE_START 0x01
52 #define CE_T3T_UPDATE_FL_NDEF_UPDATE_CPLT 0x02
53 #define CE_T3T_UPDATE_FL_UPDATE 0x04
54 
55 /*******************************************************************************
56 * Static constant definitions
57 *******************************************************************************/
58 /* Default PMm param */
59 static const uint8_t CE_DEFAULT_LF_PMM[NCI_T3T_PMM_LEN] = {
60     0x01, /* This PAD0 is used to identify HCE-F on Android */
61     0xFE, /* This PAD0 is used to identify HCE-F on Android */
62     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
63 
64 /*******************************************************************************
65 **
66 ** Function         ce_t3t_init
67 **
68 ** Description      Initialize tag-specific fields of ce control block
69 **
70 ** Returns          none
71 **
72 *******************************************************************************/
ce_t3t_init(void)73 void ce_t3t_init(void) {
74   memcpy(ce_cb.mem.t3t.local_pmm, CE_DEFAULT_LF_PMM, NCI_T3T_PMM_LEN);
75   ce_cb.mem.t3t.ndef_info.nbr = CE_T3T_DEFAULT_CHECK_MAXBLOCKS;
76   ce_cb.mem.t3t.ndef_info.nbw = CE_T3T_DEFAULT_UPDATE_MAXBLOCKS;
77 }
78 
79 /*******************************************************************************
80 **
81 ** Function         ce_t3t_send_to_lower
82 **
83 ** Description      Send C-APDU to lower layer
84 **
85 ** Returns          none
86 **
87 *******************************************************************************/
ce_t3t_send_to_lower(NFC_HDR * p_msg)88 void ce_t3t_send_to_lower(NFC_HDR* p_msg) {
89   uint8_t* p;
90 
91   /* Set NFC-F SoD field (payload len + 1) */
92   p_msg->offset -= 1; /* Point to SoD field */
93   p = (uint8_t*)(p_msg + 1) + p_msg->offset;
94   UINT8_TO_STREAM(p, (p_msg->len + 1));
95   p_msg->len += 1; /* Increment len to include SoD */
96 
97   if (NFC_SendData(NFC_RF_CONN_ID, p_msg) != NFC_STATUS_OK) {
98     LOG(ERROR) << StringPrintf("failed");
99   }
100 }
101 
102 /*******************************************************************************
103 **
104 ** Function         ce_t3t_is_valid_opcode
105 **
106 ** Description      Valid opcode
107 **
108 ** Returns          Type of command
109 **
110 *******************************************************************************/
ce_t3t_is_valid_opcode(uint8_t cmd_id)111 uint8_t ce_t3t_is_valid_opcode(uint8_t cmd_id) {
112   uint8_t retval = CE_T3T_COMMAND_INVALID;
113 
114   if ((cmd_id == T3T_MSG_OPC_CHECK_CMD) || (cmd_id == T3T_MSG_OPC_UPDATE_CMD)) {
115     retval = CE_T3T_COMMAND_NFC_FORUM;
116   } else if ((cmd_id == T3T_MSG_OPC_POLL_CMD) ||
117              (cmd_id == T3T_MSG_OPC_REQ_SERVICE_CMD) ||
118              (cmd_id == T3T_MSG_OPC_REQ_RESPONSE_CMD) ||
119              (cmd_id == T3T_MSG_OPC_REQ_SYSTEMCODE_CMD)) {
120     retval = CE_T3T_COMMAND_FELICA;
121   }
122 
123   return (retval);
124 }
125 
126 /*****************************************************************************
127 **
128 ** Function         ce_t3t_get_rsp_buf
129 **
130 ** Description      Get a buffer for sending T3T messages
131 **
132 ** Returns          NFC_HDR *
133 **
134 *****************************************************************************/
ce_t3t_get_rsp_buf(void)135 NFC_HDR* ce_t3t_get_rsp_buf(void) {
136   NFC_HDR* p_cmd_buf;
137 
138   p_cmd_buf = (NFC_HDR*)GKI_getpoolbuf(NFC_CE_POOL_ID);
139   if (p_cmd_buf != nullptr) {
140     /* Reserve offset for NCI_DATA_HDR and NFC-F Sod (LEN) field */
141     p_cmd_buf->offset = NCI_MSG_OFFSET_SIZE + NCI_DATA_HDR_SIZE + 1;
142     p_cmd_buf->len = 0;
143   }
144 
145   return (p_cmd_buf);
146 }
147 
148 /*******************************************************************************
149 **
150 ** Function         ce_t3t_send_rsp
151 **
152 ** Description      Send response to reader/writer
153 **
154 ** Returns          none
155 **
156 *******************************************************************************/
ce_t3t_send_rsp(tCE_CB * p_ce_cb,uint8_t * p_nfcid2,uint8_t opcode,uint8_t status1,uint8_t status2)157 void ce_t3t_send_rsp(tCE_CB* p_ce_cb, uint8_t* p_nfcid2, uint8_t opcode,
158                      uint8_t status1, uint8_t status2) {
159   tCE_T3T_MEM* p_cb = &p_ce_cb->mem.t3t;
160   NFC_HDR* p_rsp_msg;
161   uint8_t *p_dst, *p_rsp_start;
162 
163   /* If p_nfcid2 is NULL, then used activated NFCID2 */
164   if (p_nfcid2 == nullptr) {
165     p_nfcid2 = p_cb->local_nfcid2;
166   }
167 
168   p_rsp_msg = ce_t3t_get_rsp_buf();
169   if (p_rsp_msg != nullptr) {
170     p_dst = p_rsp_start = (uint8_t*)(p_rsp_msg + 1) + p_rsp_msg->offset;
171 
172     /* Response Code */
173     UINT8_TO_STREAM(p_dst, opcode);
174 
175     /* Manufacturer ID */
176     ARRAY_TO_STREAM(p_dst, p_nfcid2, NCI_RF_F_UID_LEN);
177 
178     /* Status1 and Status2 */
179     UINT8_TO_STREAM(p_dst, status1);
180     UINT8_TO_STREAM(p_dst, status2);
181 
182     p_rsp_msg->len = (uint16_t)(p_dst - p_rsp_start);
183     ce_t3t_send_to_lower(p_rsp_msg);
184   } else {
185     LOG(ERROR) << StringPrintf(
186         "CE: Unable to allocat buffer for response message");
187   }
188 }
189 
190 /*******************************************************************************
191 **
192 ** Function         ce_t3t_handle_update_cmd
193 **
194 ** Description      Handle UPDATE command from reader/writer
195 **
196 ** Returns          none
197 **
198 *******************************************************************************/
ce_t3t_handle_update_cmd(tCE_CB * p_ce_cb,NFC_HDR * p_cmd_msg)199 void ce_t3t_handle_update_cmd(tCE_CB* p_ce_cb, NFC_HDR* p_cmd_msg) {
200   tCE_T3T_MEM* p_cb = &p_ce_cb->mem.t3t;
201   uint8_t* p_temp;
202   uint8_t* p_block_list = p_cb->cur_cmd.p_block_list_start;
203   uint8_t* p_block_data = p_cb->cur_cmd.p_block_data_start;
204   uint8_t i, j, bl0;
205   uint16_t block_number, service_code, checksum, checksum_rx;
206   uint32_t newlen_hiword;
207   tCE_T3T_NDEF_INFO ndef_info;
208   tNFC_STATUS nfc_status = NFC_STATUS_OK;
209   uint8_t update_flags = 0;
210 
211   /* If in idle state, notify app that update is starting */
212   if (p_cb->state == CE_T3T_STATE_IDLE) {
213     p_cb->state = CE_T3T_STATE_UPDATING;
214   }
215 
216   for (i = 0; i < p_cb->cur_cmd.num_blocks; i++) {
217     /* Read byte0 of block list */
218     STREAM_TO_UINT8(bl0, p_block_list);
219 
220     if (bl0 & T3T_MSG_MASK_TWO_BYTE_BLOCK_DESC_FORMAT) {
221       STREAM_TO_UINT8(block_number, p_block_list);
222     } else {
223       STREAM_TO_UINT16(block_number, p_block_list);
224     }
225 
226     /* Read the block from memory */
227     service_code =
228         p_cb->cur_cmd.service_code_list[bl0 & T3T_MSG_SERVICE_LIST_MASK];
229 
230     /* Reject UPDATE command if service code=T3T_MSG_NDEF_SC_RO */
231     if (service_code == T3T_MSG_NDEF_SC_RO) {
232       /* Error: invalid block number to update */
233       LOG(ERROR) << StringPrintf("CE: UPDATE request using read-only service");
234       nfc_status = NFC_STATUS_FAILED;
235       break;
236     }
237 
238     /* Check for NDEF */
239     if (service_code == T3T_MSG_NDEF_SC_RW) {
240       if (p_cb->cur_cmd.num_blocks > p_cb->ndef_info.nbw) {
241         LOG(ERROR) << StringPrintf(
242             "CE: Requested too many blocks to update (requested: %i, max: %i)",
243             p_cb->cur_cmd.num_blocks, p_cb->ndef_info.nbw);
244         nfc_status = NFC_STATUS_FAILED;
245         break;
246       } else if (p_cb->ndef_info.rwflag == T3T_MSG_NDEF_RWFLAG_RO) {
247         LOG(ERROR) << StringPrintf(
248             "CE: error: write-request to read-only NDEF message.");
249         nfc_status = NFC_STATUS_FAILED;
250         break;
251       } else if (block_number == 0) {
252         DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
253             "CE: Update sc 0x%04x block %i.", service_code, block_number);
254 
255         /* Special caes: NDEF block0 is the ndef attribute block */
256         p_temp = p_block_data;
257         STREAM_TO_UINT8(ndef_info.version, p_block_data);
258         p_block_data += 8; /* Ignore nbr,nbw,maxb,and reserved (reader/writer
259                               not allowed to update this) */
260         STREAM_TO_UINT8(ndef_info.writef, p_block_data);
261         p_block_data++; /* Ignore rwflag (reader/writer not allowed to update
262                            this) */
263         STREAM_TO_UINT8(newlen_hiword, p_block_data);
264         BE_STREAM_TO_UINT16(ndef_info.ln, p_block_data);
265         ndef_info.ln += (newlen_hiword << 16);
266         BE_STREAM_TO_UINT16(checksum_rx, p_block_data);
267 
268         checksum = 0;
269         for (j = 0; j < T3T_MSG_NDEF_ATTR_INFO_SIZE; j++) {
270           checksum += p_temp[j];
271         }
272 
273         /* Compare calcuated checksum with received checksum */
274         if (checksum != checksum_rx) {
275           LOG(ERROR) << StringPrintf(
276               "CE: Checksum failed for NDEF attribute block.");
277           nfc_status = NFC_STATUS_FAILED;
278         } else {
279           /* Update NDEF attribute block (only allowed to update current length
280            * and writef fields) */
281           p_cb->ndef_info.scratch_ln = ndef_info.ln;
282           p_cb->ndef_info.scratch_writef = ndef_info.writef;
283 
284           /* If writef=0 indicates completion of NDEF update */
285           if (ndef_info.writef == 0) {
286             update_flags |= CE_T3T_UPDATE_FL_NDEF_UPDATE_CPLT;
287           }
288           /* writef=1 indicates start of NDEF update */
289           else {
290             update_flags |= CE_T3T_UPDATE_FL_NDEF_UPDATE_START;
291           }
292         }
293       } else {
294         DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
295             "CE: Udpate sc 0x%04x block %i.", service_code, block_number);
296 
297         /* Verify that block_number is within NDEF memory */
298         if (block_number > p_cb->ndef_info.nmaxb) {
299           /* Error: invalid block number to update */
300           LOG(ERROR) << StringPrintf(
301               "CE: Requested invalid NDEF block number to update %i (max is "
302               "%i).",
303               block_number, p_cb->ndef_info.nmaxb);
304           nfc_status = NFC_STATUS_FAILED;
305           break;
306         } else {
307           /* Update NDEF memory block */
308           STREAM_TO_ARRAY(
309               (&p_cb->ndef_info
310                     .p_scratch_buf[(block_number - 1) * T3T_MSG_BLOCKSIZE]),
311               p_block_data, T3T_MSG_BLOCKSIZE);
312         }
313 
314         /* Set flag to indicate that this UPDATE contained at least one block */
315         update_flags |= CE_T3T_UPDATE_FL_UPDATE;
316       }
317     } else {
318       /* Error: invalid service code */
319       LOG(ERROR) << StringPrintf("CE: Requested invalid service code: 0x%04x.",
320                                  service_code);
321       nfc_status = NFC_STATUS_FAILED;
322       break;
323     }
324   }
325 
326   /* Send appropriate response to reader/writer */
327   if (nfc_status == NFC_STATUS_OK) {
328     ce_t3t_send_rsp(p_ce_cb, nullptr, T3T_MSG_OPC_UPDATE_RSP,
329                     T3T_MSG_RSP_STATUS_OK, T3T_MSG_RSP_STATUS_OK);
330   } else {
331     ce_t3t_send_rsp(p_ce_cb, nullptr, T3T_MSG_OPC_UPDATE_RSP,
332                     T3T_MSG_RSP_STATUS_ERROR, T3T_MSG_RSP_STATUS2_ERROR_MEMORY);
333     p_cb->state = CE_T3T_STATE_IDLE;
334   }
335 
336   /* Notify the app of what got updated */
337   if (update_flags & CE_T3T_UPDATE_FL_NDEF_UPDATE_START) {
338     /* NDEF attribute got updated with WriteF=TRUE */
339     p_ce_cb->p_cback(CE_T3T_NDEF_UPDATE_START_EVT, nullptr);
340   }
341 
342   if (update_flags & CE_T3T_UPDATE_FL_UPDATE) {
343     /* UPDATE message contained at least one non-NDEF block */
344     p_ce_cb->p_cback(CE_T3T_UPDATE_EVT, nullptr);
345   }
346 
347   if (update_flags & CE_T3T_UPDATE_FL_NDEF_UPDATE_CPLT) {
348     /* NDEF attribute got updated with WriteF=FALSE */
349     tCE_DATA ce_data;
350     ce_data.update_info.status = nfc_status;
351     ce_data.update_info.p_data = p_cb->ndef_info.p_scratch_buf;
352     ce_data.update_info.length = p_cb->ndef_info.scratch_ln;
353     p_cb->state = CE_T3T_STATE_IDLE;
354     p_ce_cb->p_cback(CE_T3T_NDEF_UPDATE_CPLT_EVT, &ce_data);
355   }
356 
357   GKI_freebuf(p_cmd_msg);
358 }
359 
360 /*******************************************************************************
361 **
362 ** Function         ce_t3t_handle_check_cmd
363 **
364 ** Description      Handle CHECK command from reader/writer
365 **
366 ** Returns          Nothing
367 **
368 *******************************************************************************/
ce_t3t_handle_check_cmd(tCE_CB * p_ce_cb,NFC_HDR * p_cmd_msg)369 void ce_t3t_handle_check_cmd(tCE_CB* p_ce_cb, NFC_HDR* p_cmd_msg) {
370   tCE_T3T_MEM* p_cb = &p_ce_cb->mem.t3t;
371   NFC_HDR* p_rsp_msg;
372   uint8_t* p_rsp_start;
373   uint8_t *p_dst, *p_temp, *p_status;
374   uint8_t* p_src = p_cb->cur_cmd.p_block_list_start;
375   uint8_t i, bl0;
376   uint8_t ndef_writef;
377   uint32_t ndef_len;
378   uint16_t block_number, service_code, checksum;
379 
380   p_rsp_msg = ce_t3t_get_rsp_buf();
381   if (p_rsp_msg != nullptr) {
382     p_dst = p_rsp_start = (uint8_t*)(p_rsp_msg + 1) + p_rsp_msg->offset;
383 
384     /* Response Code */
385     UINT8_TO_STREAM(p_dst, T3T_MSG_OPC_CHECK_RSP);
386 
387     /* Manufacturer ID */
388     ARRAY_TO_STREAM(p_dst, p_cb->local_nfcid2, NCI_RF_F_UID_LEN);
389 
390     /* Save pointer to start of status field */
391     p_status = p_dst;
392 
393     /* Status1 and Status2 (assume success initially */
394     UINT8_TO_STREAM(p_dst, T3T_MSG_RSP_STATUS_OK);
395     UINT8_TO_STREAM(p_dst, T3T_MSG_RSP_STATUS_OK);
396     UINT8_TO_STREAM(p_dst, p_cb->cur_cmd.num_blocks);
397 
398     for (i = 0; i < p_cb->cur_cmd.num_blocks; i++) {
399       /* Read byte0 of block list */
400       STREAM_TO_UINT8(bl0, p_src);
401 
402       if (bl0 & T3T_MSG_MASK_TWO_BYTE_BLOCK_DESC_FORMAT) {
403         STREAM_TO_UINT8(block_number, p_src);
404       } else {
405         STREAM_TO_UINT16(block_number, p_src);
406       }
407 
408       /* Read the block from memory */
409       service_code =
410           p_cb->cur_cmd.service_code_list[bl0 & T3T_MSG_SERVICE_LIST_MASK];
411 
412       /* Check for NDEF */
413       if ((service_code == T3T_MSG_NDEF_SC_RO) ||
414           (service_code == T3T_MSG_NDEF_SC_RW)) {
415         /* Verify Nbr (NDEF only) */
416         if (p_cb->cur_cmd.num_blocks > p_cb->ndef_info.nbr) {
417           /* Error: invalid number of blocks to check */
418           LOG(ERROR) << StringPrintf(
419               "CE: Requested too many blocks to check (requested: %i, max: %i)",
420               p_cb->cur_cmd.num_blocks, p_cb->ndef_info.nbr);
421 
422           p_dst = p_status;
423           UINT8_TO_STREAM(p_dst, T3T_MSG_RSP_STATUS_ERROR);
424           UINT8_TO_STREAM(p_dst, T3T_MSG_RSP_STATUS2_ERROR_MEMORY);
425           break;
426         } else if (block_number == 0) {
427           /* Special caes: NDEF block0 is the ndef attribute block */
428           p_temp = p_dst;
429 
430           /* For rw ndef, use scratch buffer's attributes (in case reader/writer
431            * had previously updated NDEF) */
432           if ((p_cb->ndef_info.rwflag == T3T_MSG_NDEF_RWFLAG_RW) &&
433               (p_cb->ndef_info.p_scratch_buf)) {
434             ndef_writef = p_cb->ndef_info.scratch_writef;
435             ndef_len = p_cb->ndef_info.scratch_ln;
436           } else {
437             ndef_writef = p_cb->ndef_info.writef;
438             ndef_len = p_cb->ndef_info.ln;
439           }
440 
441           UINT8_TO_STREAM(p_dst, p_cb->ndef_info.version);
442           UINT8_TO_STREAM(p_dst, p_cb->ndef_info.nbr);
443           UINT8_TO_STREAM(p_dst, p_cb->ndef_info.nbw);
444           UINT16_TO_BE_STREAM(p_dst, p_cb->ndef_info.nmaxb);
445           UINT32_TO_STREAM(p_dst, 0);
446           UINT8_TO_STREAM(p_dst, ndef_writef);
447           UINT8_TO_STREAM(p_dst, p_cb->ndef_info.rwflag);
448           UINT8_TO_STREAM(p_dst, (ndef_len >> 16 & 0xFF));
449           UINT16_TO_BE_STREAM(p_dst, (ndef_len & 0xFFFF));
450 
451           checksum = 0;
452           for (int j = 0; j < T3T_MSG_NDEF_ATTR_INFO_SIZE; j++) {
453             checksum += p_temp[j];
454           }
455           UINT16_TO_BE_STREAM(p_dst, checksum);
456         } else {
457           /* Verify that block_number is within NDEF memory */
458           if (block_number > p_cb->ndef_info.nmaxb) {
459             /* Invalid block number */
460             p_dst = p_status;
461 
462             LOG(ERROR) << StringPrintf(
463                 "CE: Requested block number to check %i.", block_number);
464 
465             /* Error: invalid number of blocks to check */
466             UINT8_TO_STREAM(p_dst, T3T_MSG_RSP_STATUS_ERROR);
467             UINT8_TO_STREAM(p_dst, T3T_MSG_RSP_STATUS2_ERROR_MEMORY);
468             break;
469           } else {
470             /* If card is RW, then read from the scratch buffer (so reader/write
471              * can read back what it had just written */
472             if ((p_cb->ndef_info.rwflag == T3T_MSG_NDEF_RWFLAG_RW) &&
473                 (p_cb->ndef_info.p_scratch_buf)) {
474               ARRAY_TO_STREAM(
475                   p_dst,
476                   (&p_cb->ndef_info
477                         .p_scratch_buf[(block_number - 1) * T3T_MSG_BLOCKSIZE]),
478                   T3T_MSG_BLOCKSIZE);
479             } else {
480               ARRAY_TO_STREAM(
481                   p_dst, (&p_cb->ndef_info
482                                .p_buf[(block_number - 1) * T3T_MSG_BLOCKSIZE]),
483                   T3T_MSG_BLOCKSIZE);
484             }
485           }
486         }
487       } else {
488         /* Error: invalid service code */
489         LOG(ERROR) << StringPrintf(
490             "CE: Requested invalid service code: 0x%04x.", service_code);
491 
492         p_dst = p_status;
493         UINT8_TO_STREAM(p_dst, T3T_MSG_RSP_STATUS_ERROR);
494         UINT8_TO_STREAM(p_dst, T3T_MSG_RSP_STATUS2_ERROR_MEMORY);
495         break;
496       }
497     }
498 
499     p_rsp_msg->len = (uint16_t)(p_dst - p_rsp_start);
500     ce_t3t_send_to_lower(p_rsp_msg);
501   } else {
502     LOG(ERROR) << StringPrintf(
503         "CE: Unable to allocat buffer for response message");
504   }
505 
506   GKI_freebuf(p_cmd_msg);
507 }
508 
509 /*******************************************************************************
510 **
511 ** Function         ce_t3t_handle_non_nfc_forum_cmd
512 **
513 ** Description      Handle POLL command from reader/writer
514 **
515 ** Returns          Nothing
516 **
517 *******************************************************************************/
ce_t3t_handle_non_nfc_forum_cmd(tCE_CB * p_mem_cb,uint8_t cmd_id,NFC_HDR * p_cmd_msg)518 void ce_t3t_handle_non_nfc_forum_cmd(tCE_CB* p_mem_cb, uint8_t cmd_id,
519                                      NFC_HDR* p_cmd_msg) {
520   tCE_T3T_MEM* p_cb = &p_mem_cb->mem.t3t;
521   NFC_HDR* p_rsp_msg;
522   uint8_t* p_rsp_start;
523   uint8_t* p_dst;
524   uint8_t* p = (uint8_t*)(p_cmd_msg + 1) + p_cmd_msg->offset;
525   uint16_t sc;
526   uint8_t rc;
527   bool send_response = true;
528 
529   p_rsp_msg = ce_t3t_get_rsp_buf();
530   if (p_rsp_msg != nullptr) {
531     p_dst = p_rsp_start = (uint8_t*)(p_rsp_msg + 1) + p_rsp_msg->offset;
532 
533     switch (cmd_id) {
534       case T3T_MSG_OPC_POLL_CMD:
535         if (p_cmd_msg->len < 5) {
536           LOG(ERROR) << "Received invalid T3t message";
537           android_errorWriteLog(0x534e4554, "121150966");
538           send_response = false;
539           break;
540         }
541         /* Get system code and RC */
542         /* Skip over sod and cmd_id */
543         p += 2;
544         BE_STREAM_TO_UINT16(sc, p);
545         STREAM_TO_UINT8(rc, p);
546 
547         /* If requesting wildcard system code, or specifically our system code,
548          * then send POLL response */
549         if ((sc == 0xFFFF) || (sc == p_cb->system_code)) {
550           /* Response Code */
551           UINT8_TO_STREAM(p_dst, T3T_MSG_OPC_POLL_RSP);
552 
553           /* Manufacturer ID */
554           ARRAY_TO_STREAM(p_dst, p_cb->local_nfcid2, NCI_RF_F_UID_LEN);
555 
556           /* Manufacturer Parameter PMm */
557           ARRAY_TO_STREAM(p_dst, p_cb->local_pmm, NCI_T3T_PMM_LEN);
558 
559           /* If requesting system code */
560           if (rc == T3T_POLL_RC_SC) {
561             UINT16_TO_BE_STREAM(p_dst, p_cb->system_code);
562           }
563         } else {
564           send_response = false;
565         }
566         break;
567 
568       case T3T_MSG_OPC_REQ_RESPONSE_CMD:
569         /* Response Code */
570         UINT8_TO_STREAM(p_dst, T3T_MSG_OPC_REQ_RESPONSE_RSP);
571 
572         /* Manufacturer ID */
573         ARRAY_TO_STREAM(p_dst, p_cb->local_nfcid2, NCI_RF_F_UID_LEN);
574 
575         /* Mode */
576         UINT8_TO_STREAM(p_dst, 0);
577         break;
578 
579       case T3T_MSG_OPC_REQ_SYSTEMCODE_CMD:
580         /* Response Code */
581         UINT8_TO_STREAM(p_dst, T3T_MSG_OPC_REQ_SYSTEMCODE_RSP);
582 
583         /* Manufacturer ID */
584         ARRAY_TO_STREAM(p_dst, p_cb->local_nfcid2, NCI_RF_F_UID_LEN);
585 
586         /* Number of system codes */
587         UINT8_TO_STREAM(p_dst, 1);
588 
589         /* system codes */
590         UINT16_TO_BE_STREAM(p_dst, T3T_SYSTEM_CODE_NDEF);
591         break;
592 
593       case T3T_MSG_OPC_REQ_SERVICE_CMD:
594       default:
595         /* Unhandled command */
596         LOG(ERROR) << StringPrintf("Unhandled CE opcode: %02x", cmd_id);
597         send_response = false;
598         break;
599     }
600 
601     if (send_response) {
602       p_rsp_msg->len = (uint16_t)(p_dst - p_rsp_start);
603       ce_t3t_send_to_lower(p_rsp_msg);
604     } else {
605       GKI_freebuf(p_rsp_msg);
606     }
607   } else {
608     LOG(ERROR) << StringPrintf(
609         "CE: Unable to allocat buffer for response message");
610   }
611   GKI_freebuf(p_cmd_msg);
612 }
613 
614 /*******************************************************************************
615 **
616 ** Function         ce_t3t_data_cback
617 **
618 ** Description      This callback function receives the data from NFCC.
619 **
620 ** Returns          none
621 **
622 *******************************************************************************/
ce_t3t_data_cback(tNFC_DATA_CEVT * p_data)623 void ce_t3t_data_cback(tNFC_DATA_CEVT* p_data) {
624   tCE_CB* p_ce_cb = &ce_cb;
625   tCE_T3T_MEM* p_cb = &p_ce_cb->mem.t3t;
626   NFC_HDR* p_msg = p_data->p_data;
627   tCE_DATA ce_data;
628   uint8_t cmd_id, bl0, entry_len, i;
629   uint8_t* p_nfcid2 = nullptr;
630   uint8_t* p = (uint8_t*)(p_msg + 1) + p_msg->offset;
631   uint8_t cmd_nfcid2[NCI_RF_F_UID_LEN];
632   uint16_t block_list_start_offset, remaining;
633   bool msg_processed = false;
634   bool block_list_ok;
635   uint8_t sod;
636   uint8_t cmd_type;
637 
638   /* If activate system code is not NDEF, or if no local NDEF contents was set,
639    * then pass data up to the app */
640   if ((p_cb->system_code != T3T_SYSTEM_CODE_NDEF) ||
641       (!p_cb->ndef_info.initialized)) {
642     ce_data.raw_frame.status = p_data->status;
643     ce_data.raw_frame.p_data = p_msg;
644     p_ce_cb->p_cback(CE_T3T_RAW_FRAME_EVT, &ce_data);
645     return;
646   }
647 
648   /* Verify that message contains at least Sod and cmd_id */
649   if (p_msg->len < 2) {
650     LOG(ERROR) << StringPrintf(
651         "CE: received invalid T3t message (invalid length: %i)", p_msg->len);
652   } else {
653     /* Get and validate command opcode */
654     STREAM_TO_UINT8(sod, p);
655     STREAM_TO_UINT8(cmd_id, p);
656 
657     /* Valid command and message length */
658     cmd_type = ce_t3t_is_valid_opcode(cmd_id);
659     if (cmd_type == CE_T3T_COMMAND_INVALID) {
660       LOG(ERROR) << StringPrintf(
661           "CE: received invalid T3t message (invalid command: 0x%02X)", cmd_id);
662     } else if (cmd_type == CE_T3T_COMMAND_FELICA) {
663       ce_t3t_handle_non_nfc_forum_cmd(p_ce_cb, cmd_id, p_msg);
664       msg_processed = true;
665     } else {
666       /* Verify that message contains at least NFCID2 and NUM services */
667       if (p_msg->len < T3T_MSG_CMD_COMMON_HDR_LEN) {
668         LOG(ERROR) << StringPrintf(
669             "CE: received invalid T3t message (invalid length: %i)",
670             p_msg->len);
671       } else {
672         /* Handle NFC_FORUM command (UPDATE or CHECK) */
673         STREAM_TO_ARRAY(cmd_nfcid2, p, NCI_RF_F_UID_LEN);
674         STREAM_TO_UINT8(p_cb->cur_cmd.num_services, p);
675 
676         /* Validate num_services */
677         if (p_cb->cur_cmd.num_services > T3T_MSG_SERVICE_LIST_MAX) {
678           LOG(ERROR) << StringPrintf(
679               "CE: recieved num_services (%i) exceeds maximum (%i)",
680               p_cb->cur_cmd.num_services, T3T_MSG_SERVICE_LIST_MAX);
681         } else {
682           /* Calculate offset of block-list-start */
683           block_list_start_offset =
684               T3T_MSG_CMD_COMMON_HDR_LEN + 2 * p_cb->cur_cmd.num_services + 1;
685 
686           if (p_cb->state == CE_T3T_STATE_NOT_ACTIVATED) {
687             LOG(ERROR) << StringPrintf(
688                 "CE: received command 0x%02X while in bad state (%i))", cmd_id,
689                 p_cb->state);
690           } else if (memcmp(cmd_nfcid2, p_cb->local_nfcid2, NCI_RF_F_UID_LEN) !=
691                      0) {
692             LOG(ERROR) << StringPrintf(
693                 "CE: received invalid T3t message (invalid NFCID2)");
694             p_nfcid2 =
695                 cmd_nfcid2; /* respond with ERROR using the NFCID2 from the
696                                command message */
697           } else if (p_msg->len < block_list_start_offset) {
698             /* Does not have minimum (including number_of_blocks field) */
699             LOG(ERROR) << StringPrintf("CE: incomplete message");
700           } else {
701             /* Parse service code list */
702             for (i = 0; i < p_cb->cur_cmd.num_services; i++) {
703               STREAM_TO_UINT16(p_cb->cur_cmd.service_code_list[i], p);
704             }
705 
706             /* Verify that block list */
707             block_list_ok = true;
708             STREAM_TO_UINT8(p_cb->cur_cmd.num_blocks, p);
709             remaining = p_msg->len - block_list_start_offset;
710             p_cb->cur_cmd.p_block_list_start = p;
711             for (i = 0; i < p_cb->cur_cmd.num_blocks; i++) {
712               /* Each entry is at lease 2 bytes long */
713               if (remaining < 2) {
714                 /* Unexpected end of message (while reading block-list) */
715                 LOG(ERROR) << StringPrintf(
716                     "CE: received invalid T3t message (unexpected end of "
717                     "block-list)");
718                 block_list_ok = false;
719                 break;
720               }
721 
722               /* Get byte0 of block-list entry */
723               bl0 = *p;
724 
725               /* Validate service code index and size of block-list */
726               if ((bl0 & T3T_MSG_SERVICE_LIST_MASK) >=
727                   p_cb->cur_cmd.num_services) {
728                 /* Invalid service code */
729                 LOG(ERROR) << StringPrintf(
730                     "CE: received invalid T3t message (invalid service index: "
731                     "%i)",
732                     (bl0 & T3T_MSG_SERVICE_LIST_MASK));
733                 block_list_ok = false;
734                 break;
735               } else if ((!(bl0 & T3T_MSG_MASK_TWO_BYTE_BLOCK_DESC_FORMAT)) &&
736                          (remaining < 3)) {
737                 /* Unexpected end of message (while reading 3-byte entry) */
738                 LOG(ERROR) << StringPrintf(
739                     "CE: received invalid T3t message (unexpected end of "
740                     "block-list)");
741                 block_list_ok = false;
742                 break;
743               }
744 
745               /* Advance pointers to next block-list entry */
746               entry_len =
747                   (bl0 & T3T_MSG_MASK_TWO_BYTE_BLOCK_DESC_FORMAT) ? 2 : 3;
748               p += entry_len;
749               remaining -= entry_len;
750             }
751 
752             /* Block list is verified. Call CHECK or UPDATE handler */
753             if (block_list_ok) {
754               p_cb->cur_cmd.p_block_data_start = p;
755               if (cmd_id == T3T_MSG_OPC_CHECK_CMD) {
756                 /* This is a CHECK command. Sanity check: there shouldn't be any
757                  * more data remaining after reading block list */
758                 if (remaining) {
759                   LOG(ERROR) << StringPrintf(
760                       "CE: unexpected data after after CHECK command (%u "
761                       "bytes)",
762                       (unsigned int)remaining);
763                 }
764                 ce_t3t_handle_check_cmd(p_ce_cb, p_msg);
765                 msg_processed = true;
766               } else {
767                 /* This is an UPDATE command. See if message contains all the
768                  * expected block data */
769                 if (remaining < p_cb->cur_cmd.num_blocks * T3T_MSG_BLOCKSIZE) {
770                   LOG(ERROR)
771                       << StringPrintf("CE: unexpected end of block-data");
772                 } else {
773                   ce_t3t_handle_update_cmd(p_ce_cb, p_msg);
774                   msg_processed = true;
775                 }
776               }
777             }
778           }
779         }
780       }
781     }
782   }
783 
784   if (!msg_processed) {
785     ce_t3t_send_rsp(p_ce_cb, p_nfcid2, T3T_MSG_OPC_CHECK_RSP,
786                     T3T_MSG_RSP_STATUS_ERROR,
787                     T3T_MSG_RSP_STATUS2_ERROR_PROCESSING);
788     GKI_freebuf(p_msg);
789   }
790 }
791 
792 /*******************************************************************************
793 **
794 ** Function         ce_t3t_conn_cback
795 **
796 ** Description      This callback function receives the events/data from NFCC.
797 **
798 ** Returns          none
799 **
800 *******************************************************************************/
ce_t3t_conn_cback(uint8_t conn_id,tNFC_CONN_EVT event,tNFC_CONN * p_data)801 void ce_t3t_conn_cback(uint8_t conn_id, tNFC_CONN_EVT event,
802                        tNFC_CONN* p_data) {
803   tCE_T3T_MEM* p_cb = &ce_cb.mem.t3t;
804 
805   DLOG_IF(INFO, nfc_debug_enabled)
806       << StringPrintf("ce_t3t_conn_cback: conn_id=%i, evt=%i", conn_id, event);
807 
808   switch (event) {
809     case NFC_CONN_CREATE_CEVT:
810       break;
811 
812     case NFC_CONN_CLOSE_CEVT:
813       p_cb->state = CE_T3T_STATE_NOT_ACTIVATED;
814       break;
815 
816     case NFC_DATA_CEVT:
817       if (p_data->data.status == NFC_STATUS_OK) {
818         ce_t3t_data_cback(&p_data->data);
819       }
820       break;
821 
822     case NFC_DEACTIVATE_CEVT:
823       p_cb->state = CE_T3T_STATE_NOT_ACTIVATED;
824       NFC_SetStaticRfCback(nullptr);
825       break;
826 
827     default:
828       break;
829   }
830 }
831 
832 /*******************************************************************************
833 **
834 ** Function         ce_select_t3t
835 **
836 ** Description      Select Type 3 Tag
837 **
838 ** Returns          NFC_STATUS_OK if success
839 **
840 *******************************************************************************/
ce_select_t3t(uint16_t system_code,uint8_t nfcid2[NCI_RF_F_UID_LEN])841 tNFC_STATUS ce_select_t3t(uint16_t system_code,
842                           uint8_t nfcid2[NCI_RF_F_UID_LEN]) {
843   tCE_T3T_MEM* p_cb = &ce_cb.mem.t3t;
844 
845   DLOG_IF(INFO, nfc_debug_enabled) << __func__;
846 
847   p_cb->state = CE_T3T_STATE_IDLE;
848   p_cb->system_code = system_code;
849   memcpy(p_cb->local_nfcid2, nfcid2, NCI_RF_F_UID_LEN);
850 
851   NFC_SetStaticRfCback(ce_t3t_conn_cback);
852   return NFC_STATUS_OK;
853 }
854 
855 /*******************************************************************************
856 **
857 ** Function         CE_T3tSetLocalNDEFMsg
858 **
859 ** Description      Initialise CE Type 3 Tag with mandatory NDEF message
860 **
861 ** Returns          NFC_STATUS_OK if success
862 **
863 *******************************************************************************/
CE_T3tSetLocalNDEFMsg(bool read_only,uint32_t size_max,uint32_t size_current,uint8_t * p_buf,uint8_t * p_scratch_buf)864 tNFC_STATUS CE_T3tSetLocalNDEFMsg(bool read_only, uint32_t size_max,
865                                   uint32_t size_current, uint8_t* p_buf,
866                                   uint8_t* p_scratch_buf) {
867   tCE_T3T_MEM* p_cb = &ce_cb.mem.t3t;
868 
869   DLOG_IF(INFO, nfc_debug_enabled)
870       << StringPrintf("CE_T3tSetContent: ro=%i, size_max=%i, size_current=%i",
871                       read_only, size_max, size_current);
872 
873   /* Verify scratch buffer was provided if NDEF message is read/write */
874   if ((!read_only) && (!p_scratch_buf)) {
875     LOG(ERROR) << StringPrintf(
876         "p_scratch_buf cannot be NULL if not "
877         "read-only");
878     return NFC_STATUS_FAILED;
879   }
880 
881   /* Check if disabling the local NDEF */
882   if (!p_buf) {
883     p_cb->ndef_info.initialized = false;
884   }
885   /* Save ndef attributes */
886   else {
887     p_cb->ndef_info.initialized = true;
888     p_cb->ndef_info.ln = size_current; /* Current length */
889     p_cb->ndef_info.nmaxb = (uint16_t)(
890         (size_max + 15) / T3T_MSG_BLOCKSIZE); /* Max length (in blocks) */
891     p_cb->ndef_info.rwflag =
892         (read_only) ? T3T_MSG_NDEF_RWFLAG_RO : T3T_MSG_NDEF_RWFLAG_RW;
893     p_cb->ndef_info.writef = T3T_MSG_NDEF_WRITEF_OFF;
894     p_cb->ndef_info.version = 0x10;
895     p_cb->ndef_info.p_buf = p_buf;
896     p_cb->ndef_info.p_scratch_buf = p_scratch_buf;
897 
898     /* Initiate scratch buffer with same contents as read-buffer */
899     if (p_scratch_buf) {
900       p_cb->ndef_info.scratch_ln = p_cb->ndef_info.ln;
901       p_cb->ndef_info.scratch_writef = T3T_MSG_NDEF_WRITEF_OFF;
902       memcpy(p_scratch_buf, p_buf, p_cb->ndef_info.ln);
903     }
904   }
905 
906   return (NFC_STATUS_OK);
907 }
908 
909 /*******************************************************************************
910 **
911 ** Function         CE_T3tSetLocalNDefParams
912 **
913 ** Description      Sets T3T-specific NDEF parameters. (Optional - if not
914 **                  called, then CE will use default parameters)
915 **
916 ** Returns          NFC_STATUS_OK if success
917 **
918 *******************************************************************************/
CE_T3tSetLocalNDefParams(uint8_t nbr,uint8_t nbw)919 tNFC_STATUS CE_T3tSetLocalNDefParams(uint8_t nbr, uint8_t nbw) {
920   tCE_T3T_MEM* p_cb = &ce_cb.mem.t3t;
921 
922   DLOG_IF(INFO, nfc_debug_enabled)
923       << StringPrintf("CE_T3tSetLocalNDefParams: nbr=%i, nbw=%i", nbr, nbw);
924 
925   /* Validate */
926   if ((nbr > T3T_MSG_NUM_BLOCKS_CHECK_MAX) ||
927       (nbw > T3T_MSG_NUM_BLOCKS_UPDATE_MAX) || (nbr < 1) || (nbw < 1)) {
928     LOG(ERROR) << StringPrintf("CE_T3tSetLocalNDefParams: invalid params");
929     return NFC_STATUS_FAILED;
930   }
931 
932   p_cb->ndef_info.nbr = nbr;
933   p_cb->ndef_info.nbw = nbw;
934 
935   return NFC_STATUS_OK;
936 }
937 
938 /*******************************************************************************
939 **
940 ** Function         CE_T3tSendCheckRsp
941 **
942 ** Description      Send CHECK response message
943 **
944 ** Returns          NFC_STATUS_OK if success
945 **
946 *******************************************************************************/
CE_T3tSendCheckRsp(uint8_t status1,uint8_t status2,uint8_t num_blocks,uint8_t * p_block_data)947 tNFC_STATUS CE_T3tSendCheckRsp(uint8_t status1, uint8_t status2,
948                                uint8_t num_blocks, uint8_t* p_block_data) {
949   tCE_T3T_MEM* p_cb = &ce_cb.mem.t3t;
950   tNFC_STATUS retval = NFC_STATUS_OK;
951   NFC_HDR* p_rsp_msg;
952   uint8_t *p_dst, *p_rsp_start;
953 
954   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
955       "CE_T3tCheckRsp: status1=0x%02X, status2=0x%02X, num_blocks=%i", status1,
956       status2, num_blocks);
957 
958   /* Validate num_blocks */
959   if (num_blocks > T3T_MSG_NUM_BLOCKS_CHECK_MAX) {
960     LOG(ERROR) << StringPrintf(
961         "CE_T3tCheckRsp num_blocks (%i) exceeds maximum (%i)", num_blocks,
962         T3T_MSG_NUM_BLOCKS_CHECK_MAX);
963     return (NFC_STATUS_FAILED);
964   }
965 
966   p_rsp_msg = ce_t3t_get_rsp_buf();
967   if (p_rsp_msg != nullptr) {
968     p_dst = p_rsp_start = (uint8_t*)(p_rsp_msg + 1) + p_rsp_msg->offset;
969 
970     /* Response Code */
971     UINT8_TO_STREAM(p_dst, T3T_MSG_OPC_CHECK_RSP);
972 
973     /* Manufacturer ID */
974     ARRAY_TO_STREAM(p_dst, p_cb->local_nfcid2, NCI_RF_F_UID_LEN);
975 
976     /* Status1 and Status2 */
977     UINT8_TO_STREAM(p_dst, status1);
978     UINT8_TO_STREAM(p_dst, status2);
979 
980     if (status1 == T3T_MSG_RSP_STATUS_OK) {
981       UINT8_TO_STREAM(p_dst, num_blocks);
982       ARRAY_TO_STREAM(p_dst, p_block_data, (num_blocks * T3T_MSG_BLOCKSIZE));
983     }
984 
985     p_rsp_msg->len = (uint16_t)(p_dst - p_rsp_start);
986     ce_t3t_send_to_lower(p_rsp_msg);
987   } else {
988     LOG(ERROR) << StringPrintf(
989         "CE: Unable to allocate buffer for response message");
990   }
991 
992   return (retval);
993 }
994 
995 /*******************************************************************************
996 **
997 ** Function         CE_T3tSendUpdateRsp
998 **
999 ** Description      Send UPDATE response message
1000 **
1001 ** Returns          NFC_STATUS_OK if success
1002 **
1003 *******************************************************************************/
CE_T3tSendUpdateRsp(uint8_t status1,uint8_t status2)1004 tNFC_STATUS CE_T3tSendUpdateRsp(uint8_t status1, uint8_t status2) {
1005   tNFC_STATUS retval = NFC_STATUS_OK;
1006   tCE_CB* p_ce_cb = &ce_cb;
1007 
1008   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
1009       "CE_T3tUpdateRsp: status1=0x%02X, status2=0x%02X", status1, status2);
1010   ce_t3t_send_rsp(p_ce_cb, nullptr, T3T_MSG_OPC_UPDATE_RSP, status1, status2);
1011 
1012   return (retval);
1013 }
1014