OSDN Git Service

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