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 
30 #include "nfc_target.h"
31 
32 #include "bt_types.h"
33 #include "ce_api.h"
34 #include "ce_int.h"
35 #include "trace_api.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 != NULL) {
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 == NULL) {
165     p_nfcid2 = p_cb->local_nfcid2;
166   }
167 
168   p_rsp_msg = ce_t3t_get_rsp_buf();
169   if (p_rsp_msg != NULL) {
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, NULL, 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, NULL, 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, NULL);
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, NULL);
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 != NULL) {
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 (i = 0; i < T3T_MSG_NDEF_ATTR_INFO_SIZE; i++) {
453             checksum += p_temp[i];
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 != NULL) {
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         /* Get system code and RC */
536         /* Skip over sod and cmd_id */
537         p += 2;
538         BE_STREAM_TO_UINT16(sc, p);
539         STREAM_TO_UINT8(rc, p);
540 
541         /* If requesting wildcard system code, or specifically our system code,
542          * then send POLL response */
543         if ((sc == 0xFFFF) || (sc == p_cb->system_code)) {
544           /* Response Code */
545           UINT8_TO_STREAM(p_dst, T3T_MSG_OPC_POLL_RSP);
546 
547           /* Manufacturer ID */
548           ARRAY_TO_STREAM(p_dst, p_cb->local_nfcid2, NCI_RF_F_UID_LEN);
549 
550           /* Manufacturer Parameter PMm */
551           ARRAY_TO_STREAM(p_dst, p_cb->local_pmm, NCI_T3T_PMM_LEN);
552 
553           /* If requesting system code */
554           if (rc == T3T_POLL_RC_SC) {
555             UINT16_TO_BE_STREAM(p_dst, p_cb->system_code);
556           }
557         } else {
558           send_response = false;
559         }
560         break;
561 
562       case T3T_MSG_OPC_REQ_RESPONSE_CMD:
563         /* Response Code */
564         UINT8_TO_STREAM(p_dst, T3T_MSG_OPC_REQ_RESPONSE_RSP);
565 
566         /* Manufacturer ID */
567         ARRAY_TO_STREAM(p_dst, p_cb->local_nfcid2, NCI_RF_F_UID_LEN);
568 
569         /* Mode */
570         UINT8_TO_STREAM(p_dst, 0);
571         break;
572 
573       case T3T_MSG_OPC_REQ_SYSTEMCODE_CMD:
574         /* Response Code */
575         UINT8_TO_STREAM(p_dst, T3T_MSG_OPC_REQ_SYSTEMCODE_RSP);
576 
577         /* Manufacturer ID */
578         ARRAY_TO_STREAM(p_dst, p_cb->local_nfcid2, NCI_RF_F_UID_LEN);
579 
580         /* Number of system codes */
581         UINT8_TO_STREAM(p_dst, 1);
582 
583         /* system codes */
584         UINT16_TO_BE_STREAM(p_dst, T3T_SYSTEM_CODE_NDEF);
585         break;
586 
587       case T3T_MSG_OPC_REQ_SERVICE_CMD:
588       default:
589         /* Unhandled command */
590         LOG(ERROR) << StringPrintf("Unhandled CE opcode: %02x", cmd_id);
591         send_response = false;
592         break;
593     }
594 
595     if (send_response) {
596       p_rsp_msg->len = (uint16_t)(p_dst - p_rsp_start);
597       ce_t3t_send_to_lower(p_rsp_msg);
598     } else {
599       GKI_freebuf(p_rsp_msg);
600     }
601   } else {
602     LOG(ERROR) << StringPrintf(
603         "CE: Unable to allocat buffer for response message");
604   }
605   GKI_freebuf(p_cmd_msg);
606 }
607 
608 /*******************************************************************************
609 **
610 ** Function         ce_t3t_data_cback
611 **
612 ** Description      This callback function receives the data from NFCC.
613 **
614 ** Returns          none
615 **
616 *******************************************************************************/
ce_t3t_data_cback(tNFC_DATA_CEVT * p_data)617 void ce_t3t_data_cback(tNFC_DATA_CEVT* p_data) {
618   tCE_CB* p_ce_cb = &ce_cb;
619   tCE_T3T_MEM* p_cb = &p_ce_cb->mem.t3t;
620   NFC_HDR* p_msg = p_data->p_data;
621   tCE_DATA ce_data;
622   uint8_t cmd_id, bl0, entry_len, i;
623   uint8_t* p_nfcid2 = NULL;
624   uint8_t* p = (uint8_t*)(p_msg + 1) + p_msg->offset;
625   uint8_t cmd_nfcid2[NCI_RF_F_UID_LEN];
626   uint16_t block_list_start_offset, remaining;
627   bool msg_processed = false;
628   bool block_list_ok;
629   uint8_t sod;
630   uint8_t cmd_type;
631 
632   /* If activate system code is not NDEF, or if no local NDEF contents was set,
633    * then pass data up to the app */
634   if ((p_cb->system_code != T3T_SYSTEM_CODE_NDEF) ||
635       (!p_cb->ndef_info.initialized)) {
636     ce_data.raw_frame.status = p_data->status;
637     ce_data.raw_frame.p_data = p_msg;
638     p_ce_cb->p_cback(CE_T3T_RAW_FRAME_EVT, &ce_data);
639     return;
640   }
641 
642   /* Verify that message contains at least Sod and cmd_id */
643   if (p_msg->len < 2) {
644     LOG(ERROR) << StringPrintf(
645         "CE: received invalid T3t message (invalid length: %i)", p_msg->len);
646   } else {
647     /* Get and validate command opcode */
648     STREAM_TO_UINT8(sod, p);
649     STREAM_TO_UINT8(cmd_id, p);
650 
651     /* Valid command and message length */
652     cmd_type = ce_t3t_is_valid_opcode(cmd_id);
653     if (cmd_type == CE_T3T_COMMAND_INVALID) {
654       LOG(ERROR) << StringPrintf(
655           "CE: received invalid T3t message (invalid command: 0x%02X)", cmd_id);
656     } else if (cmd_type == CE_T3T_COMMAND_FELICA) {
657       ce_t3t_handle_non_nfc_forum_cmd(p_ce_cb, cmd_id, p_msg);
658       msg_processed = true;
659     } else {
660       /* Verify that message contains at least NFCID2 and NUM services */
661       if (p_msg->len < T3T_MSG_CMD_COMMON_HDR_LEN) {
662         LOG(ERROR) << StringPrintf(
663             "CE: received invalid T3t message (invalid length: %i)",
664             p_msg->len);
665       } else {
666         /* Handle NFC_FORUM command (UPDATE or CHECK) */
667         STREAM_TO_ARRAY(cmd_nfcid2, p, NCI_RF_F_UID_LEN);
668         STREAM_TO_UINT8(p_cb->cur_cmd.num_services, p);
669 
670         /* Calculate offset of block-list-start */
671         block_list_start_offset =
672             T3T_MSG_CMD_COMMON_HDR_LEN + 2 * p_cb->cur_cmd.num_services + 1;
673 
674         if (p_cb->state == CE_T3T_STATE_NOT_ACTIVATED) {
675           LOG(ERROR) << StringPrintf(
676               "CE: received command 0x%02X while in bad state (%i))", cmd_id,
677               p_cb->state);
678         } else if (memcmp(cmd_nfcid2, p_cb->local_nfcid2, NCI_RF_F_UID_LEN) !=
679                    0) {
680           LOG(ERROR) << StringPrintf(
681               "CE: received invalid T3t message (invalid NFCID2)");
682           p_nfcid2 = cmd_nfcid2; /* respond with ERROR using the NFCID2 from the
683                                     command message */
684         } else if (p_msg->len < block_list_start_offset) {
685           /* Does not have minimum (including number_of_blocks field) */
686           LOG(ERROR) << StringPrintf("CE: incomplete message");
687         } else {
688           /* Parse service code list */
689           for (i = 0; i < p_cb->cur_cmd.num_services; i++) {
690             STREAM_TO_UINT16(p_cb->cur_cmd.service_code_list[i], p);
691           }
692 
693           /* Verify that block list */
694           block_list_ok = true;
695           STREAM_TO_UINT8(p_cb->cur_cmd.num_blocks, p);
696           remaining = p_msg->len - block_list_start_offset;
697           p_cb->cur_cmd.p_block_list_start = p;
698           for (i = 0; i < p_cb->cur_cmd.num_blocks; i++) {
699             /* Each entry is at lease 2 bytes long */
700             if (remaining < 2) {
701               /* Unexpected end of message (while reading block-list) */
702               LOG(ERROR) << StringPrintf(
703                   "CE: received invalid T3t message (unexpected end of "
704                   "block-list)");
705               block_list_ok = false;
706               break;
707             }
708 
709             /* Get byte0 of block-list entry */
710             bl0 = *p;
711 
712             /* Validate service code index and size of block-list */
713             if ((bl0 & T3T_MSG_SERVICE_LIST_MASK) >=
714                 p_cb->cur_cmd.num_services) {
715               /* Invalid service code */
716               LOG(ERROR) << StringPrintf(
717                   "CE: received invalid T3t message (invalid service index: "
718                   "%i)",
719                   (bl0 & T3T_MSG_SERVICE_LIST_MASK));
720               block_list_ok = false;
721               break;
722             } else if ((!(bl0 & T3T_MSG_MASK_TWO_BYTE_BLOCK_DESC_FORMAT)) &&
723                        (remaining < 3)) {
724               /* Unexpected end of message (while reading 3-byte entry) */
725               LOG(ERROR) << StringPrintf(
726                   "CE: received invalid T3t message (unexpected end of "
727                   "block-list)");
728               block_list_ok = false;
729               break;
730             }
731 
732             /* Advance pointers to next block-list entry */
733             entry_len = (bl0 & T3T_MSG_MASK_TWO_BYTE_BLOCK_DESC_FORMAT) ? 2 : 3;
734             p += entry_len;
735             remaining -= entry_len;
736           }
737 
738           /* Block list is verified. Call CHECK or UPDATE handler */
739           if (block_list_ok) {
740             p_cb->cur_cmd.p_block_data_start = p;
741             if (cmd_id == T3T_MSG_OPC_CHECK_CMD) {
742               /* This is a CHECK command. Sanity check: there shouldn't be any
743                * more data remaining after reading block list */
744               if (remaining) {
745                 LOG(ERROR) << StringPrintf(
746                     "CE: unexpected data after after CHECK command (%u bytes)",
747                     (unsigned int)remaining);
748               }
749               ce_t3t_handle_check_cmd(p_ce_cb, p_msg);
750               msg_processed = true;
751             } else {
752               /* This is an UPDATE command. See if message contains all the
753                * expected block data */
754               if (remaining < p_cb->cur_cmd.num_blocks * T3T_MSG_BLOCKSIZE) {
755                 LOG(ERROR) << StringPrintf("CE: unexpected end of block-data");
756               } else {
757                 ce_t3t_handle_update_cmd(p_ce_cb, p_msg);
758                 msg_processed = true;
759               }
760             }
761           }
762         }
763       }
764     }
765   }
766 
767   if (!msg_processed) {
768     ce_t3t_send_rsp(p_ce_cb, p_nfcid2, T3T_MSG_OPC_CHECK_RSP,
769                     T3T_MSG_RSP_STATUS_ERROR,
770                     T3T_MSG_RSP_STATUS2_ERROR_PROCESSING);
771     GKI_freebuf(p_msg);
772   }
773 }
774 
775 /*******************************************************************************
776 **
777 ** Function         ce_t3t_conn_cback
778 **
779 ** Description      This callback function receives the events/data from NFCC.
780 **
781 ** Returns          none
782 **
783 *******************************************************************************/
ce_t3t_conn_cback(uint8_t conn_id,tNFC_CONN_EVT event,tNFC_CONN * p_data)784 void ce_t3t_conn_cback(uint8_t conn_id, tNFC_CONN_EVT event,
785                        tNFC_CONN* p_data) {
786   tCE_T3T_MEM* p_cb = &ce_cb.mem.t3t;
787 
788   DLOG_IF(INFO, nfc_debug_enabled)
789       << StringPrintf("ce_t3t_conn_cback: conn_id=%i, evt=%i", conn_id, event);
790 
791   switch (event) {
792     case NFC_CONN_CREATE_CEVT:
793       break;
794 
795     case NFC_CONN_CLOSE_CEVT:
796       p_cb->state = CE_T3T_STATE_NOT_ACTIVATED;
797       break;
798 
799     case NFC_DATA_CEVT:
800       if (p_data->data.status == NFC_STATUS_OK) {
801         ce_t3t_data_cback(&p_data->data);
802       }
803       break;
804 
805     case NFC_DEACTIVATE_CEVT:
806       p_cb->state = CE_T3T_STATE_NOT_ACTIVATED;
807       NFC_SetStaticRfCback(NULL);
808       break;
809 
810     default:
811       break;
812   }
813 }
814 
815 /*******************************************************************************
816 **
817 ** Function         ce_select_t3t
818 **
819 ** Description      Select Type 3 Tag
820 **
821 ** Returns          NFC_STATUS_OK if success
822 **
823 *******************************************************************************/
ce_select_t3t(uint16_t system_code,uint8_t nfcid2[NCI_RF_F_UID_LEN])824 tNFC_STATUS ce_select_t3t(uint16_t system_code,
825                           uint8_t nfcid2[NCI_RF_F_UID_LEN]) {
826   tCE_T3T_MEM* p_cb = &ce_cb.mem.t3t;
827 
828   DLOG_IF(INFO, nfc_debug_enabled) << __func__;
829 
830   p_cb->state = CE_T3T_STATE_IDLE;
831   p_cb->system_code = system_code;
832   memcpy(p_cb->local_nfcid2, nfcid2, NCI_RF_F_UID_LEN);
833 
834   NFC_SetStaticRfCback(ce_t3t_conn_cback);
835   return NFC_STATUS_OK;
836 }
837 
838 /*******************************************************************************
839 **
840 ** Function         CE_T3tSetLocalNDEFMsg
841 **
842 ** Description      Initialise CE Type 3 Tag with mandatory NDEF message
843 **
844 ** Returns          NFC_STATUS_OK if success
845 **
846 *******************************************************************************/
CE_T3tSetLocalNDEFMsg(bool read_only,uint32_t size_max,uint32_t size_current,uint8_t * p_buf,uint8_t * p_scratch_buf)847 tNFC_STATUS CE_T3tSetLocalNDEFMsg(bool read_only, uint32_t size_max,
848                                   uint32_t size_current, uint8_t* p_buf,
849                                   uint8_t* p_scratch_buf) {
850   tCE_T3T_MEM* p_cb = &ce_cb.mem.t3t;
851 
852   DLOG_IF(INFO, nfc_debug_enabled)
853       << StringPrintf("CE_T3tSetContent: ro=%i, size_max=%i, size_current=%i",
854                       read_only, size_max, size_current);
855 
856   /* Verify scratch buffer was provided if NDEF message is read/write */
857   if ((!read_only) && (!p_scratch_buf)) {
858     LOG(ERROR) << StringPrintf(
859         "p_scratch_buf cannot be NULL if not "
860         "read-only");
861     return NFC_STATUS_FAILED;
862   }
863 
864   /* Check if disabling the local NDEF */
865   if (!p_buf) {
866     p_cb->ndef_info.initialized = false;
867   }
868   /* Save ndef attributes */
869   else {
870     p_cb->ndef_info.initialized = true;
871     p_cb->ndef_info.ln = size_current; /* Current length */
872     p_cb->ndef_info.nmaxb = (uint16_t)(
873         (size_max + 15) / T3T_MSG_BLOCKSIZE); /* Max length (in blocks) */
874     p_cb->ndef_info.rwflag =
875         (read_only) ? T3T_MSG_NDEF_RWFLAG_RO : T3T_MSG_NDEF_RWFLAG_RW;
876     p_cb->ndef_info.writef = T3T_MSG_NDEF_WRITEF_OFF;
877     p_cb->ndef_info.version = 0x10;
878     p_cb->ndef_info.p_buf = p_buf;
879     p_cb->ndef_info.p_scratch_buf = p_scratch_buf;
880 
881     /* Initiate scratch buffer with same contents as read-buffer */
882     if (p_scratch_buf) {
883       p_cb->ndef_info.scratch_ln = p_cb->ndef_info.ln;
884       p_cb->ndef_info.scratch_writef = T3T_MSG_NDEF_WRITEF_OFF;
885       memcpy(p_scratch_buf, p_buf, p_cb->ndef_info.ln);
886     }
887   }
888 
889   return (NFC_STATUS_OK);
890 }
891 
892 /*******************************************************************************
893 **
894 ** Function         CE_T3tSetLocalNDefParams
895 **
896 ** Description      Sets T3T-specific NDEF parameters. (Optional - if not
897 **                  called, then CE will use default parameters)
898 **
899 ** Returns          NFC_STATUS_OK if success
900 **
901 *******************************************************************************/
CE_T3tSetLocalNDefParams(uint8_t nbr,uint8_t nbw)902 tNFC_STATUS CE_T3tSetLocalNDefParams(uint8_t nbr, uint8_t nbw) {
903   tCE_T3T_MEM* p_cb = &ce_cb.mem.t3t;
904 
905   DLOG_IF(INFO, nfc_debug_enabled)
906       << StringPrintf("CE_T3tSetLocalNDefParams: nbr=%i, nbw=%i", nbr, nbw);
907 
908   /* Validate */
909   if ((nbr > T3T_MSG_NUM_BLOCKS_CHECK_MAX) ||
910       (nbw > T3T_MSG_NUM_BLOCKS_UPDATE_MAX) || (nbr < 1) || (nbw < 1)) {
911     LOG(ERROR) << StringPrintf("CE_T3tSetLocalNDefParams: invalid params");
912     return NFC_STATUS_FAILED;
913   }
914 
915   p_cb->ndef_info.nbr = nbr;
916   p_cb->ndef_info.nbw = nbw;
917 
918   return NFC_STATUS_OK;
919 }
920 
921 /*******************************************************************************
922 **
923 ** Function         CE_T3tSendCheckRsp
924 **
925 ** Description      Send CHECK response message
926 **
927 ** Returns          NFC_STATUS_OK if success
928 **
929 *******************************************************************************/
CE_T3tSendCheckRsp(uint8_t status1,uint8_t status2,uint8_t num_blocks,uint8_t * p_block_data)930 tNFC_STATUS CE_T3tSendCheckRsp(uint8_t status1, uint8_t status2,
931                                uint8_t num_blocks, uint8_t* p_block_data) {
932   tCE_T3T_MEM* p_cb = &ce_cb.mem.t3t;
933   tNFC_STATUS retval = NFC_STATUS_OK;
934   NFC_HDR* p_rsp_msg;
935   uint8_t *p_dst, *p_rsp_start;
936 
937   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
938       "CE_T3tCheckRsp: status1=0x%02X, status2=0x%02X, num_blocks=%i", status1,
939       status2, num_blocks);
940 
941   /* Validate num_blocks */
942   if (num_blocks > T3T_MSG_NUM_BLOCKS_CHECK_MAX) {
943     LOG(ERROR) << StringPrintf(
944         "CE_T3tCheckRsp num_blocks (%i) exceeds maximum (%i)", num_blocks,
945         T3T_MSG_NUM_BLOCKS_CHECK_MAX);
946     return (NFC_STATUS_FAILED);
947   }
948 
949   p_rsp_msg = ce_t3t_get_rsp_buf();
950   if (p_rsp_msg != NULL) {
951     p_dst = p_rsp_start = (uint8_t*)(p_rsp_msg + 1) + p_rsp_msg->offset;
952 
953     /* Response Code */
954     UINT8_TO_STREAM(p_dst, T3T_MSG_OPC_CHECK_RSP);
955 
956     /* Manufacturer ID */
957     ARRAY_TO_STREAM(p_dst, p_cb->local_nfcid2, NCI_RF_F_UID_LEN);
958 
959     /* Status1 and Status2 */
960     UINT8_TO_STREAM(p_dst, status1);
961     UINT8_TO_STREAM(p_dst, status2);
962 
963     if (status1 == T3T_MSG_RSP_STATUS_OK) {
964       UINT8_TO_STREAM(p_dst, num_blocks);
965       ARRAY_TO_STREAM(p_dst, p_block_data, (num_blocks * T3T_MSG_BLOCKSIZE));
966     }
967 
968     p_rsp_msg->len = (uint16_t)(p_dst - p_rsp_start);
969     ce_t3t_send_to_lower(p_rsp_msg);
970   } else {
971     LOG(ERROR) << StringPrintf(
972         "CE: Unable to allocate buffer for response message");
973   }
974 
975   return (retval);
976 }
977 
978 /*******************************************************************************
979 **
980 ** Function         CE_T3tSendUpdateRsp
981 **
982 ** Description      Send UPDATE response message
983 **
984 ** Returns          NFC_STATUS_OK if success
985 **
986 *******************************************************************************/
CE_T3tSendUpdateRsp(uint8_t status1,uint8_t status2)987 tNFC_STATUS CE_T3tSendUpdateRsp(uint8_t status1, uint8_t status2) {
988   tNFC_STATUS retval = NFC_STATUS_OK;
989   tCE_CB* p_ce_cb = &ce_cb;
990 
991   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
992       "CE_T3tUpdateRsp: status1=0x%02X, status2=0x%02X", status1, status2);
993   ce_t3t_send_rsp(p_ce_cb, NULL, T3T_MSG_OPC_UPDATE_RSP, status1, status2);
994 
995   return (retval);
996 }
997