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 <bluetooth/log.h>
28 #include <string.h>
29 
30 #include "gatt_int.h"
31 #include "hardware/bt_gatt_types.h"
32 #include "internal_include/bt_target.h"
33 #include "internal_include/bt_trace.h"
34 #include "os/log.h"
35 #include "osi/include/allocator.h"
36 #include "osi/include/osi.h"
37 #include "stack/arbiter/acl_arbiter.h"
38 #include "stack/eatt/eatt.h"
39 #include "stack/include/bt_types.h"
40 #include "types/bluetooth/uuid.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 namespace bluetooth;
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         log::verbose("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   log::assert_that(p_clcb->p_attr_buf != nullptr,
231                    "assert failed: p_clcb->p_attr_buf != nullptr");
232   tGATT_VALUE& attr = *((tGATT_VALUE*)p_clcb->p_attr_buf);
233 
234   uint16_t payload_size = gatt_tcb_get_payload_size(tcb, p_clcb->cid);
235 
236   switch (p_clcb->op_subtype) {
237     case GATT_WRITE_NO_RSP: {
238       p_clcb->s_handle = attr.handle;
239       uint8_t op_code = (sec_act == GATT_SEC_SIGN_DATA) ? GATT_SIGN_CMD_WRITE
240                                                         : GATT_CMD_WRITE;
241       tGATT_STATUS rt = gatt_send_write_msg(tcb, p_clcb, op_code, attr.handle,
242                                             attr.len, 0, attr.value);
243       if (rt != GATT_CMD_STARTED) {
244         if (rt != GATT_SUCCESS) {
245           log::error("gatt_act_write() failed op_code=0x{:x} rt={}", op_code,
246                      rt);
247         }
248         gatt_end_operation(p_clcb, rt, NULL);
249       }
250       return;
251     }
252 
253     case GATT_WRITE: {
254       if (attr.len <= (payload_size - GATT_HDR_SIZE)) {
255         p_clcb->s_handle = attr.handle;
256 
257         tGATT_STATUS rt = gatt_send_write_msg(
258             tcb, p_clcb, GATT_REQ_WRITE, attr.handle, attr.len, 0, attr.value);
259         if (rt != GATT_SUCCESS && rt != GATT_CMD_STARTED &&
260             rt != GATT_CONGESTED) {
261           if (rt != GATT_SUCCESS) {
262             log::error("gatt_act_write() failed op_code=0x{:x} rt={}",
263                        GATT_REQ_WRITE, 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       log::fatal("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   log::verbose("");
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   log::verbose("");
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   log::verbose("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(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   log::verbose("offset =0x{:x} len={}", 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(tGATT_TCB &,tGATT_CLCB * p_clcb,uint16_t len,uint8_t * p_data)391 void gatt_process_find_type_value_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb,
392                                       uint16_t len, uint8_t* p_data) {
393   tGATT_DISC_RES result;
394   uint8_t* p = p_data;
395 
396   log::verbose("");
397   /* unexpected response */
398   if (p_clcb->operation != GATTC_OPTYPE_DISCOVERY ||
399       p_clcb->op_subtype != GATT_DISC_SRVC_BY_UUID)
400     return;
401 
402   memset(&result, 0, sizeof(tGATT_DISC_RES));
403   result.type = bluetooth::Uuid::From16Bit(GATT_UUID_PRI_SERVICE);
404 
405   /* returns a series of handle ranges */
406   while (len >= 4) {
407     STREAM_TO_UINT16(result.handle, p);
408     STREAM_TO_UINT16(result.value.group_value.e_handle, p);
409     result.value.group_value.service_type = p_clcb->uuid;
410 
411     len -= 4;
412 
413     if (p_clcb->p_reg->app_cb.p_disc_res_cb)
414       (*p_clcb->p_reg->app_cb.p_disc_res_cb)(
415           p_clcb->conn_id, static_cast<tGATT_DISC_TYPE>(p_clcb->op_subtype),
416           &result);
417   }
418 
419   /* last handle  + 1 */
420   p_clcb->s_handle = (result.value.group_value.e_handle == 0)
421                          ? 0
422                          : (result.value.group_value.e_handle + 1);
423   /* initiate another request */
424   gatt_act_discovery(p_clcb);
425 }
426 /*******************************************************************************
427  *
428  * Function         gatt_process_read_info_rsp
429  *
430  * Description      This function is called to handle the read information
431  *                  response.
432  *
433  *
434  * Returns          void
435  *
436  ******************************************************************************/
gatt_process_read_info_rsp(tGATT_TCB &,tGATT_CLCB * p_clcb,uint8_t,uint16_t len,uint8_t * p_data)437 void gatt_process_read_info_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb,
438                                 uint8_t /* op_code */, uint16_t len,
439                                 uint8_t* p_data) {
440   tGATT_DISC_RES result;
441   uint8_t *p = p_data, uuid_len = 0, type;
442 
443   if (len < GATT_INFO_RSP_MIN_LEN) {
444     log::error("invalid Info Response PDU received, discard.");
445     gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL);
446     return;
447   }
448   /* unexpected response */
449   if (p_clcb->operation != GATTC_OPTYPE_DISCOVERY ||
450       p_clcb->op_subtype != GATT_DISC_CHAR_DSCPT)
451     return;
452 
453   STREAM_TO_UINT8(type, p);
454   len -= 1;
455 
456   if (type == GATT_INFO_TYPE_PAIR_16)
457     uuid_len = Uuid::kNumBytes16;
458   else if (type == GATT_INFO_TYPE_PAIR_128)
459     uuid_len = Uuid::kNumBytes128;
460 
461   while (len >= uuid_len + 2) {
462     STREAM_TO_UINT16(result.handle, p);
463 
464     if (uuid_len > 0) {
465       if (!gatt_parse_uuid_from_cmd(&result.type, uuid_len, &p)) break;
466     } else
467       result.type = p_clcb->uuid;
468 
469     len -= (uuid_len + 2);
470 
471     if (p_clcb->p_reg->app_cb.p_disc_res_cb)
472       (*p_clcb->p_reg->app_cb.p_disc_res_cb)(
473           p_clcb->conn_id, static_cast<tGATT_DISC_TYPE>(p_clcb->op_subtype),
474           &result);
475   }
476 
477   p_clcb->s_handle = (result.handle == 0) ? 0 : (result.handle + 1);
478   /* initiate another request */
479   gatt_act_discovery(p_clcb);
480 }
481 /*******************************************************************************
482  *
483  * Function         gatt_proc_disc_error_rsp
484  *
485  * Description      Process the read by type response and send another request
486  *                  if needed.
487  *
488  * Returns          void.
489  *
490  ******************************************************************************/
gatt_proc_disc_error_rsp(tGATT_TCB &,tGATT_CLCB * p_clcb,uint8_t opcode,uint16_t,uint8_t reason)491 void gatt_proc_disc_error_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb,
492                               uint8_t opcode, uint16_t /* handle */,
493                               uint8_t reason) {
494   tGATT_STATUS status = (tGATT_STATUS)reason;
495 
496   log::verbose("reason: {:02x} cmd_code {:04x}", reason, opcode);
497 
498   switch (opcode) {
499     case GATT_REQ_READ_BY_GRP_TYPE:
500     case GATT_REQ_FIND_TYPE_VALUE:
501     case GATT_REQ_READ_BY_TYPE:
502     case GATT_REQ_FIND_INFO:
503       if (reason == GATT_NOT_FOUND) {
504         status = GATT_SUCCESS;
505         log::verbose("Discovery completed");
506       }
507       break;
508     default:
509       log::error("Incorrect discovery opcode {:04x}", opcode);
510       break;
511   }
512 
513   gatt_end_operation(p_clcb, status, NULL);
514 }
515 
516 /*******************************************************************************
517  *
518  * Function         gatt_process_error_rsp
519  *
520  * Description      This function is called to handle the error response
521  *
522  *
523  * Returns          void
524  *
525  ******************************************************************************/
gatt_process_error_rsp(tGATT_TCB & tcb,tGATT_CLCB * p_clcb,uint8_t,uint16_t len,uint8_t * p_data)526 void gatt_process_error_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb,
527                             uint8_t /* op_code */, uint16_t len,
528                             uint8_t* p_data) {
529   uint8_t opcode, *p = p_data;
530   uint8_t reason;
531   uint16_t handle;
532   tGATT_VALUE* p_attr = (tGATT_VALUE*)p_clcb->p_attr_buf;
533 
534   log::verbose("");
535 
536   if (len < 4) {
537     log::error("Error response too short");
538     // Specification does not clearly define what should happen if error
539     // response is too short. General rule in BT Spec 5.0 Vol 3, Part F 3.4.1.1
540     // is: "If an error code is received in the Error Response that is not
541     // understood by the client, for example an error code that was reserved for
542     // future use that is now being used in a future version of this
543     // specification, then the Error Response shall still be considered to state
544     // that the given request cannot be performed for an unknown reason."
545     opcode = handle = 0;
546     reason = static_cast<tGATT_STATUS>(0x7f);
547   } else {
548     STREAM_TO_UINT8(opcode, p);
549     STREAM_TO_UINT16(handle, p);
550     STREAM_TO_UINT8(reason, p);
551   }
552 
553   if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY) {
554     gatt_proc_disc_error_rsp(tcb, p_clcb, opcode, handle,
555                              static_cast<tGATT_STATUS>(reason));
556   } else {
557     if ((p_clcb->operation == GATTC_OPTYPE_WRITE) &&
558         (p_clcb->op_subtype == GATT_WRITE) &&
559         (opcode == GATT_REQ_PREPARE_WRITE) && (p_attr) &&
560         (handle == p_attr->handle)) {
561       p_clcb->status = static_cast<tGATT_STATUS>(reason);
562       gatt_send_queue_write_cancel(tcb, p_clcb, GATT_PREP_WRITE_CANCEL);
563     } else if ((p_clcb->operation == GATTC_OPTYPE_READ) &&
564                ((p_clcb->op_subtype == GATT_READ_CHAR_VALUE_HDL) ||
565                 (p_clcb->op_subtype == GATT_READ_BY_HANDLE)) &&
566                (opcode == GATT_REQ_READ_BLOB) &&
567                p_clcb->first_read_blob_after_read &&
568                (reason == GATT_NOT_LONG)) {
569       gatt_end_operation(p_clcb, GATT_SUCCESS, (void*)p_clcb->p_attr_buf);
570     } else
571       gatt_end_operation(p_clcb, static_cast<tGATT_STATUS>(reason), NULL);
572   }
573 }
574 /*******************************************************************************
575  *
576  * Function         gatt_process_prep_write_rsp
577  *
578  * Description      This function is called to handle the read response
579  *
580  *
581  * Returns          void
582  *
583  ******************************************************************************/
gatt_process_prep_write_rsp(tGATT_TCB & tcb,tGATT_CLCB * p_clcb,uint8_t op_code,uint16_t len,uint8_t * p_data)584 void gatt_process_prep_write_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb,
585                                  uint8_t op_code, uint16_t len,
586                                  uint8_t* p_data) {
587   uint8_t* p = p_data;
588 
589   tGATT_VALUE value = {
590       .conn_id = p_clcb->conn_id, .auth_req = GATT_AUTH_REQ_NONE,
591   };
592 
593   log::verbose("value resp op_code = {} len = {}", gatt_dbg_op_name(op_code),
594                len);
595 
596   if (len < GATT_PREP_WRITE_RSP_MIN_LEN ||
597       len > GATT_PREP_WRITE_RSP_MIN_LEN + sizeof(value.value)) {
598     log::error("illegal prepare write response length, discard");
599     gatt_end_operation(p_clcb, GATT_INVALID_PDU, &value);
600     return;
601   }
602 
603   STREAM_TO_UINT16(value.handle, p);
604   STREAM_TO_UINT16(value.offset, p);
605 
606   value.len = len - GATT_PREP_WRITE_RSP_MIN_LEN;
607 
608   memcpy(value.value, p, value.len);
609 
610   bool subtype_is_write_prepare = (p_clcb->op_subtype == GATT_WRITE_PREPARE);
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   // We now know that we have not terminated, or else we would have returned
618   // early.  We free the buffer only if the subtype is not equal to
619   // GATT_WRITE_PREPARE, so checking here is adequate to prevent UAF.
620   if (subtype_is_write_prepare) {
621     /* application should verify handle offset
622        and value are matched or not */
623     gatt_end_operation(p_clcb, p_clcb->status, &value);
624   }
625 }
626 
627 /*******************************************************************************
628  *
629  * Function         gatt_process_notification
630  *
631  * Description      Handle the handle value indication/notification.
632  *
633  * Returns          void
634  *
635  ******************************************************************************/
gatt_process_notification(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t len,uint8_t * p_data)636 void gatt_process_notification(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code,
637                                uint16_t len, uint8_t* p_data) {
638   tGATT_VALUE value = {};
639   tGATT_REG* p_reg;
640   uint16_t conn_id;
641   tGATT_STATUS encrypt_status = {};
642   uint8_t* p = p_data;
643   uint8_t i;
644   tGATTC_OPTYPE event = (op_code == GATT_HANDLE_VALUE_IND)
645                             ? GATTC_OPTYPE_INDICATION
646                             : GATTC_OPTYPE_NOTIFICATION;
647 
648   log::verbose("");
649 
650   // Ensure our packet has enough data (2 bytes)
651   if (len < GATT_NOTIFICATION_MIN_LEN) {
652     log::error("illegal notification PDU length, discard");
653     return;
654   }
655 
656   // Get 2 byte handle
657   STREAM_TO_UINT16(value.handle, p);
658 
659   // Fail early if the GATT handle is not valid
660   if (!GATT_HANDLE_IS_VALID(value.handle)) {
661     /* illegal handle, send ack now */
662     if (op_code == GATT_HANDLE_VALUE_IND)
663       attp_send_cl_confirmation_msg(tcb, cid);
664     return;
665   }
666 
667   // Calculate value length based on opcode
668   if (op_code == GATT_HANDLE_MULTI_VALUE_NOTIF) {
669     // Ensure our packet has enough data; MIN + 2 more bytes for len value
670     if (len < GATT_NOTIFICATION_MIN_LEN + 2) {
671       log::error("illegal notification PDU length, discard");
672       return;
673     }
674 
675     // Allow multi value opcode to set value len from the packet
676     STREAM_TO_UINT16(value.len, p);
677 
678     if (value.len > len - 4) {
679       log::error("value.len ({}) greater than length ({})", value.len, len - 4);
680       return;
681     }
682 
683   } else {
684     // For single value, just use the passed in len minus opcode length (2)
685     value.len = len - 2;
686   }
687 
688   // Verify the new calculated length
689   if (value.len > GATT_MAX_ATTR_LEN) {
690     log::error("value.len larger than GATT_MAX_ATTR_LEN, discard");
691     return;
692   }
693 
694   // Handle indications differently
695   if (event == GATTC_OPTYPE_INDICATION) {
696     if (tcb.ind_count) {
697       /* this is an error case that receiving an indication but we
698          still has an indication not being acked yet.
699          For now, just log the error reset the counter.
700          Later we need to disconnect the link unconditionally.
701       */
702       log::error("rcv Ind. but ind_count={} (will reset ind_count)",
703                  tcb.ind_count);
704     }
705 
706     // Zero out the ind_count
707     tcb.ind_count = 0;
708 
709     // Notify all registered clients with the handle value
710     // notification/indication
711     // Note: need to do the indication count and start timer first then do
712     // callback
713     for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) {
714       if (p_reg->in_use && p_reg->app_cb.p_cmpl_cb) tcb.ind_count++;
715     }
716 
717     /* start a timer for app confirmation */
718     if (tcb.ind_count > 0) {
719       gatt_start_ind_ack_timer(tcb, cid);
720     } else { /* no app to indicate, or invalid handle */
721       attp_send_cl_confirmation_msg(tcb, cid);
722     }
723   }
724 
725   encrypt_status = gatt_get_link_encrypt_status(tcb);
726 
727   STREAM_TO_ARRAY(value.value, p, value.len);
728 
729   tGATT_CL_COMPLETE gatt_cl_complete;
730   gatt_cl_complete.att_value = value;
731   gatt_cl_complete.cid = cid;
732 
733   for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) {
734     if (p_reg->in_use && p_reg->app_cb.p_cmpl_cb) {
735       conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, p_reg->gatt_if);
736       (*p_reg->app_cb.p_cmpl_cb)(conn_id, event, encrypt_status,
737                                  &gatt_cl_complete);
738     }
739   }
740 
741   // If this is single value, then nothing is left to do
742   if (op_code != GATT_HANDLE_MULTI_VALUE_NOTIF) return;
743 
744   // Need a signed type to check if the value is below 0
745   // as uint16_t doesn't have negatives so the negatives register as a number
746   // thus anything less than zero won't trigger the conditional and it is not
747   // always 0
748   // when done looping as value.len is arbitrary.
749   int16_t rem_len = (int16_t)len - (4 /* octets */ + value.len);
750 
751   // Already streamed the first value and sent it, lets send the rest
752   while (rem_len > 4 /* octets */) {
753     // 2
754     STREAM_TO_UINT16(value.handle, p);
755     // + 2 = 4
756     STREAM_TO_UINT16(value.len, p);
757     // Accounting
758     rem_len -= 4;
759     // Make sure we don't read past the remaining data even if the length says
760     // we can Also need to watch comparing the int16_t with the uint16_t
761     value.len = std::min((uint16_t)rem_len, value.len);
762     if (value.len > sizeof(value.value)) {
763       log::error("Unexpected value.len (>GATT_MAX_ATTR_LEN), stop");
764       return ;
765     }
766     STREAM_TO_ARRAY(value.value, p, value.len);
767     // Accounting
768     rem_len -= value.len;
769 
770     gatt_cl_complete.att_value = value;
771     gatt_cl_complete.cid = cid;
772 
773     for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) {
774       if (p_reg->in_use && p_reg->app_cb.p_cmpl_cb) {
775         conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, p_reg->gatt_if);
776         (*p_reg->app_cb.p_cmpl_cb)(conn_id, event, encrypt_status,
777                                    &gatt_cl_complete);
778       }
779     }
780   }
781 }
782 
783 /*******************************************************************************
784  *
785  * Function         gatt_process_read_by_type_rsp
786  *
787  * Description      This function is called to handle the read by type response.
788  *                  read by type can be used for discovery, or read by type or
789  *                  read characteristic value.
790  *
791  * Returns          void
792  *
793  ******************************************************************************/
gatt_process_read_by_type_rsp(tGATT_TCB & tcb,tGATT_CLCB * p_clcb,uint8_t op_code,uint16_t len,uint8_t * p_data)794 void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb,
795                                    uint8_t op_code, uint16_t len,
796                                    uint8_t* p_data) {
797   tGATT_DISC_RES result;
798   tGATT_DISC_VALUE record_value;
799   uint8_t *p = p_data, value_len, handle_len = 2;
800   uint16_t handle = 0;
801 
802   /* discovery procedure and no callback function registered */
803   if (((!p_clcb->p_reg) || (!p_clcb->p_reg->app_cb.p_disc_res_cb)) &&
804       (p_clcb->operation == GATTC_OPTYPE_DISCOVERY))
805     return;
806 
807   if (len < GATT_READ_BY_TYPE_RSP_MIN_LEN) {
808     log::error("Illegal ReadByType/ReadByGroupType Response length, discard");
809     gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL);
810     return;
811   }
812 
813   STREAM_TO_UINT8(value_len, p);
814   uint16_t payload_size = gatt_tcb_get_payload_size(tcb, p_clcb->cid);
815   if ((value_len > (payload_size - 2)) || (value_len > (len - 1))) {
816     /* this is an error case that server's response containing a value length
817        which is larger than MTU-2
818        or value_len > message total length -1 */
819     log::error(
820         "Discard response op_code={} vale_len={} > (MTU-2={} or msg_len-1={})",
821         op_code, value_len, payload_size - 2, len - 1);
822     gatt_end_operation(p_clcb, GATT_ERROR, NULL);
823     return;
824   }
825 
826   if (op_code == GATT_RSP_READ_BY_GRP_TYPE) handle_len = 4;
827 
828   value_len -= handle_len; /* subtract the handle pairs bytes */
829   len -= 1;
830 
831   while (len >= (handle_len + value_len)) {
832     STREAM_TO_UINT16(handle, p);
833 
834     if (!GATT_HANDLE_IS_VALID(handle)) {
835       gatt_end_operation(p_clcb, GATT_INVALID_HANDLE, NULL);
836       return;
837     }
838 
839     memset(&result, 0, sizeof(tGATT_DISC_RES));
840     memset(&record_value, 0, sizeof(tGATT_DISC_VALUE));
841 
842     result.handle = handle;
843     result.type =
844         bluetooth::Uuid::From16Bit(disc_type_to_uuid[p_clcb->op_subtype]);
845 
846     /* discover all services */
847     if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY &&
848         p_clcb->op_subtype == GATT_DISC_SRVC_ALL &&
849         op_code == GATT_RSP_READ_BY_GRP_TYPE) {
850       STREAM_TO_UINT16(handle, p);
851 
852       if (!GATT_HANDLE_IS_VALID(handle)) {
853         gatt_end_operation(p_clcb, GATT_INVALID_HANDLE, NULL);
854         return;
855       } else {
856         record_value.group_value.e_handle = handle;
857         if (!gatt_parse_uuid_from_cmd(&record_value.group_value.service_type,
858                                       value_len, &p)) {
859           log::error("discover all service response parsing failure");
860           break;
861         }
862       }
863     }
864     /* discover included service */
865     else if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY &&
866              p_clcb->op_subtype == GATT_DISC_INC_SRVC) {
867       if (value_len < 4) {
868         log::error("Illegal Response length, must be at least 4.");
869         gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL);
870         return;
871       }
872       STREAM_TO_UINT16(record_value.incl_service.s_handle, p);
873       STREAM_TO_UINT16(record_value.incl_service.e_handle, p);
874 
875       if (!GATT_HANDLE_IS_VALID(record_value.incl_service.s_handle) ||
876           !GATT_HANDLE_IS_VALID(record_value.incl_service.e_handle)) {
877         gatt_end_operation(p_clcb, GATT_INVALID_HANDLE, NULL);
878         return;
879       }
880 
881       if (value_len == 6) {
882         uint16_t tmp;
883         STREAM_TO_UINT16(tmp, p);
884         record_value.incl_service.service_type =
885             bluetooth::Uuid::From16Bit(tmp);
886       } else if (value_len == 4) {
887         p_clcb->s_handle = record_value.incl_service.s_handle;
888         p_clcb->read_uuid128.wait_for_read_rsp = true;
889         p_clcb->read_uuid128.next_disc_start_hdl = handle + 1;
890         memcpy(&p_clcb->read_uuid128.result, &result, sizeof(result));
891         memcpy(&p_clcb->read_uuid128.result.value, &record_value,
892                sizeof(result.value));
893         p_clcb->op_subtype |= 0x90;
894         gatt_act_read(p_clcb, 0);
895         return;
896       } else {
897         log::error("INCL_SRVC failed with invalid data value_len={}",
898                    value_len);
899         gatt_end_operation(p_clcb, GATT_INVALID_PDU, (void*)p);
900         return;
901       }
902     }
903     /* read by type */
904     else if (p_clcb->operation == GATTC_OPTYPE_READ &&
905              p_clcb->op_subtype == GATT_READ_BY_TYPE) {
906       p_clcb->counter = len - 2;
907       p_clcb->s_handle = handle;
908       if (p_clcb->counter == (payload_size - 4)) {
909         p_clcb->op_subtype = GATT_READ_BY_HANDLE;
910         if (!p_clcb->p_attr_buf)
911           p_clcb->p_attr_buf = (uint8_t*)osi_malloc(GATT_MAX_ATTR_LEN);
912         if (p_clcb->counter <= GATT_MAX_ATTR_LEN) {
913           memcpy(p_clcb->p_attr_buf, p, p_clcb->counter);
914           gatt_act_read(p_clcb, p_clcb->counter);
915         } else {
916           gatt_end_operation(p_clcb, GATT_INTERNAL_ERROR, (void*)p);
917         }
918       } else {
919         gatt_end_operation(p_clcb, GATT_SUCCESS, (void*)p);
920       }
921       return;
922     } else /* discover characteristic */
923     {
924       if (value_len < 3) {
925         log::error("Illegal Response length, must be at least 3.");
926         gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL);
927         return;
928       }
929       STREAM_TO_UINT8(record_value.dclr_value.char_prop, p);
930       STREAM_TO_UINT16(record_value.dclr_value.val_handle, p);
931       if (!GATT_HANDLE_IS_VALID(record_value.dclr_value.val_handle)) {
932         gatt_end_operation(p_clcb, GATT_INVALID_HANDLE, NULL);
933         return;
934       }
935       if (!gatt_parse_uuid_from_cmd(&record_value.dclr_value.char_uuid,
936                                     (uint16_t)(value_len - 3), &p)) {
937         gatt_end_operation(p_clcb, GATT_SUCCESS, NULL);
938         /* invalid format, and skip the result */
939         return;
940       }
941 
942       /* UUID not matching */
943       if (!p_clcb->uuid.IsEmpty() &&
944           !record_value.dclr_value.char_uuid.IsEmpty() &&
945           record_value.dclr_value.char_uuid != p_clcb->uuid) {
946         len -= (value_len + 2);
947         continue; /* skip the result, and look for next one */
948       }
949 
950       if (p_clcb->operation == GATTC_OPTYPE_READ)
951       /* UUID match for read characteristic value */
952       {
953         /* only read the first matching UUID characteristic value, and
954           discard the rest results */
955         p_clcb->s_handle = record_value.dclr_value.val_handle;
956         p_clcb->op_subtype |= 0x80;
957         gatt_act_read(p_clcb, 0);
958         return;
959       }
960     }
961     len -= (value_len + handle_len);
962 
963     /* result is (handle, 16bits UUID) pairs */
964     memcpy(&result.value, &record_value, sizeof(result.value));
965 
966     /* send callback if is discover procedure */
967     if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY &&
968         p_clcb->p_reg->app_cb.p_disc_res_cb)
969       (*p_clcb->p_reg->app_cb.p_disc_res_cb)(
970           p_clcb->conn_id, static_cast<tGATT_DISC_TYPE>(p_clcb->op_subtype),
971           &result);
972   }
973 
974   p_clcb->s_handle = (handle == 0) ? 0 : (handle + 1);
975 
976   if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY) {
977     /* initiate another request */
978     gatt_act_discovery(p_clcb);
979   } else /* read characteristic value */
980   {
981     gatt_act_read(p_clcb, 0);
982   }
983 }
984 
985 /*******************************************************************************
986  *
987  * Function         gatt_process_read_rsp
988  *
989  * Description      This function is called to handle the read BLOB response
990  *
991  *
992  * Returns          void
993  *
994  ******************************************************************************/
gatt_process_read_rsp(tGATT_TCB & tcb,tGATT_CLCB * p_clcb,uint8_t,uint16_t len,uint8_t * p_data)995 void gatt_process_read_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb,
996                            uint8_t /* op_code */, uint16_t len,
997                            uint8_t* p_data) {
998   uint16_t offset = p_clcb->counter;
999   uint8_t* p = p_data;
1000 
1001   uint16_t payload_size = gatt_tcb_get_payload_size(tcb, p_clcb->cid);
1002 
1003   if (p_clcb->operation == GATTC_OPTYPE_READ) {
1004     if (p_clcb->op_subtype != GATT_READ_BY_HANDLE) {
1005       p_clcb->counter = len;
1006       gatt_end_operation(p_clcb, GATT_SUCCESS, (void*)p);
1007     } else {
1008       /* allocate GKI buffer holding up long attribute value  */
1009       if (!p_clcb->p_attr_buf)
1010         p_clcb->p_attr_buf = (uint8_t*)osi_malloc(GATT_MAX_ATTR_LEN);
1011 
1012       /* copy attribute value into cb buffer  */
1013       if (offset < GATT_MAX_ATTR_LEN) {
1014         if ((len + offset) > GATT_MAX_ATTR_LEN)
1015           len = GATT_MAX_ATTR_LEN - offset;
1016 
1017         p_clcb->counter += len;
1018 
1019         memcpy(p_clcb->p_attr_buf + offset, p, len);
1020 
1021         /* full packet for read or read blob rsp */
1022         bool packet_is_full;
1023         if (payload_size == p_clcb->read_req_current_mtu) {
1024           packet_is_full = (len == (payload_size - 1));
1025         } else {
1026           packet_is_full = (len == (p_clcb->read_req_current_mtu - 1) ||
1027                             len == (payload_size - 1));
1028           p_clcb->read_req_current_mtu = payload_size;
1029         }
1030 
1031         /* send next request if needed  */
1032         if (packet_is_full && (len + offset < GATT_MAX_ATTR_LEN)) {
1033           log::verbose(
1034               "full pkt issue read blob for remaining bytes old offset={} "
1035               "len={} new offset={}",
1036               offset, len, p_clcb->counter);
1037           gatt_act_read(p_clcb, p_clcb->counter);
1038         } else /* end of request, send callback */
1039         {
1040           gatt_end_operation(p_clcb, GATT_SUCCESS, (void*)p_clcb->p_attr_buf);
1041         }
1042       } else /* exception, should not happen */
1043       {
1044         log::error("attr offset = {} p_attr_buf = {}", offset,
1045                    fmt::ptr(p_clcb->p_attr_buf));
1046         gatt_end_operation(p_clcb, GATT_NO_RESOURCES,
1047                            (void*)p_clcb->p_attr_buf);
1048       }
1049     }
1050   } else {
1051     if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY &&
1052         p_clcb->op_subtype == GATT_DISC_INC_SRVC &&
1053         p_clcb->read_uuid128.wait_for_read_rsp) {
1054       p_clcb->s_handle = p_clcb->read_uuid128.next_disc_start_hdl;
1055       p_clcb->read_uuid128.wait_for_read_rsp = false;
1056       if (len == Uuid::kNumBytes128) {
1057         p_clcb->read_uuid128.result.value.incl_service.service_type =
1058             bluetooth::Uuid::From128BitLE(p);
1059         if (p_clcb->p_reg->app_cb.p_disc_res_cb)
1060           (*p_clcb->p_reg->app_cb.p_disc_res_cb)(
1061               p_clcb->conn_id, static_cast<tGATT_DISC_TYPE>(p_clcb->op_subtype),
1062               &p_clcb->read_uuid128.result);
1063         gatt_act_discovery(p_clcb);
1064       } else {
1065         gatt_end_operation(p_clcb, GATT_INVALID_PDU, (void*)p);
1066       }
1067     }
1068   }
1069 }
1070 
1071 /*******************************************************************************
1072  *
1073  * Function         gatt_process_handle_rsp
1074  *
1075  * Description      This function is called to handle the write response
1076  *
1077  *
1078  * Returns          void
1079  *
1080  ******************************************************************************/
gatt_process_handle_rsp(tGATT_CLCB * p_clcb)1081 void gatt_process_handle_rsp(tGATT_CLCB* p_clcb) {
1082   gatt_end_operation(p_clcb, GATT_SUCCESS, NULL);
1083 }
1084 /*******************************************************************************
1085  *
1086  * Function         gatt_process_mtu_rsp
1087  *
1088  * Description      Process the configure MTU response.
1089  *
1090  *
1091  * Returns          void
1092  *
1093  ******************************************************************************/
gatt_process_mtu_rsp(tGATT_TCB & tcb,tGATT_CLCB * p_clcb,uint16_t len,uint8_t * p_data)1094 void gatt_process_mtu_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint16_t len,
1095                           uint8_t* p_data) {
1096   uint16_t mtu;
1097   tGATT_STATUS status = GATT_SUCCESS;
1098 
1099   if (len < GATT_MTU_RSP_MIN_LEN) {
1100     log::error("invalid MTU response PDU received, discard.");
1101     status = GATT_INVALID_PDU;
1102   } else {
1103     STREAM_TO_UINT16(mtu, p_data);
1104 
1105     log::info("Local pending MTU {}, Remote ({}) MTU {}",
1106               tcb.pending_user_mtu_exchange_value, tcb.peer_bda, mtu);
1107 
1108     /* Aim for default as we did in the request */
1109     if (mtu < GATT_DEF_BLE_MTU_SIZE) {
1110       tcb.payload_size = GATT_DEF_BLE_MTU_SIZE;
1111     } else {
1112       tcb.payload_size = std::min(mtu, (uint16_t)(gatt_get_local_mtu()));
1113     }
1114 
1115     bluetooth::shim::arbiter::GetArbiter().OnIncomingMtuResp(tcb.tcb_idx,
1116                                                              tcb.payload_size);
1117 
1118     /* This is just to track the biggest MTU requested by the user.
1119      * This value will be used in the BTM_SetBleDataLength */
1120     if (tcb.pending_user_mtu_exchange_value > tcb.max_user_mtu) {
1121       tcb.max_user_mtu =
1122           std::min(tcb.pending_user_mtu_exchange_value, tcb.payload_size);
1123     } else if (tcb.pending_user_mtu_exchange_value == 0) {
1124       tcb.max_user_mtu = tcb.payload_size;
1125     }
1126     tcb.pending_user_mtu_exchange_value = 0;
1127 
1128     log::info("MTU Exchange resulted in: {}", tcb.payload_size);
1129 
1130     BTM_SetBleDataLength(tcb.peer_bda, tcb.max_user_mtu + L2CAP_PKT_OVERHEAD);
1131   }
1132 
1133   gatt_end_operation(p_clcb, status, NULL);
1134 }
1135 /*******************************************************************************
1136  *
1137  * Function         gatt_cmd_to_rsp_code
1138  *
1139  * Description      Convert an ATT command op code into the corresponding
1140  *                  response code assume no error occurs.
1141  *
1142  * Returns          response code.
1143  *
1144  ******************************************************************************/
gatt_cmd_to_rsp_code(uint8_t cmd_code)1145 uint8_t gatt_cmd_to_rsp_code(uint8_t cmd_code) {
1146   uint8_t rsp_code = 0;
1147 
1148   if (cmd_code > 1 && cmd_code != GATT_CMD_WRITE) {
1149     rsp_code = cmd_code + 1;
1150   }
1151   return rsp_code;
1152 }
1153 
1154 /** Find next command in queue and sent to server */
gatt_cl_send_next_cmd_inq(tGATT_TCB & tcb)1155 bool gatt_cl_send_next_cmd_inq(tGATT_TCB& tcb) {
1156   std::deque<tGATT_CMD_Q>* cl_cmd_q = nullptr;
1157 
1158   while (
1159       gatt_is_outstanding_msg_in_att_send_queue(tcb) ||
1160       EattExtension::GetInstance()->IsOutstandingMsgInSendQueue(tcb.peer_bda)) {
1161     if (gatt_is_outstanding_msg_in_att_send_queue(tcb)) {
1162       cl_cmd_q = &tcb.cl_cmd_q;
1163     } else {
1164       EattChannel* channel =
1165           EattExtension::GetInstance()->GetChannelWithQueuedDataToSend(
1166               tcb.peer_bda);
1167       cl_cmd_q = &channel->cl_cmd_q_;
1168     }
1169 
1170     tGATT_CMD_Q& cmd = cl_cmd_q->front();
1171     if (!cmd.to_send || cmd.p_cmd == NULL) {
1172       return false;
1173     }
1174 
1175     tGATT_STATUS att_ret;
1176     att_ret = attp_send_msg_to_l2cap(tcb, cmd.cid, cmd.p_cmd);
1177 
1178     if (att_ret != GATT_SUCCESS && att_ret != GATT_CONGESTED) {
1179       log::error("L2CAP sent error");
1180       cl_cmd_q->pop_front();
1181       continue;
1182     }
1183 
1184     cmd.to_send = false;
1185     cmd.p_cmd = NULL;
1186 
1187     if (cmd.op_code == GATT_CMD_WRITE || cmd.op_code == GATT_SIGN_CMD_WRITE) {
1188       /* dequeue the request if is write command or sign write */
1189       uint8_t rsp_code;
1190       tGATT_CLCB* p_clcb = gatt_cmd_dequeue(tcb, cmd.cid, &rsp_code);
1191 
1192       /* send command complete callback here */
1193       gatt_end_operation(p_clcb, att_ret, NULL);
1194 
1195       /* if no ack needed, keep sending */
1196       if (att_ret == GATT_SUCCESS) continue;
1197 
1198       return true;
1199     }
1200 
1201     gatt_start_rsp_timer(cmd.p_clcb);
1202     return true;
1203   }
1204 
1205   return false;
1206 }
1207 
1208 /** 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)1209 void gatt_client_handle_server_rsp(tGATT_TCB& tcb, uint16_t cid,
1210                                    uint8_t op_code, uint16_t len,
1211                                    uint8_t* p_data) {
1212   log::verbose("opcode: 0x{:x} cid{}", op_code, cid);
1213 
1214   uint16_t payload_size = gatt_tcb_get_payload_size(tcb, cid);
1215 
1216   if (op_code == GATT_HANDLE_VALUE_IND || op_code == GATT_HANDLE_VALUE_NOTIF ||
1217       op_code == GATT_HANDLE_MULTI_VALUE_NOTIF) {
1218     if (len >= payload_size) {
1219       log::error("invalid indicate pkt size: {}, PDU size: {}", len + 1,
1220                  payload_size);
1221       return;
1222     }
1223 
1224     gatt_process_notification(tcb, cid, op_code, len, p_data);
1225     return;
1226   }
1227 
1228   uint8_t cmd_code = 0;
1229   tGATT_CLCB* p_clcb = gatt_cmd_dequeue(tcb, cid, &cmd_code);
1230   if (!p_clcb) {
1231     log::warn("ATT - clcb already not in use, ignoring response");
1232     gatt_cl_send_next_cmd_inq(tcb);
1233     return;
1234   }
1235 
1236   uint8_t rsp_code = gatt_cmd_to_rsp_code(cmd_code);
1237   if (!p_clcb) {
1238     log::warn("ATT - clcb already not in use, ignoring response");
1239     gatt_cl_send_next_cmd_inq(tcb);
1240     return;
1241   }
1242 
1243   if (rsp_code != op_code && op_code != GATT_RSP_ERROR) {
1244     log::warn(
1245         "ATT - Ignore wrong response. Receives ({:02x}) Request({:02x}) "
1246         "Ignored",
1247         op_code, rsp_code);
1248     return;
1249   }
1250 
1251   gatt_stop_rsp_timer(p_clcb);
1252   p_clcb->retry_count = 0;
1253 
1254   /* the size of the message may not be bigger than the local max PDU size*/
1255   /* The message has to be smaller than the agreed MTU, len does not count
1256    * op_code */
1257   if (len >= payload_size) {
1258     log::error("invalid response pkt size: {}, PDU size: {}", len + 1,
1259                payload_size);
1260     gatt_end_operation(p_clcb, GATT_ERROR, NULL);
1261   } else {
1262     switch (op_code) {
1263       case GATT_RSP_ERROR:
1264         gatt_process_error_rsp(tcb, p_clcb, op_code, len, p_data);
1265         break;
1266 
1267       case GATT_RSP_MTU: /* 2 bytes mtu */
1268         gatt_process_mtu_rsp(tcb, p_clcb, len, p_data);
1269         break;
1270 
1271       case GATT_RSP_FIND_INFO:
1272         gatt_process_read_info_rsp(tcb, p_clcb, op_code, len, p_data);
1273         break;
1274 
1275       case GATT_RSP_READ_BY_TYPE:
1276       case GATT_RSP_READ_BY_GRP_TYPE:
1277         gatt_process_read_by_type_rsp(tcb, p_clcb, op_code, len, p_data);
1278         break;
1279 
1280       case GATT_RSP_READ:
1281       case GATT_RSP_READ_BLOB:
1282       case GATT_RSP_READ_MULTI:
1283       case GATT_RSP_READ_MULTI_VAR:
1284         gatt_process_read_rsp(tcb, p_clcb, op_code, len, p_data);
1285         break;
1286 
1287       case GATT_RSP_FIND_TYPE_VALUE: /* disc service with UUID */
1288         gatt_process_find_type_value_rsp(tcb, p_clcb, len, p_data);
1289         break;
1290 
1291       case GATT_RSP_WRITE:
1292         gatt_process_handle_rsp(p_clcb);
1293         break;
1294 
1295       case GATT_RSP_PREPARE_WRITE:
1296         gatt_process_prep_write_rsp(tcb, p_clcb, op_code, len, p_data);
1297         break;
1298 
1299       case GATT_RSP_EXEC_WRITE:
1300         gatt_end_operation(p_clcb, p_clcb->status, NULL);
1301         break;
1302 
1303       default:
1304         log::error("Unknown opcode = {:x}", op_code);
1305         break;
1306     }
1307   }
1308 
1309   gatt_cl_send_next_cmd_inq(tcb);
1310 }
1311