• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 1999-2012 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 main GATT client functions
22  *
23  ******************************************************************************/
24 
25 #define LOG_TAG "bluetooth"
26 
27 #include <string.h>
28 
29 #include "bt_target.h"
30 #include "bt_utils.h"
31 #include "gatt_int.h"
32 #include "l2c_api.h"
33 #include "osi/include/allocator.h"
34 #include "osi/include/log.h"
35 #include "osi/include/osi.h"
36 #include "stack/eatt/eatt.h"
37 #include "stack/include/bt_types.h"
38 #include "types/bluetooth/uuid.h"
39 
40 #include <base/logging.h>
41 
42 #define GATT_WRITE_LONG_HDR_SIZE 5 /* 1 opcode + 2 handle + 2 offset */
43 #define GATT_READ_CHAR_VALUE_HDL (GATT_READ_CHAR_VALUE | 0x80)
44 #define GATT_READ_INC_SRV_UUID128 (GATT_DISC_INC_SRVC | 0x90)
45 
46 #define GATT_PREP_WRITE_RSP_MIN_LEN 4
47 #define GATT_NOTIFICATION_MIN_LEN 2
48 #define GATT_WRITE_RSP_MIN_LEN 2
49 #define GATT_INFO_RSP_MIN_LEN 1
50 #define GATT_MTU_RSP_MIN_LEN 2
51 #define GATT_READ_BY_TYPE_RSP_MIN_LEN 1
52 
53 #define L2CAP_PKT_OVERHEAD 4
54 
55 using base::StringPrintf;
56 using bluetooth::Uuid;
57 using bluetooth::eatt::EattExtension;
58 using bluetooth::eatt::EattChannel;
59 
60 /*******************************************************************************
61  *                      G L O B A L      G A T T       D A T A                 *
62  ******************************************************************************/
63 void gatt_send_prepare_write(tGATT_TCB& tcb, tGATT_CLCB* p_clcb);
64 
65 uint8_t disc_type_to_att_opcode[GATT_DISC_MAX] = {
66     0,
67     GATT_REQ_READ_BY_GRP_TYPE, /*  GATT_DISC_SRVC_ALL = 1, */
68     GATT_REQ_FIND_TYPE_VALUE,  /*  GATT_DISC_SRVC_BY_UUID,  */
69     GATT_REQ_READ_BY_TYPE,     /*  GATT_DISC_INC_SRVC,      */
70     GATT_REQ_READ_BY_TYPE,     /*  GATT_DISC_CHAR,          */
71     GATT_REQ_FIND_INFO         /*  GATT_DISC_CHAR_DSCPT,    */
72 };
73 
74 uint16_t disc_type_to_uuid[GATT_DISC_MAX] = {
75     0,                         /* reserved */
76     GATT_UUID_PRI_SERVICE,     /* <service> DISC_SRVC_ALL */
77     GATT_UUID_PRI_SERVICE,     /* <service> for DISC_SERVC_BY_UUID */
78     GATT_UUID_INCLUDE_SERVICE, /* <include_service> for DISC_INC_SRVC */
79     GATT_UUID_CHAR_DECLARE,    /* <characteristic> for DISC_CHAR */
80     0                          /* no type filtering for DISC_CHAR_DSCPT */
81 };
82 
83 /*******************************************************************************
84  *
85  * Function         gatt_act_discovery
86  *
87  * Description      GATT discovery operation.
88  *
89  * Returns          void.
90  *
91  ******************************************************************************/
gatt_act_discovery(tGATT_CLCB * p_clcb)92 void gatt_act_discovery(tGATT_CLCB* p_clcb) {
93   uint8_t op_code = disc_type_to_att_opcode[p_clcb->op_subtype];
94 
95   if (p_clcb->s_handle > p_clcb->e_handle || p_clcb->s_handle == 0) {
96     LOG_DEBUG("Completed GATT discovery of all handle ranges");
97     gatt_end_operation(p_clcb, GATT_SUCCESS, NULL);
98     return;
99   }
100 
101   tGATT_CL_MSG cl_req;
102   memset(&cl_req, 0, sizeof(tGATT_CL_MSG));
103 
104   cl_req.browse.s_handle = p_clcb->s_handle;
105   cl_req.browse.e_handle = p_clcb->e_handle;
106 
107   if (disc_type_to_uuid[p_clcb->op_subtype] != 0) {
108     cl_req.browse.uuid =
109         bluetooth::Uuid::From16Bit(disc_type_to_uuid[p_clcb->op_subtype]);
110   }
111 
112   if (p_clcb->op_subtype ==
113       GATT_DISC_SRVC_BY_UUID) /* fill in the FindByTypeValue request info*/
114   {
115     cl_req.find_type_value.uuid =
116         bluetooth::Uuid::From16Bit(disc_type_to_uuid[p_clcb->op_subtype]);
117     cl_req.find_type_value.s_handle = p_clcb->s_handle;
118     cl_req.find_type_value.e_handle = p_clcb->e_handle;
119 
120     size_t size = p_clcb->uuid.GetShortestRepresentationSize();
121     cl_req.find_type_value.value_len = size;
122     if (size == Uuid::kNumBytes16) {
123       uint8_t* p = cl_req.find_type_value.value;
124       UINT16_TO_STREAM(p, p_clcb->uuid.As16Bit());
125     } else if (size == Uuid::kNumBytes32) {
126       /* if service type is 32 bits UUID, convert it now */
127       memcpy(cl_req.find_type_value.value, p_clcb->uuid.To128BitLE().data(),
128             Uuid::kNumBytes128);
129       cl_req.find_type_value.value_len = Uuid::kNumBytes128;
130     } else
131       memcpy(cl_req.find_type_value.value, p_clcb->uuid.To128BitLE().data(),
132              size);
133   }
134 
135   tGATT_STATUS st = attp_send_cl_msg(*p_clcb->p_tcb, p_clcb, op_code, &cl_req);
136   if (st != GATT_SUCCESS && st != GATT_CMD_STARTED) {
137     LOG_WARN("Unable to send ATT message");
138     gatt_end_operation(p_clcb, GATT_ERROR, NULL);
139   }
140 }
141 
142 /*******************************************************************************
143  *
144  * Function         gatt_act_read
145  *
146  * Description      GATT read operation.
147  *
148  * Returns          void.
149  *
150  ******************************************************************************/
gatt_act_read(tGATT_CLCB * p_clcb,uint16_t offset)151 void gatt_act_read(tGATT_CLCB* p_clcb, uint16_t offset) {
152   tGATT_TCB& tcb = *p_clcb->p_tcb;
153   tGATT_STATUS rt = GATT_INTERNAL_ERROR;
154   tGATT_CL_MSG msg;
155   uint8_t op_code = 0;
156 
157   memset(&msg, 0, sizeof(tGATT_CL_MSG));
158 
159   switch (p_clcb->op_subtype) {
160     case GATT_READ_CHAR_VALUE:
161     case GATT_READ_BY_TYPE:
162       op_code = GATT_REQ_READ_BY_TYPE;
163       msg.browse.s_handle = p_clcb->s_handle;
164       msg.browse.e_handle = p_clcb->e_handle;
165       if (p_clcb->op_subtype == GATT_READ_BY_TYPE)
166         msg.browse.uuid = p_clcb->uuid;
167       else {
168         msg.browse.uuid = bluetooth::Uuid::From16Bit(GATT_UUID_CHAR_DECLARE);
169       }
170       break;
171 
172     case GATT_READ_CHAR_VALUE_HDL:
173     case GATT_READ_BY_HANDLE:
174       if (!p_clcb->counter) {
175         op_code = GATT_REQ_READ;
176         msg.handle = p_clcb->s_handle;
177       } else {
178         if (!p_clcb->first_read_blob_after_read)
179           p_clcb->first_read_blob_after_read = true;
180         else
181           p_clcb->first_read_blob_after_read = false;
182 
183         VLOG(1) << __func__ << ": first_read_blob_after_read="
184                 << p_clcb->first_read_blob_after_read;
185         op_code = GATT_REQ_READ_BLOB;
186         msg.read_blob.offset = offset;
187         msg.read_blob.handle = p_clcb->s_handle;
188       }
189       p_clcb->op_subtype &= ~0x80;
190       break;
191 
192     case GATT_READ_PARTIAL:
193       op_code = GATT_REQ_READ_BLOB;
194       msg.read_blob.handle = p_clcb->s_handle;
195       msg.read_blob.offset = offset;
196       break;
197 
198     case GATT_READ_MULTIPLE:
199       op_code = GATT_REQ_READ_MULTI;
200       memcpy(&msg.read_multi, p_clcb->p_attr_buf, sizeof(tGATT_READ_MULTI));
201       break;
202 
203     case GATT_READ_MULTIPLE_VAR_LEN:
204       op_code = GATT_REQ_READ_MULTI_VAR;
205       memcpy(&msg.read_multi, p_clcb->p_attr_buf, sizeof(tGATT_READ_MULTI));
206       break;
207 
208     case GATT_READ_INC_SRV_UUID128:
209       op_code = GATT_REQ_READ;
210       msg.handle = p_clcb->s_handle;
211       p_clcb->op_subtype &= ~0x90;
212       break;
213 
214     default:
215       LOG(ERROR) << "Unknown read type:" << +p_clcb->op_subtype;
216       break;
217   }
218 
219   if (op_code != 0) rt = attp_send_cl_msg(tcb, p_clcb, op_code, &msg);
220 
221   if (op_code == 0 || (rt != GATT_SUCCESS && rt != GATT_CMD_STARTED)) {
222     gatt_end_operation(p_clcb, rt, NULL);
223   }
224 }
225 
226 /** GATT write operation */
gatt_act_write(tGATT_CLCB * p_clcb,uint8_t sec_act)227 void gatt_act_write(tGATT_CLCB* p_clcb, uint8_t sec_act) {
228   tGATT_TCB& tcb = *p_clcb->p_tcb;
229 
230   CHECK(p_clcb->p_attr_buf);
231   tGATT_VALUE& attr = *((tGATT_VALUE*)p_clcb->p_attr_buf);
232 
233   uint16_t payload_size = gatt_tcb_get_payload_size_tx(tcb, p_clcb->cid);
234 
235   switch (p_clcb->op_subtype) {
236     case GATT_WRITE_NO_RSP: {
237       p_clcb->s_handle = attr.handle;
238       uint8_t op_code = (sec_act == GATT_SEC_SIGN_DATA) ? GATT_SIGN_CMD_WRITE
239                                                         : GATT_CMD_WRITE;
240       tGATT_STATUS rt = gatt_send_write_msg(tcb, p_clcb, op_code, attr.handle,
241                                             attr.len, 0, attr.value);
242       if (rt != GATT_CMD_STARTED) {
243         if (rt != GATT_SUCCESS) {
244           LOG(ERROR) << StringPrintf(
245               "gatt_act_write() failed op_code=0x%x rt=%d", op_code, rt);
246         }
247         gatt_end_operation(p_clcb, rt, NULL);
248       }
249       return;
250     }
251 
252     case GATT_WRITE: {
253       if (attr.len <= (payload_size - GATT_HDR_SIZE)) {
254         p_clcb->s_handle = attr.handle;
255 
256         tGATT_STATUS rt = gatt_send_write_msg(
257             tcb, p_clcb, GATT_REQ_WRITE, attr.handle, attr.len, 0, attr.value);
258         if (rt != GATT_SUCCESS && rt != GATT_CMD_STARTED &&
259             rt != GATT_CONGESTED) {
260           if (rt != GATT_SUCCESS) {
261             LOG(ERROR) << StringPrintf(
262                 "gatt_act_write() failed op_code=0x%x rt=%d", GATT_REQ_WRITE,
263                 rt);
264           }
265           gatt_end_operation(p_clcb, rt, NULL);
266         }
267 
268       } else {
269         /* prepare write for long attribute */
270         gatt_send_prepare_write(tcb, p_clcb);
271       }
272       return;
273     }
274 
275     case GATT_WRITE_PREPARE:
276       gatt_send_prepare_write(tcb, p_clcb);
277       return;
278 
279     default:
280       CHECK(false) << "Unknown write type" << p_clcb->op_subtype;
281       return;
282   }
283 }
284 /*******************************************************************************
285  *
286  * Function         gatt_send_queue_write_cancel
287  *
288  * Description      send queue write cancel
289  *
290  * Returns          void.
291  *
292  ******************************************************************************/
gatt_send_queue_write_cancel(tGATT_TCB & tcb,tGATT_CLCB * p_clcb,tGATT_EXEC_FLAG flag)293 void gatt_send_queue_write_cancel(tGATT_TCB& tcb, tGATT_CLCB* p_clcb,
294                                   tGATT_EXEC_FLAG flag) {
295   tGATT_STATUS rt;
296 
297   VLOG(1) << __func__;
298 
299   tGATT_CL_MSG gatt_cl_msg;
300   gatt_cl_msg.exec_write = flag;
301   rt = attp_send_cl_msg(tcb, p_clcb, GATT_REQ_EXEC_WRITE, &gatt_cl_msg);
302 
303   if (rt != GATT_SUCCESS) {
304     gatt_end_operation(p_clcb, rt, NULL);
305   }
306 }
307 /*******************************************************************************
308  *
309  * Function         gatt_check_write_long_terminate
310  *
311  * Description      To terminate write long or not.
312  *
313  * Returns          true: write long is terminated; false keep sending.
314  *
315  ******************************************************************************/
gatt_check_write_long_terminate(tGATT_TCB & tcb,tGATT_CLCB * p_clcb,tGATT_VALUE * p_rsp_value)316 bool gatt_check_write_long_terminate(tGATT_TCB& tcb, tGATT_CLCB* p_clcb,
317                                      tGATT_VALUE* p_rsp_value) {
318   tGATT_VALUE* p_attr = (tGATT_VALUE*)p_clcb->p_attr_buf;
319   bool terminate = false;
320   tGATT_EXEC_FLAG flag = GATT_PREP_WRITE_EXEC;
321 
322   VLOG(1) << __func__;
323   /* check the first write response status */
324   if (p_rsp_value != NULL) {
325     if (p_rsp_value->handle != p_attr->handle ||
326         p_rsp_value->len != p_clcb->counter ||
327         memcmp(p_rsp_value->value, p_attr->value + p_attr->offset,
328                p_rsp_value->len)) {
329       /* data does not match    */
330       p_clcb->status = GATT_ERROR;
331       flag = GATT_PREP_WRITE_CANCEL;
332       terminate = true;
333     } else /* response checking is good */
334     {
335       p_clcb->status = GATT_SUCCESS;
336       /* update write offset and check if end of attribute value */
337       if ((p_attr->offset += p_rsp_value->len) >= p_attr->len) terminate = true;
338     }
339   }
340   if (terminate && p_clcb->op_subtype != GATT_WRITE_PREPARE) {
341     gatt_send_queue_write_cancel(tcb, p_clcb, flag);
342   }
343   return terminate;
344 }
345 
346 /** Send prepare write */
gatt_send_prepare_write(tGATT_TCB & tcb,tGATT_CLCB * p_clcb)347 void gatt_send_prepare_write(tGATT_TCB& tcb, tGATT_CLCB* p_clcb) {
348   tGATT_VALUE* p_attr = (tGATT_VALUE*)p_clcb->p_attr_buf;
349   uint8_t type = p_clcb->op_subtype;
350 
351   VLOG(1) << __func__ << StringPrintf(" type=0x%x", type);
352   uint16_t to_send = p_attr->len - p_attr->offset;
353 
354   uint16_t payload_size = gatt_tcb_get_payload_size_tx(tcb, p_clcb->cid);
355   if (to_send > (payload_size -
356                  GATT_WRITE_LONG_HDR_SIZE)) /* 2 = uint16_t offset bytes  */
357     to_send = payload_size - GATT_WRITE_LONG_HDR_SIZE;
358 
359   p_clcb->s_handle = p_attr->handle;
360 
361   uint16_t offset = p_attr->offset;
362   if (type == GATT_WRITE_PREPARE) {
363     offset += p_clcb->start_offset;
364   }
365 
366   VLOG(1) << StringPrintf("offset =0x%x len=%d", offset, to_send);
367 
368   tGATT_STATUS rt = gatt_send_write_msg(
369       tcb, p_clcb, GATT_REQ_PREPARE_WRITE, p_attr->handle, to_send, /* length */
370       offset,                          /* used as offset */
371       p_attr->value + p_attr->offset); /* data */
372 
373   /* remember the write long attribute length */
374   p_clcb->counter = to_send;
375 
376   if (rt != GATT_SUCCESS && rt != GATT_CMD_STARTED && rt != GATT_CONGESTED) {
377     gatt_end_operation(p_clcb, rt, NULL);
378   }
379 }
380 
381 /*******************************************************************************
382  *
383  * Function         gatt_process_find_type_value_rsp
384  *
385  * Description      This function handles the find by type value response.
386  *
387  *
388  * Returns          void
389  *
390  ******************************************************************************/
gatt_process_find_type_value_rsp(UNUSED_ATTR tGATT_TCB & tcb,tGATT_CLCB * p_clcb,uint16_t len,uint8_t * p_data)391 void gatt_process_find_type_value_rsp(UNUSED_ATTR tGATT_TCB& tcb,
392                                       tGATT_CLCB* p_clcb, uint16_t len,
393                                       uint8_t* p_data) {
394   tGATT_DISC_RES result;
395   uint8_t* p = p_data;
396 
397   VLOG(1) << __func__;
398   /* unexpected response */
399   if (p_clcb->operation != GATTC_OPTYPE_DISCOVERY ||
400       p_clcb->op_subtype != GATT_DISC_SRVC_BY_UUID)
401     return;
402 
403   memset(&result, 0, sizeof(tGATT_DISC_RES));
404   result.type = bluetooth::Uuid::From16Bit(GATT_UUID_PRI_SERVICE);
405 
406   /* returns a series of handle ranges */
407   while (len >= 4) {
408     STREAM_TO_UINT16(result.handle, p);
409     STREAM_TO_UINT16(result.value.group_value.e_handle, p);
410     result.value.group_value.service_type = p_clcb->uuid;
411 
412     len -= 4;
413 
414     if (p_clcb->p_reg->app_cb.p_disc_res_cb)
415       (*p_clcb->p_reg->app_cb.p_disc_res_cb)(
416           p_clcb->conn_id, static_cast<tGATT_DISC_TYPE>(p_clcb->op_subtype),
417           &result);
418   }
419 
420   /* last handle  + 1 */
421   p_clcb->s_handle = (result.value.group_value.e_handle == 0)
422                          ? 0
423                          : (result.value.group_value.e_handle + 1);
424   /* initiate another request */
425   gatt_act_discovery(p_clcb);
426 }
427 /*******************************************************************************
428  *
429  * Function         gatt_process_read_info_rsp
430  *
431  * Description      This function is called to handle the read information
432  *                  response.
433  *
434  *
435  * Returns          void
436  *
437  ******************************************************************************/
gatt_process_read_info_rsp(UNUSED_ATTR tGATT_TCB & tcb,tGATT_CLCB * p_clcb,UNUSED_ATTR uint8_t op_code,uint16_t len,uint8_t * p_data)438 void gatt_process_read_info_rsp(UNUSED_ATTR tGATT_TCB& tcb, tGATT_CLCB* p_clcb,
439                                 UNUSED_ATTR uint8_t op_code, uint16_t len,
440                                 uint8_t* p_data) {
441   tGATT_DISC_RES result;
442   uint8_t *p = p_data, uuid_len = 0, type;
443 
444   if (len < GATT_INFO_RSP_MIN_LEN) {
445     LOG(ERROR) << "invalid Info Response PDU received, discard.";
446     gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL);
447     return;
448   }
449   /* unexpected response */
450   if (p_clcb->operation != GATTC_OPTYPE_DISCOVERY ||
451       p_clcb->op_subtype != GATT_DISC_CHAR_DSCPT)
452     return;
453 
454   STREAM_TO_UINT8(type, p);
455   len -= 1;
456 
457   if (type == GATT_INFO_TYPE_PAIR_16)
458     uuid_len = Uuid::kNumBytes16;
459   else if (type == GATT_INFO_TYPE_PAIR_128)
460     uuid_len = Uuid::kNumBytes128;
461 
462   while (len >= uuid_len + 2) {
463     STREAM_TO_UINT16(result.handle, p);
464 
465     if (uuid_len > 0) {
466       if (!gatt_parse_uuid_from_cmd(&result.type, uuid_len, &p)) break;
467     } else
468       result.type = p_clcb->uuid;
469 
470     len -= (uuid_len + 2);
471 
472     if (p_clcb->p_reg->app_cb.p_disc_res_cb)
473       (*p_clcb->p_reg->app_cb.p_disc_res_cb)(
474           p_clcb->conn_id, static_cast<tGATT_DISC_TYPE>(p_clcb->op_subtype),
475           &result);
476   }
477 
478   p_clcb->s_handle = (result.handle == 0) ? 0 : (result.handle + 1);
479   /* initiate another request */
480   gatt_act_discovery(p_clcb);
481 }
482 /*******************************************************************************
483  *
484  * Function         gatt_proc_disc_error_rsp
485  *
486  * Description      Process the read by type response and send another request
487  *                  if needed.
488  *
489  * Returns          void.
490  *
491  ******************************************************************************/
gatt_proc_disc_error_rsp(UNUSED_ATTR tGATT_TCB & tcb,tGATT_CLCB * p_clcb,uint8_t opcode,UNUSED_ATTR uint16_t handle,uint8_t reason)492 void gatt_proc_disc_error_rsp(UNUSED_ATTR tGATT_TCB& tcb, tGATT_CLCB* p_clcb,
493                               uint8_t opcode, UNUSED_ATTR uint16_t handle,
494                               uint8_t reason) {
495   tGATT_STATUS status = (tGATT_STATUS)reason;
496 
497   VLOG(1) << __func__
498           << StringPrintf("reason: %02x cmd_code %04x", reason, opcode);
499 
500   switch (opcode) {
501     case GATT_REQ_READ_BY_GRP_TYPE:
502     case GATT_REQ_FIND_TYPE_VALUE:
503     case GATT_REQ_READ_BY_TYPE:
504     case GATT_REQ_FIND_INFO:
505       if (reason == GATT_NOT_FOUND) {
506         status = GATT_SUCCESS;
507         VLOG(1) << "Discovery completed";
508       }
509       break;
510     default:
511       LOG(ERROR) << StringPrintf("Incorrect discovery opcode %04x", opcode);
512       break;
513   }
514 
515   gatt_end_operation(p_clcb, status, NULL);
516 }
517 
518 /*******************************************************************************
519  *
520  * Function         gatt_process_error_rsp
521  *
522  * Description      This function is called to handle the error response
523  *
524  *
525  * Returns          void
526  *
527  ******************************************************************************/
gatt_process_error_rsp(tGATT_TCB & tcb,tGATT_CLCB * p_clcb,UNUSED_ATTR uint8_t op_code,UNUSED_ATTR uint16_t len,uint8_t * p_data)528 void gatt_process_error_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb,
529                             UNUSED_ATTR uint8_t op_code,
530                             UNUSED_ATTR uint16_t len, uint8_t* p_data) {
531   uint8_t opcode, *p = p_data;
532   uint8_t reason;
533   uint16_t handle;
534   tGATT_VALUE* p_attr = (tGATT_VALUE*)p_clcb->p_attr_buf;
535 
536   VLOG(1) << __func__;
537 
538   if (len < 4) {
539     LOG(ERROR) << "Error response too short";
540     // Specification does not clearly define what should happen if error
541     // response is too short. General rule in BT Spec 5.0 Vol 3, Part F 3.4.1.1
542     // is: "If an error code is received in the Error Response that is not
543     // understood by the client, for example an error code that was reserved for
544     // future use that is now being used in a future version of this
545     // specification, then the Error Response shall still be considered to state
546     // that the given request cannot be performed for an unknown reason."
547     opcode = handle = 0;
548     reason = static_cast<tGATT_STATUS>(0x7f);
549   } else {
550     STREAM_TO_UINT8(opcode, p);
551     STREAM_TO_UINT16(handle, p);
552     STREAM_TO_UINT8(reason, p);
553   }
554 
555   if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY) {
556     gatt_proc_disc_error_rsp(tcb, p_clcb, opcode, handle,
557                              static_cast<tGATT_STATUS>(reason));
558   } else {
559     if ((p_clcb->operation == GATTC_OPTYPE_WRITE) &&
560         (p_clcb->op_subtype == GATT_WRITE) &&
561         (opcode == GATT_REQ_PREPARE_WRITE) && (p_attr) &&
562         (handle == p_attr->handle)) {
563       p_clcb->status = static_cast<tGATT_STATUS>(reason);
564       gatt_send_queue_write_cancel(tcb, p_clcb, GATT_PREP_WRITE_CANCEL);
565     } else if ((p_clcb->operation == GATTC_OPTYPE_READ) &&
566                ((p_clcb->op_subtype == GATT_READ_CHAR_VALUE_HDL) ||
567                 (p_clcb->op_subtype == GATT_READ_BY_HANDLE)) &&
568                (opcode == GATT_REQ_READ_BLOB) &&
569                p_clcb->first_read_blob_after_read &&
570                (reason == GATT_NOT_LONG)) {
571       gatt_end_operation(p_clcb, GATT_SUCCESS, (void*)p_clcb->p_attr_buf);
572     } else
573       gatt_end_operation(p_clcb, static_cast<tGATT_STATUS>(reason), NULL);
574   }
575 }
576 /*******************************************************************************
577  *
578  * Function         gatt_process_prep_write_rsp
579  *
580  * Description      This function is called to handle the read response
581  *
582  *
583  * Returns          void
584  *
585  ******************************************************************************/
gatt_process_prep_write_rsp(tGATT_TCB & tcb,tGATT_CLCB * p_clcb,uint8_t op_code,uint16_t len,uint8_t * p_data)586 void gatt_process_prep_write_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb,
587                                  uint8_t op_code, uint16_t len,
588                                  uint8_t* p_data) {
589   uint8_t* p = p_data;
590 
591   tGATT_VALUE value = {
592       .conn_id = p_clcb->conn_id, .auth_req = GATT_AUTH_REQ_NONE,
593   };
594 
595   VLOG(1) << StringPrintf("value resp op_code = %s len = %d",
596                           gatt_dbg_op_name(op_code), len);
597 
598   if (len < GATT_PREP_WRITE_RSP_MIN_LEN ||
599       len > GATT_PREP_WRITE_RSP_MIN_LEN + sizeof(value.value)) {
600     LOG(ERROR) << "illegal prepare write response length, discard";
601     gatt_end_operation(p_clcb, GATT_INVALID_PDU, &value);
602     return;
603   }
604 
605   STREAM_TO_UINT16(value.handle, p);
606   STREAM_TO_UINT16(value.offset, p);
607 
608   value.len = len - GATT_PREP_WRITE_RSP_MIN_LEN;
609 
610   memcpy(value.value, p, value.len);
611 
612   if (!gatt_check_write_long_terminate(tcb, p_clcb, &value)) {
613     gatt_send_prepare_write(tcb, p_clcb);
614     return;
615   }
616 
617   if (p_clcb->op_subtype == GATT_WRITE_PREPARE) {
618     /* application should verify handle offset
619        and value are matched or not */
620     gatt_end_operation(p_clcb, p_clcb->status, &value);
621   }
622 }
623 
624 /*******************************************************************************
625  *
626  * Function         gatt_process_notification
627  *
628  * Description      Handle the handle value indication/notification.
629  *
630  * Returns          void
631  *
632  ******************************************************************************/
gatt_process_notification(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t len,uint8_t * p_data)633 void gatt_process_notification(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code,
634                                uint16_t len, uint8_t* p_data) {
635   tGATT_VALUE value = {};
636   tGATT_REG* p_reg;
637   uint16_t conn_id;
638   tGATT_STATUS encrypt_status = {};
639   uint8_t* p = p_data;
640   uint8_t i;
641   tGATTC_OPTYPE event = (op_code == GATT_HANDLE_VALUE_IND)
642                             ? GATTC_OPTYPE_INDICATION
643                             : GATTC_OPTYPE_NOTIFICATION;
644 
645   VLOG(1) << __func__;
646 
647   // Ensure our packet has enough data (2 bytes)
648   if (len < GATT_NOTIFICATION_MIN_LEN) {
649     LOG(ERROR) << "illegal notification PDU length, discard";
650     return;
651   }
652 
653   // Get 2 byte handle
654   STREAM_TO_UINT16(value.handle, p);
655 
656   // Fail early if the GATT handle is not valid
657   if (!GATT_HANDLE_IS_VALID(value.handle)) {
658     /* illegal handle, send ack now */
659     if (op_code == GATT_HANDLE_VALUE_IND)
660       attp_send_cl_confirmation_msg(tcb, cid);
661     return;
662   }
663 
664   // Calculate value length based on opcode
665   if (op_code == GATT_HANDLE_MULTI_VALUE_NOTIF) {
666     // Ensure our packet has enough data; MIN + 2 more bytes for len value
667     if (len < GATT_NOTIFICATION_MIN_LEN + 2) {
668       LOG(ERROR) << "illegal notification PDU length, discard";
669       return;
670     }
671 
672     // Allow multi value opcode to set value len from the packet
673     STREAM_TO_UINT16(value.len, p);
674 
675     if (value.len > len - 4) {
676       LOG(ERROR) << "value.len (" << value.len << ") greater than length ("
677                  << (len - 4);
678       return;
679     }
680 
681   } else {
682     // For single value, just use the passed in len minus opcode length (2)
683     value.len = len - 2;
684   }
685 
686   // Verify the new calculated length
687   if (value.len > GATT_MAX_ATTR_LEN) {
688     LOG(ERROR) << "value.len larger than GATT_MAX_ATTR_LEN, discard";
689     return;
690   }
691 
692   // Handle indications differently
693   if (event == GATTC_OPTYPE_INDICATION) {
694     if (tcb.ind_count) {
695       /* this is an error case that receiving an indication but we
696          still has an indication not being acked yet.
697          For now, just log the error reset the counter.
698          Later we need to disconnect the link unconditionally.
699       */
700       LOG(ERROR) << __func__ << " rcv Ind. but ind_count=" << tcb.ind_count
701                  << " (will reset ind_count)";
702     }
703 
704     // Zero out the ind_count
705     tcb.ind_count = 0;
706 
707     // Notify all registered clients with the handle value
708     // notification/indication
709     // Note: need to do the indication count and start timer first then do
710     // callback
711     for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) {
712       if (p_reg->in_use && p_reg->app_cb.p_cmpl_cb) tcb.ind_count++;
713     }
714 
715     /* start a timer for app confirmation */
716     if (tcb.ind_count > 0) {
717       gatt_start_ind_ack_timer(tcb, cid);
718     } else { /* no app to indicate, or invalid handle */
719       attp_send_cl_confirmation_msg(tcb, cid);
720     }
721   }
722 
723   encrypt_status = gatt_get_link_encrypt_status(tcb);
724 
725   STREAM_TO_ARRAY(value.value, p, value.len);
726 
727   tGATT_CL_COMPLETE gatt_cl_complete;
728   gatt_cl_complete.att_value = value;
729   gatt_cl_complete.cid = cid;
730 
731   for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) {
732     if (p_reg->in_use && p_reg->app_cb.p_cmpl_cb) {
733       conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, p_reg->gatt_if);
734       (*p_reg->app_cb.p_cmpl_cb)(conn_id, event, encrypt_status,
735                                  &gatt_cl_complete);
736     }
737   }
738 
739   // If this is single value, then nothing is left to do
740   if (op_code != GATT_HANDLE_MULTI_VALUE_NOTIF) return;
741 
742   // Need a signed type to check if the value is below 0
743   // as uint16_t doesn't have negatives so the negatives register as a number
744   // thus anything less than zero won't trigger the conditional and it is not
745   // always 0
746   // when done looping as value.len is arbitrary.
747   int16_t rem_len = (int16_t)len - (4 /* octets */ + value.len);
748 
749   // Already streamed the first value and sent it, lets send the rest
750   while (rem_len > 4 /* octets */) {
751     // 2
752     STREAM_TO_UINT16(value.handle, p);
753     // + 2 = 4
754     STREAM_TO_UINT16(value.len, p);
755     // Accounting
756     rem_len -= 4;
757     // Make sure we don't read past the remaining data even if the length says
758     // we can Also need to watch comparing the int16_t with the uint16_t
759     value.len = std::min((uint16_t)rem_len, value.len);
760     STREAM_TO_ARRAY(value.value, p, value.len);
761     // Accounting
762     rem_len -= value.len;
763 
764     gatt_cl_complete.att_value = value;
765     gatt_cl_complete.cid = cid;
766 
767     for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) {
768       if (p_reg->in_use && p_reg->app_cb.p_cmpl_cb) {
769         conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, p_reg->gatt_if);
770         (*p_reg->app_cb.p_cmpl_cb)(conn_id, event, encrypt_status,
771                                    &gatt_cl_complete);
772       }
773     }
774   }
775 }
776 
777 /*******************************************************************************
778  *
779  * Function         gatt_process_read_by_type_rsp
780  *
781  * Description      This function is called to handle the read by type response.
782  *                  read by type can be used for discovery, or read by type or
783  *                  read characteristic value.
784  *
785  * Returns          void
786  *
787  ******************************************************************************/
gatt_process_read_by_type_rsp(tGATT_TCB & tcb,tGATT_CLCB * p_clcb,uint8_t op_code,uint16_t len,uint8_t * p_data)788 void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb,
789                                    uint8_t op_code, uint16_t len,
790                                    uint8_t* p_data) {
791   tGATT_DISC_RES result;
792   tGATT_DISC_VALUE record_value;
793   uint8_t *p = p_data, value_len, handle_len = 2;
794   uint16_t handle = 0;
795 
796   /* discovery procedure and no callback function registered */
797   if (((!p_clcb->p_reg) || (!p_clcb->p_reg->app_cb.p_disc_res_cb)) &&
798       (p_clcb->operation == GATTC_OPTYPE_DISCOVERY))
799     return;
800 
801   if (len < GATT_READ_BY_TYPE_RSP_MIN_LEN) {
802     LOG(ERROR) << "Illegal ReadByType/ReadByGroupType Response length, discard";
803     gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL);
804     return;
805   }
806 
807   STREAM_TO_UINT8(value_len, p);
808   uint16_t payload_size = gatt_tcb_get_payload_size_rx(tcb, p_clcb->cid);
809   if ((value_len > (payload_size - 2)) || (value_len > (len - 1))) {
810     /* this is an error case that server's response containing a value length
811        which is larger than MTU-2
812        or value_len > message total length -1 */
813     LOG(ERROR) << __func__
814                << StringPrintf(
815                       ": Discard response op_code=%d "
816                       "vale_len=%d > (MTU-2=%d or msg_len-1=%d)",
817                       op_code, value_len, (payload_size - 2), (len - 1));
818     gatt_end_operation(p_clcb, GATT_ERROR, NULL);
819     return;
820   }
821 
822   if (op_code == GATT_RSP_READ_BY_GRP_TYPE) handle_len = 4;
823 
824   value_len -= handle_len; /* substract the handle pairs bytes */
825   len -= 1;
826 
827   while (len >= (handle_len + value_len)) {
828     STREAM_TO_UINT16(handle, p);
829 
830     if (!GATT_HANDLE_IS_VALID(handle)) {
831       gatt_end_operation(p_clcb, GATT_INVALID_HANDLE, NULL);
832       return;
833     }
834 
835     memset(&result, 0, sizeof(tGATT_DISC_RES));
836     memset(&record_value, 0, sizeof(tGATT_DISC_VALUE));
837 
838     result.handle = handle;
839     result.type =
840         bluetooth::Uuid::From16Bit(disc_type_to_uuid[p_clcb->op_subtype]);
841 
842     /* discover all services */
843     if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY &&
844         p_clcb->op_subtype == GATT_DISC_SRVC_ALL &&
845         op_code == GATT_RSP_READ_BY_GRP_TYPE) {
846       STREAM_TO_UINT16(handle, p);
847 
848       if (!GATT_HANDLE_IS_VALID(handle)) {
849         gatt_end_operation(p_clcb, GATT_INVALID_HANDLE, NULL);
850         return;
851       } else {
852         record_value.group_value.e_handle = handle;
853         if (!gatt_parse_uuid_from_cmd(&record_value.group_value.service_type,
854                                       value_len, &p)) {
855           LOG(ERROR) << "discover all service response parsing failure";
856           break;
857         }
858       }
859     }
860     /* discover included service */
861     else if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY &&
862              p_clcb->op_subtype == GATT_DISC_INC_SRVC) {
863       if (value_len < 4) {
864         LOG(ERROR) << __func__ << " Illegal Response length, must be at least 4.";
865         gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL);
866         return;
867       }
868       STREAM_TO_UINT16(record_value.incl_service.s_handle, p);
869       STREAM_TO_UINT16(record_value.incl_service.e_handle, p);
870 
871       if (!GATT_HANDLE_IS_VALID(record_value.incl_service.s_handle) ||
872           !GATT_HANDLE_IS_VALID(record_value.incl_service.e_handle)) {
873         gatt_end_operation(p_clcb, GATT_INVALID_HANDLE, NULL);
874         return;
875       }
876 
877       if (value_len == 6) {
878         uint16_t tmp;
879         STREAM_TO_UINT16(tmp, p);
880         record_value.incl_service.service_type =
881             bluetooth::Uuid::From16Bit(tmp);
882       } else if (value_len == 4) {
883         p_clcb->s_handle = record_value.incl_service.s_handle;
884         p_clcb->read_uuid128.wait_for_read_rsp = true;
885         p_clcb->read_uuid128.next_disc_start_hdl = handle + 1;
886         memcpy(&p_clcb->read_uuid128.result, &result, sizeof(result));
887         memcpy(&p_clcb->read_uuid128.result.value, &record_value,
888                sizeof(result.value));
889         p_clcb->op_subtype |= 0x90;
890         gatt_act_read(p_clcb, 0);
891         return;
892       } else {
893         LOG(ERROR) << __func__
894                    << ": INCL_SRVC failed with invalid data value_len="
895                    << +value_len;
896         gatt_end_operation(p_clcb, GATT_INVALID_PDU, (void*)p);
897         return;
898       }
899     }
900     /* read by type */
901     else if (p_clcb->operation == GATTC_OPTYPE_READ &&
902              p_clcb->op_subtype == GATT_READ_BY_TYPE) {
903       p_clcb->counter = len - 2;
904       p_clcb->s_handle = handle;
905       if (p_clcb->counter == (payload_size - 4)) {
906         p_clcb->op_subtype = GATT_READ_BY_HANDLE;
907         if (!p_clcb->p_attr_buf)
908           p_clcb->p_attr_buf = (uint8_t*)osi_malloc(GATT_MAX_ATTR_LEN);
909         if (p_clcb->counter <= GATT_MAX_ATTR_LEN) {
910           memcpy(p_clcb->p_attr_buf, p, p_clcb->counter);
911           gatt_act_read(p_clcb, p_clcb->counter);
912         } else {
913           gatt_end_operation(p_clcb, GATT_INTERNAL_ERROR, (void*)p);
914         }
915       } else {
916         gatt_end_operation(p_clcb, GATT_SUCCESS, (void*)p);
917       }
918       return;
919     } else /* discover characterisitic */
920     {
921       if (value_len < 3) {
922         LOG(ERROR) << __func__ << " Illegal Response length, must be at least 3.";
923         gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL);
924         return;
925       }
926       STREAM_TO_UINT8(record_value.dclr_value.char_prop, p);
927       STREAM_TO_UINT16(record_value.dclr_value.val_handle, p);
928       if (!GATT_HANDLE_IS_VALID(record_value.dclr_value.val_handle)) {
929         gatt_end_operation(p_clcb, GATT_INVALID_HANDLE, NULL);
930         return;
931       }
932       if (!gatt_parse_uuid_from_cmd(&record_value.dclr_value.char_uuid,
933                                     (uint16_t)(value_len - 3), &p)) {
934         gatt_end_operation(p_clcb, GATT_SUCCESS, NULL);
935         /* invalid format, and skip the result */
936         return;
937       }
938 
939       /* UUID not matching */
940       if (!p_clcb->uuid.IsEmpty() &&
941           !record_value.dclr_value.char_uuid.IsEmpty() &&
942           record_value.dclr_value.char_uuid != p_clcb->uuid) {
943         len -= (value_len + 2);
944         continue; /* skip the result, and look for next one */
945       }
946 
947       if (p_clcb->operation == GATTC_OPTYPE_READ)
948       /* UUID match for read characteristic value */
949       {
950         /* only read the first matching UUID characteristic value, and
951           discard the rest results */
952         p_clcb->s_handle = record_value.dclr_value.val_handle;
953         p_clcb->op_subtype |= 0x80;
954         gatt_act_read(p_clcb, 0);
955         return;
956       }
957     }
958     len -= (value_len + handle_len);
959 
960     /* result is (handle, 16bits UUID) pairs */
961     memcpy(&result.value, &record_value, sizeof(result.value));
962 
963     /* send callback if is discover procedure */
964     if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY &&
965         p_clcb->p_reg->app_cb.p_disc_res_cb)
966       (*p_clcb->p_reg->app_cb.p_disc_res_cb)(
967           p_clcb->conn_id, static_cast<tGATT_DISC_TYPE>(p_clcb->op_subtype),
968           &result);
969   }
970 
971   p_clcb->s_handle = (handle == 0) ? 0 : (handle + 1);
972 
973   if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY) {
974     /* initiate another request */
975     gatt_act_discovery(p_clcb);
976   } else /* read characteristic value */
977   {
978     gatt_act_read(p_clcb, 0);
979   }
980 }
981 
982 /*******************************************************************************
983  *
984  * Function         gatt_process_read_rsp
985  *
986  * Description      This function is called to handle the read BLOB response
987  *
988  *
989  * Returns          void
990  *
991  ******************************************************************************/
gatt_process_read_rsp(tGATT_TCB & tcb,tGATT_CLCB * p_clcb,UNUSED_ATTR uint8_t op_code,uint16_t len,uint8_t * p_data)992 void gatt_process_read_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb,
993                            UNUSED_ATTR uint8_t op_code, uint16_t len,
994                            uint8_t* p_data) {
995   uint16_t offset = p_clcb->counter;
996   uint8_t* p = p_data;
997 
998   uint16_t payload_size = gatt_tcb_get_payload_size_rx(tcb, p_clcb->cid);
999 
1000   if (p_clcb->operation == GATTC_OPTYPE_READ) {
1001     if (p_clcb->op_subtype != GATT_READ_BY_HANDLE) {
1002       p_clcb->counter = len;
1003       gatt_end_operation(p_clcb, GATT_SUCCESS, (void*)p);
1004     } else {
1005       /* allocate GKI buffer holding up long attribute value  */
1006       if (!p_clcb->p_attr_buf)
1007         p_clcb->p_attr_buf = (uint8_t*)osi_malloc(GATT_MAX_ATTR_LEN);
1008 
1009       /* copy attrobute value into cb buffer  */
1010       if (offset < GATT_MAX_ATTR_LEN) {
1011         if ((len + offset) > GATT_MAX_ATTR_LEN)
1012           len = GATT_MAX_ATTR_LEN - offset;
1013 
1014         p_clcb->counter += len;
1015 
1016         memcpy(p_clcb->p_attr_buf + offset, p, len);
1017 
1018         /* full packet for read or read blob rsp */
1019         bool packet_is_full;
1020         if (payload_size == p_clcb->read_req_current_mtu) {
1021           packet_is_full = (len == (payload_size - 1));
1022         } else {
1023           packet_is_full = (len == (p_clcb->read_req_current_mtu - 1) ||
1024                             len == (payload_size - 1));
1025           p_clcb->read_req_current_mtu = payload_size;
1026         }
1027 
1028         /* send next request if needed  */
1029         if (packet_is_full && (len + offset < GATT_MAX_ATTR_LEN)) {
1030           VLOG(1) << StringPrintf(
1031               "full pkt issue read blob for remianing bytes old offset=%d "
1032               "len=%d new offset=%d",
1033               offset, len, p_clcb->counter);
1034           gatt_act_read(p_clcb, p_clcb->counter);
1035         } else /* end of request, send callback */
1036         {
1037           gatt_end_operation(p_clcb, GATT_SUCCESS, (void*)p_clcb->p_attr_buf);
1038         }
1039       } else /* exception, should not happen */
1040       {
1041         LOG(ERROR) << "attr offset = " << +offset
1042                    << " p_attr_buf = " << p_clcb->p_attr_buf;
1043         gatt_end_operation(p_clcb, GATT_NO_RESOURCES,
1044                            (void*)p_clcb->p_attr_buf);
1045       }
1046     }
1047   } else {
1048     if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY &&
1049         p_clcb->op_subtype == GATT_DISC_INC_SRVC &&
1050         p_clcb->read_uuid128.wait_for_read_rsp) {
1051       p_clcb->s_handle = p_clcb->read_uuid128.next_disc_start_hdl;
1052       p_clcb->read_uuid128.wait_for_read_rsp = false;
1053       if (len == Uuid::kNumBytes128) {
1054         p_clcb->read_uuid128.result.value.incl_service.service_type =
1055             bluetooth::Uuid::From128BitLE(p);
1056         if (p_clcb->p_reg->app_cb.p_disc_res_cb)
1057           (*p_clcb->p_reg->app_cb.p_disc_res_cb)(
1058               p_clcb->conn_id, static_cast<tGATT_DISC_TYPE>(p_clcb->op_subtype),
1059               &p_clcb->read_uuid128.result);
1060         gatt_act_discovery(p_clcb);
1061       } else {
1062         gatt_end_operation(p_clcb, GATT_INVALID_PDU, (void*)p);
1063       }
1064     }
1065   }
1066 }
1067 
1068 /*******************************************************************************
1069  *
1070  * Function         gatt_process_handle_rsp
1071  *
1072  * Description      This function is called to handle the write response
1073  *
1074  *
1075  * Returns          void
1076  *
1077  ******************************************************************************/
gatt_process_handle_rsp(tGATT_CLCB * p_clcb)1078 void gatt_process_handle_rsp(tGATT_CLCB* p_clcb) {
1079   gatt_end_operation(p_clcb, GATT_SUCCESS, NULL);
1080 }
1081 /*******************************************************************************
1082  *
1083  * Function         gatt_process_mtu_rsp
1084  *
1085  * Description      Process the configure MTU response.
1086  *
1087  *
1088  * Returns          void
1089  *
1090  ******************************************************************************/
gatt_process_mtu_rsp(tGATT_TCB & tcb,tGATT_CLCB * p_clcb,uint16_t len,uint8_t * p_data)1091 void gatt_process_mtu_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint16_t len,
1092                           uint8_t* p_data) {
1093   uint16_t mtu;
1094   tGATT_STATUS status = GATT_SUCCESS;
1095 
1096   if (len < GATT_MTU_RSP_MIN_LEN) {
1097     LOG(ERROR) << "invalid MTU response PDU received, discard.";
1098     status = GATT_INVALID_PDU;
1099   } else {
1100     STREAM_TO_UINT16(mtu, p_data);
1101 
1102     if (mtu < tcb.payload_size && mtu >= GATT_DEF_BLE_MTU_SIZE)
1103       tcb.payload_size = mtu;
1104   }
1105 
1106   BTM_SetBleDataLength(tcb.peer_bda, tcb.payload_size + L2CAP_PKT_OVERHEAD);
1107 
1108   gatt_end_operation(p_clcb, status, NULL);
1109 }
1110 /*******************************************************************************
1111  *
1112  * Function         gatt_cmd_to_rsp_code
1113  *
1114  * Description      Convert an ATT command op code into the corresponding
1115  *                  response code assume no error occurs.
1116  *
1117  * Returns          response code.
1118  *
1119  ******************************************************************************/
gatt_cmd_to_rsp_code(uint8_t cmd_code)1120 uint8_t gatt_cmd_to_rsp_code(uint8_t cmd_code) {
1121   uint8_t rsp_code = 0;
1122 
1123   if (cmd_code > 1 && cmd_code != GATT_CMD_WRITE) {
1124     rsp_code = cmd_code + 1;
1125   }
1126   return rsp_code;
1127 }
1128 
1129 /** Find next command in queue and sent to server */
gatt_cl_send_next_cmd_inq(tGATT_TCB & tcb)1130 bool gatt_cl_send_next_cmd_inq(tGATT_TCB& tcb) {
1131   std::deque<tGATT_CMD_Q>* cl_cmd_q = nullptr;
1132 
1133   while (
1134       gatt_is_outstanding_msg_in_att_send_queue(tcb) ||
1135       EattExtension::GetInstance()->IsOutstandingMsgInSendQueue(tcb.peer_bda)) {
1136     if (gatt_is_outstanding_msg_in_att_send_queue(tcb)) {
1137       cl_cmd_q = &tcb.cl_cmd_q;
1138     } else {
1139       EattChannel* channel =
1140           EattExtension::GetInstance()->GetChannelWithQueuedDataToSend(
1141               tcb.peer_bda);
1142       cl_cmd_q = &channel->cl_cmd_q_;
1143     }
1144 
1145     tGATT_CMD_Q& cmd = cl_cmd_q->front();
1146     if (!cmd.to_send || cmd.p_cmd == NULL) {
1147       return false;
1148     }
1149 
1150     tGATT_STATUS att_ret;
1151     att_ret = attp_send_msg_to_l2cap(tcb, cmd.cid, cmd.p_cmd);
1152 
1153     if (att_ret != GATT_SUCCESS && att_ret != GATT_CONGESTED) {
1154       LOG(ERROR) << __func__ << ": L2CAP sent error";
1155       cl_cmd_q->pop_front();
1156       continue;
1157     }
1158 
1159     cmd.to_send = false;
1160     cmd.p_cmd = NULL;
1161 
1162     if (cmd.op_code == GATT_CMD_WRITE || cmd.op_code == GATT_SIGN_CMD_WRITE) {
1163       /* dequeue the request if is write command or sign write */
1164       uint8_t rsp_code;
1165       tGATT_CLCB* p_clcb = gatt_cmd_dequeue(tcb, cmd.cid, &rsp_code);
1166 
1167       /* send command complete callback here */
1168       gatt_end_operation(p_clcb, att_ret, NULL);
1169 
1170       /* if no ack needed, keep sending */
1171       if (att_ret == GATT_SUCCESS) continue;
1172 
1173       return true;
1174     }
1175 
1176     gatt_start_rsp_timer(cmd.p_clcb);
1177     return true;
1178   }
1179 
1180   return false;
1181 }
1182 
1183 /** This function is called to handle the server response to client */
gatt_client_handle_server_rsp(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t len,uint8_t * p_data)1184 void gatt_client_handle_server_rsp(tGATT_TCB& tcb, uint16_t cid,
1185                                    uint8_t op_code, uint16_t len,
1186                                    uint8_t* p_data) {
1187   VLOG(1) << __func__ << " opcode: " << loghex(op_code) << " cid" << +cid;
1188 
1189   uint16_t payload_size = gatt_tcb_get_payload_size_rx(tcb, cid);
1190 
1191   if (op_code == GATT_HANDLE_VALUE_IND || op_code == GATT_HANDLE_VALUE_NOTIF ||
1192       op_code == GATT_HANDLE_MULTI_VALUE_NOTIF) {
1193     if (len >= payload_size) {
1194       LOG(ERROR) << StringPrintf(
1195           "%s: invalid indicate pkt size: %d, PDU size: %d", __func__, len + 1,
1196           payload_size);
1197       return;
1198     }
1199 
1200     gatt_process_notification(tcb, cid, op_code, len, p_data);
1201     return;
1202   }
1203 
1204   uint8_t cmd_code = 0;
1205   tGATT_CLCB* p_clcb = gatt_cmd_dequeue(tcb, cid, &cmd_code);
1206   if (!p_clcb) {
1207     LOG_WARN("ATT - clcb already not in use, ignoring response");
1208     gatt_cl_send_next_cmd_inq(tcb);
1209     return;
1210   }
1211 
1212   uint8_t rsp_code = gatt_cmd_to_rsp_code(cmd_code);
1213   if (!p_clcb) {
1214     LOG_WARN("ATT - clcb already not in use, ignoring response");
1215     gatt_cl_send_next_cmd_inq(tcb);
1216     return;
1217   }
1218 
1219   if (rsp_code != op_code && op_code != GATT_RSP_ERROR) {
1220     LOG(WARNING) << StringPrintf(
1221         "ATT - Ignore wrong response. Receives (%02x) Request(%02x) Ignored",
1222         op_code, rsp_code);
1223     return;
1224   }
1225 
1226   gatt_stop_rsp_timer(p_clcb);
1227   p_clcb->retry_count = 0;
1228 
1229   /* the size of the message may not be bigger than the local max PDU size*/
1230   /* The message has to be smaller than the agreed MTU, len does not count
1231    * op_code */
1232   if (len >= payload_size) {
1233     LOG(ERROR) << StringPrintf(
1234         "%s: invalid response pkt size: %d, PDU size: %d", __func__, len + 1,
1235         payload_size);
1236     gatt_end_operation(p_clcb, GATT_ERROR, NULL);
1237   } else {
1238     switch (op_code) {
1239       case GATT_RSP_ERROR:
1240         gatt_process_error_rsp(tcb, p_clcb, op_code, len, p_data);
1241         break;
1242 
1243       case GATT_RSP_MTU: /* 2 bytes mtu */
1244         gatt_process_mtu_rsp(tcb, p_clcb, len, p_data);
1245         break;
1246 
1247       case GATT_RSP_FIND_INFO:
1248         gatt_process_read_info_rsp(tcb, p_clcb, op_code, len, p_data);
1249         break;
1250 
1251       case GATT_RSP_READ_BY_TYPE:
1252       case GATT_RSP_READ_BY_GRP_TYPE:
1253         gatt_process_read_by_type_rsp(tcb, p_clcb, op_code, len, p_data);
1254         break;
1255 
1256       case GATT_RSP_READ:
1257       case GATT_RSP_READ_BLOB:
1258       case GATT_RSP_READ_MULTI:
1259       case GATT_RSP_READ_MULTI_VAR:
1260         gatt_process_read_rsp(tcb, p_clcb, op_code, len, p_data);
1261         break;
1262 
1263       case GATT_RSP_FIND_TYPE_VALUE: /* disc service with UUID */
1264         gatt_process_find_type_value_rsp(tcb, p_clcb, len, p_data);
1265         break;
1266 
1267       case GATT_RSP_WRITE:
1268         gatt_process_handle_rsp(p_clcb);
1269         break;
1270 
1271       case GATT_RSP_PREPARE_WRITE:
1272         gatt_process_prep_write_rsp(tcb, p_clcb, op_code, len, p_data);
1273         break;
1274 
1275       case GATT_RSP_EXEC_WRITE:
1276         gatt_end_operation(p_clcb, p_clcb->status, NULL);
1277         break;
1278 
1279       default:
1280         LOG(ERROR) << __func__ << ": Unknown opcode = " << std::hex << op_code;
1281         break;
1282     }
1283   }
1284 
1285   gatt_cl_send_next_cmd_inq(tcb);
1286 }
1287