• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2008-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 GATT server functions
22  *
23  ******************************************************************************/
24 #include <string.h>
25 
26 #include "bt_target.h"
27 #include "gatt_int.h"
28 #include "l2c_api.h"
29 #include "osi/include/allocator.h"
30 #include "osi/include/log.h"
31 #include "osi/include/osi.h"
32 #include "stack/eatt/eatt.h"
33 #include "stack/include/bt_hdr.h"
34 #include "stack/include/bt_types.h"
35 #include "stack/l2cap/l2c_int.h"
36 #include "types/bluetooth/uuid.h"
37 #include <base/logging.h>
38 
39 #define GATT_MTU_REQ_MIN_LEN 2
40 #define L2CAP_PKT_OVERHEAD 4
41 
42 using base::StringPrintf;
43 using bluetooth::Uuid;
44 using bluetooth::eatt::EattExtension;
45 using bluetooth::eatt::EattChannel;
46 
47 /*******************************************************************************
48  *
49  * Function         gatt_sr_enqueue_cmd
50  *
51  * Description      This function enqueue the request from client which needs a
52  *                  application response, and update the transaction ID.
53  *
54  * Returns          void
55  *
56  ******************************************************************************/
gatt_sr_enqueue_cmd(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t handle)57 uint32_t gatt_sr_enqueue_cmd(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code,
58                              uint16_t handle) {
59   tGATT_SR_CMD* p_cmd;
60 
61   if (cid == tcb.att_lcid) {
62     p_cmd = &tcb.sr_cmd;
63   } else {
64     EattChannel* channel =
65         EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
66     p_cmd = &channel->server_outstanding_cmd_;
67   }
68 
69   uint32_t trans_id = 0;
70 
71   p_cmd->cid = cid;
72 
73   if ((p_cmd->op_code == 0) ||
74       (op_code == GATT_HANDLE_VALUE_CONF)) /* no pending request */
75   {
76     if (op_code == GATT_CMD_WRITE || op_code == GATT_SIGN_CMD_WRITE ||
77         op_code == GATT_REQ_MTU || op_code == GATT_HANDLE_VALUE_CONF) {
78       trans_id = ++tcb.trans_id;
79     } else {
80       p_cmd->trans_id = ++tcb.trans_id;
81       p_cmd->op_code = op_code;
82       p_cmd->handle = handle;
83       p_cmd->status = GATT_NOT_FOUND;
84       tcb.trans_id %= GATT_TRANS_ID_MAX;
85       trans_id = p_cmd->trans_id;
86     }
87   }
88 
89   return trans_id;
90 }
91 
92 /*******************************************************************************
93  *
94  * Function         gatt_sr_cmd_empty
95  *
96  * Description      This function checks if the server command queue is empty.
97  *
98  * Returns          true if empty, false if there is pending command.
99  *
100  ******************************************************************************/
gatt_sr_cmd_empty(tGATT_TCB & tcb,uint16_t cid)101 bool gatt_sr_cmd_empty(tGATT_TCB& tcb, uint16_t cid) {
102   if (cid == tcb.att_lcid) return (tcb.sr_cmd.op_code == 0);
103 
104   EattChannel* channel =
105       EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
106 
107   return (channel->server_outstanding_cmd_.op_code == 0);
108 }
109 
110 /*******************************************************************************
111  *
112  * Function         gatt_dequeue_sr_cmd
113  *
114  * Description      This function dequeue the request from command queue.
115  *
116  * Returns          void
117  *
118  ******************************************************************************/
gatt_dequeue_sr_cmd(tGATT_TCB & tcb,uint16_t cid)119 void gatt_dequeue_sr_cmd(tGATT_TCB& tcb, uint16_t cid) {
120   tGATT_SR_CMD* p_cmd;
121 
122   if (cid == tcb.att_lcid) {
123     p_cmd = &tcb.sr_cmd;
124   } else {
125     EattChannel* channel =
126         EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
127 
128     p_cmd = &channel->server_outstanding_cmd_;
129   }
130 
131   /* Double check in case any buffers are queued */
132   VLOG(1) << "gatt_dequeue_sr_cmd cid: " << loghex(cid);
133   if (p_cmd->p_rsp_msg)
134     LOG(ERROR) << "free tcb.sr_cmd.p_rsp_msg = "
135                << p_cmd->p_rsp_msg;
136   osi_free_and_reset((void**)&p_cmd->p_rsp_msg);
137 
138   while (!fixed_queue_is_empty(p_cmd->multi_rsp_q))
139     osi_free(fixed_queue_try_dequeue(p_cmd->multi_rsp_q));
140   fixed_queue_free(p_cmd->multi_rsp_q, NULL);
141   memset(p_cmd, 0, sizeof(tGATT_SR_CMD));
142 }
143 
build_read_multi_rsp(tGATT_SR_CMD * p_cmd,uint16_t mtu)144 static void build_read_multi_rsp(tGATT_SR_CMD* p_cmd, uint16_t mtu) {
145   uint16_t ii, total_len, len;
146   uint8_t* p;
147   bool is_overflow = false;
148 
149   len = sizeof(BT_HDR) + L2CAP_MIN_OFFSET + mtu;
150   BT_HDR* p_buf = (BT_HDR*)osi_calloc(len);
151   p_buf->offset = L2CAP_MIN_OFFSET;
152   p = (uint8_t*)(p_buf + 1) + p_buf->offset;
153 
154   /* First byte in the response is the opcode */
155   if (p_cmd->multi_req.variable_len)
156     *p++ = GATT_RSP_READ_MULTI_VAR;
157   else
158     *p++ = GATT_RSP_READ_MULTI;
159 
160   p_buf->len = 1;
161 
162   /* Now walk through the buffers putting the data into the response in order
163    */
164   list_t* list = NULL;
165   const list_node_t* node = NULL;
166   if (!fixed_queue_is_empty(p_cmd->multi_rsp_q))
167     list = fixed_queue_get_list(p_cmd->multi_rsp_q);
168   for (ii = 0; ii < p_cmd->multi_req.num_handles; ii++) {
169     tGATTS_RSP* p_rsp = NULL;
170 
171     if (list != NULL) {
172       if (ii == 0)
173         node = list_begin(list);
174       else
175         node = list_next(node);
176       if (node != list_end(list)) p_rsp = (tGATTS_RSP*)list_node(node);
177     }
178 
179     if (p_rsp != NULL) {
180       total_len = (p_buf->len + p_rsp->attr_value.len);
181       if (p_cmd->multi_req.variable_len) {
182         total_len += 2;
183       }
184 
185       if (total_len > mtu) {
186         /* just send the partial response for the overflow case */
187         len = p_rsp->attr_value.len - (total_len - mtu);
188         is_overflow = true;
189         VLOG(1) << StringPrintf(
190             "multi read overflow available len=%d val_len=%d", len,
191             p_rsp->attr_value.len);
192       } else {
193         len = p_rsp->attr_value.len;
194       }
195 
196       if (p_cmd->multi_req.variable_len) {
197         UINT16_TO_STREAM(p, len);
198         p_buf->len += 2;
199       }
200 
201       if (p_rsp->attr_value.handle == p_cmd->multi_req.handles[ii]) {
202         memcpy(p, p_rsp->attr_value.value, len);
203         if (!is_overflow) p += len;
204         p_buf->len += len;
205       } else {
206         p_cmd->status = GATT_NOT_FOUND;
207         break;
208       }
209 
210       if (is_overflow) break;
211 
212     } else {
213       p_cmd->status = GATT_NOT_FOUND;
214       break;
215     }
216 
217   } /* loop through all handles*/
218 
219   /* Sanity check on the buffer length */
220   if (p_buf->len == 0) {
221     LOG(ERROR) << __func__ << " nothing found!!";
222     p_cmd->status = GATT_NOT_FOUND;
223     osi_free(p_buf);
224     VLOG(1) << __func__ << "osi_free(p_buf)";
225   } else if (p_cmd->p_rsp_msg != NULL) {
226     osi_free(p_buf);
227   } else {
228     p_cmd->p_rsp_msg = p_buf;
229   }
230 }
231 
232 /*******************************************************************************
233  *
234  * Function         process_read_multi_rsp
235  *
236  * Description      This function check the read multiple response.
237  *
238  * Returns          bool    if all replies have been received
239  *
240  ******************************************************************************/
process_read_multi_rsp(tGATT_SR_CMD * p_cmd,tGATT_STATUS status,tGATTS_RSP * p_msg,uint16_t mtu)241 static bool process_read_multi_rsp(tGATT_SR_CMD* p_cmd, tGATT_STATUS status,
242                                    tGATTS_RSP* p_msg, uint16_t mtu) {
243   VLOG(1) << StringPrintf("%s status=%d mtu=%d", __func__, status, mtu);
244 
245   if (p_cmd->multi_rsp_q == NULL)
246     p_cmd->multi_rsp_q = fixed_queue_new(SIZE_MAX);
247 
248   /* Enqueue the response */
249   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(tGATTS_RSP));
250   memcpy((void*)p_buf, (const void*)p_msg, sizeof(tGATTS_RSP));
251   fixed_queue_enqueue(p_cmd->multi_rsp_q, p_buf);
252 
253   p_cmd->status = status;
254   if (status == GATT_SUCCESS) {
255     VLOG(1) << "Multi read count=" << fixed_queue_length(p_cmd->multi_rsp_q)
256             << " num_hdls=" << p_cmd->multi_req.num_handles
257             << " variable=" << p_cmd->multi_req.variable_len;
258     /* Wait till we get all the responses */
259     if (fixed_queue_length(p_cmd->multi_rsp_q) ==
260         p_cmd->multi_req.num_handles) {
261       build_read_multi_rsp(p_cmd, mtu);
262       return (true);
263     }
264   } else /* any handle read exception occurs, return error */
265   {
266     return (true);
267   }
268 
269   /* If here, still waiting */
270   return (false);
271 }
272 
273 /*******************************************************************************
274  *
275  * Function         gatt_sr_process_app_rsp
276  *
277  * Description      This function checks whether the response message from
278  *                  application matches any pending request.
279  *
280  * Returns          void
281  *
282  ******************************************************************************/
gatt_sr_process_app_rsp(tGATT_TCB & tcb,tGATT_IF gatt_if,UNUSED_ATTR uint32_t trans_id,uint8_t op_code,tGATT_STATUS status,tGATTS_RSP * p_msg,tGATT_SR_CMD * sr_res_p)283 tGATT_STATUS gatt_sr_process_app_rsp(tGATT_TCB& tcb, tGATT_IF gatt_if,
284                                      UNUSED_ATTR uint32_t trans_id,
285                                      uint8_t op_code, tGATT_STATUS status,
286                                      tGATTS_RSP* p_msg,
287                                      tGATT_SR_CMD* sr_res_p) {
288   tGATT_STATUS ret_code = GATT_SUCCESS;
289   uint16_t payload_size = gatt_tcb_get_payload_size_tx(tcb, sr_res_p->cid);
290 
291   VLOG(1) << __func__ << " gatt_if=" << +gatt_if;
292 
293   gatt_sr_update_cback_cnt(tcb, sr_res_p->cid, gatt_if, false, false);
294 
295   if ((op_code == GATT_REQ_READ_MULTI) ||
296       (op_code == GATT_REQ_READ_MULTI_VAR)) {
297     /* If no error and still waiting, just return */
298     if (!process_read_multi_rsp(sr_res_p, status, p_msg, payload_size))
299       return (GATT_SUCCESS);
300   } else {
301     if (op_code == GATT_REQ_PREPARE_WRITE && status == GATT_SUCCESS)
302       gatt_sr_update_prep_cnt(tcb, gatt_if, true, false);
303 
304     if (op_code == GATT_REQ_EXEC_WRITE && status != GATT_SUCCESS)
305       gatt_sr_reset_cback_cnt(tcb, sr_res_p->cid);
306 
307     sr_res_p->status = status;
308 
309     if (gatt_sr_is_cback_cnt_zero(tcb) && status == GATT_SUCCESS) {
310       if (sr_res_p->p_rsp_msg == NULL) {
311         sr_res_p->p_rsp_msg = attp_build_sr_msg(
312             tcb, (uint8_t)(op_code + 1), (tGATT_SR_MSG*)p_msg, payload_size);
313       } else {
314         LOG(ERROR) << "Exception!!! already has respond message";
315       }
316     }
317   }
318   if (gatt_sr_is_cback_cnt_zero(tcb)) {
319     if ((sr_res_p->status == GATT_SUCCESS) && (sr_res_p->p_rsp_msg)) {
320       ret_code = attp_send_sr_msg(tcb, sr_res_p->cid, sr_res_p->p_rsp_msg);
321       sr_res_p->p_rsp_msg = NULL;
322     } else {
323       ret_code = gatt_send_error_rsp(tcb, sr_res_p->cid, status, op_code,
324                                      sr_res_p->handle, false);
325     }
326 
327     gatt_dequeue_sr_cmd(tcb, sr_res_p->cid);
328   }
329 
330   VLOG(1) << __func__ << " ret_code=" << +ret_code;
331 
332   return ret_code;
333 }
334 
335 /*******************************************************************************
336  *
337  * Function         gatt_process_exec_write_req
338  *
339  * Description      This function is called to process the execute write request
340  *                  from client.
341  *
342  * Returns          void
343  *
344  ******************************************************************************/
gatt_process_exec_write_req(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t len,uint8_t * p_data)345 void gatt_process_exec_write_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code,
346                                  uint16_t len, uint8_t* p_data) {
347   uint8_t *p = p_data, flag, i = 0;
348   uint32_t trans_id = 0;
349   tGATT_IF gatt_if;
350   uint16_t conn_id;
351 
352 #if (GATT_CONFORMANCE_TESTING == TRUE)
353   if (gatt_cb.enable_err_rsp && gatt_cb.req_op_code == op_code) {
354     VLOG(1)
355         << "Conformance tst: forced err rspv for Execute Write: error status="
356         << +gatt_cb.err_status;
357 
358     gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, gatt_cb.req_op_code,
359                         gatt_cb.handle, false);
360 
361     return;
362   }
363 #endif
364 
365   if (len < sizeof(flag)) {
366     LOG(ERROR) << __func__ << "invalid length";
367     gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, GATT_REQ_EXEC_WRITE, 0,
368                         false);
369     return;
370   }
371 
372   STREAM_TO_UINT8(flag, p);
373 
374   /* mask the flag */
375   flag &= GATT_PREP_WRITE_EXEC;
376 
377   /* no prep write is queued */
378   if (!gatt_sr_is_prep_cnt_zero(tcb)) {
379     trans_id = gatt_sr_enqueue_cmd(tcb, cid, op_code, 0);
380     gatt_sr_copy_prep_cnt_to_cback_cnt(tcb);
381 
382     for (i = 0; i < GATT_MAX_APPS; i++) {
383       if (tcb.prep_cnt[i]) {
384         gatt_if = (tGATT_IF)(i + 1);
385         conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, gatt_if);
386         tGATTS_DATA gatts_data;
387         gatts_data.exec_write = flag;
388         gatt_sr_send_req_callback(conn_id, trans_id, GATTS_REQ_TYPE_WRITE_EXEC,
389                                   &gatts_data);
390         tcb.prep_cnt[i] = 0;
391       }
392     }
393   } else /* nothing needs to be executed , send response now */
394   {
395     LOG(ERROR) << "gatt_process_exec_write_req: no prepare write pending";
396     gatt_send_error_rsp(tcb, cid, GATT_ERROR, GATT_REQ_EXEC_WRITE, 0, false);
397   }
398 }
399 
400 /*******************************************************************************
401  *
402  * Function         gatt_process_read_multi_req
403  *
404  * Description      This function is called to process the read multiple request
405  *                  from client.
406  *
407  * Returns          void
408  *
409  ******************************************************************************/
gatt_process_read_multi_req(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t len,uint8_t * p_data)410 void gatt_process_read_multi_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code,
411                                  uint16_t len, uint8_t* p_data) {
412   uint32_t trans_id;
413   uint16_t handle = 0, ll = len;
414   uint8_t* p = p_data;
415   tGATT_STATUS err = GATT_SUCCESS;
416   tGATT_SEC_FLAG sec_flag;
417   uint8_t key_size;
418 
419   VLOG(1) << __func__;
420 
421   tGATT_READ_MULTI* multi_req = gatt_sr_get_read_multi(tcb, cid);
422   multi_req->num_handles = 0;
423   multi_req->variable_len = (op_code == GATT_REQ_READ_MULTI_VAR);
424   gatt_sr_get_sec_info(tcb.peer_bda, tcb.transport, &sec_flag, &key_size);
425 
426 #if (GATT_CONFORMANCE_TESTING == TRUE)
427   if (gatt_cb.enable_err_rsp && gatt_cb.req_op_code == op_code) {
428     VLOG(1) << "Conformance tst: forced err rspvofr ReadMultiple: error status="
429             << +gatt_cb.err_status;
430 
431     STREAM_TO_UINT16(handle, p);
432 
433     gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, gatt_cb.req_op_code,
434                         handle, false);
435 
436     return;
437   }
438 #endif
439 
440   while (ll >= 2 && multi_req->num_handles < GATT_MAX_READ_MULTI_HANDLES) {
441     STREAM_TO_UINT16(handle, p);
442 
443     auto it = gatt_sr_find_i_rcb_by_handle(handle);
444     if (it != gatt_cb.srv_list_info->end()) {
445       multi_req->handles[multi_req->num_handles++] = handle;
446 
447       /* check read permission */
448       err = gatts_read_attr_perm_check(it->p_db, false, handle, sec_flag,
449                                        key_size);
450       if (err != GATT_SUCCESS) {
451         VLOG(1) << StringPrintf("read permission denied : 0x%02x", err);
452         break;
453       }
454     } else {
455       /* invalid handle */
456       err = GATT_INVALID_HANDLE;
457       break;
458     }
459     ll -= 2;
460   }
461 
462   if (ll != 0) {
463     LOG(ERROR) << "max attribute handle reached in ReadMultiple Request.";
464   }
465 
466   if (multi_req->num_handles == 0) err = GATT_INVALID_HANDLE;
467 
468   if (err == GATT_SUCCESS) {
469     trans_id = gatt_sr_enqueue_cmd(tcb, cid, op_code, multi_req->handles[0]);
470     if (trans_id != 0) {
471       tGATT_SR_CMD* sr_cmd_p = gatt_sr_get_cmd_by_cid(tcb, cid);
472 
473       gatt_sr_reset_cback_cnt(tcb,
474                               cid); /* read multiple use multi_rsp_q's count*/
475 
476       for (ll = 0; ll < multi_req->num_handles; ll++) {
477         tGATTS_RSP* p_msg = (tGATTS_RSP*)osi_calloc(sizeof(tGATTS_RSP));
478         handle = multi_req->handles[ll];
479         auto it = gatt_sr_find_i_rcb_by_handle(handle);
480 
481         p_msg->attr_value.handle = handle;
482         err = gatts_read_attr_value_by_handle(
483             tcb, cid, it->p_db, op_code, handle, 0, p_msg->attr_value.value,
484             &p_msg->attr_value.len, GATT_MAX_ATTR_LEN, sec_flag, key_size,
485             trans_id);
486 
487         if (err == GATT_SUCCESS) {
488           gatt_sr_process_app_rsp(tcb, it->gatt_if, trans_id, op_code,
489                                   GATT_SUCCESS, p_msg, sr_cmd_p);
490         }
491         /* either not using or done using the buffer, release it now */
492         osi_free(p_msg);
493       }
494     } else
495       err = GATT_NO_RESOURCES;
496   }
497 
498   /* in theroy BUSY is not possible(should already been checked), protected
499    * check */
500   if (err != GATT_SUCCESS && err != GATT_PENDING && err != GATT_BUSY)
501     gatt_send_error_rsp(tcb, cid, err, op_code, handle, false);
502 }
503 
504 /*******************************************************************************
505  *
506  * Function         gatt_build_primary_service_rsp
507  *
508  * Description      Primamry service request processed internally. Theretically
509  *                  only deal with ReadByTypeVAlue and ReadByGroupType.
510  *
511  * Returns          void
512  *
513  ******************************************************************************/
gatt_build_primary_service_rsp(BT_HDR * p_msg,tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t s_hdl,uint16_t e_hdl,UNUSED_ATTR uint8_t * p_data,const Uuid & value)514 static tGATT_STATUS gatt_build_primary_service_rsp(
515     BT_HDR* p_msg, tGATT_TCB& tcb, uint16_t cid, uint8_t op_code,
516     uint16_t s_hdl, uint16_t e_hdl, UNUSED_ATTR uint8_t* p_data,
517     const Uuid& value) {
518   tGATT_STATUS status = GATT_NOT_FOUND;
519   uint8_t handle_len = 4;
520 
521   uint8_t* p = (uint8_t*)(p_msg + 1) + L2CAP_MIN_OFFSET;
522 
523   uint16_t payload_size = gatt_tcb_get_payload_size_tx(tcb, cid);
524 
525   for (tGATT_SRV_LIST_ELEM& el : *gatt_cb.srv_list_info) {
526     if (el.s_hdl < s_hdl || el.s_hdl > e_hdl ||
527         el.type != GATT_UUID_PRI_SERVICE) {
528       continue;
529     }
530 
531     Uuid* p_uuid = gatts_get_service_uuid(el.p_db);
532     if (!p_uuid) continue;
533 
534     if (op_code == GATT_REQ_READ_BY_GRP_TYPE)
535       handle_len = 4 + gatt_build_uuid_to_stream_len(*p_uuid);
536 
537     /* get the length byte in the repsonse */
538     if (p_msg->offset == 0) {
539       *p++ = op_code + 1;
540       p_msg->len++;
541       p_msg->offset = handle_len;
542 
543       if (op_code == GATT_REQ_READ_BY_GRP_TYPE) {
544         *p++ = (uint8_t)p_msg->offset; /* length byte */
545         p_msg->len++;
546       }
547     }
548 
549     if (p_msg->len + p_msg->offset > payload_size ||
550         handle_len != p_msg->offset) {
551       break;
552     }
553 
554     if (op_code == GATT_REQ_FIND_TYPE_VALUE && value != *p_uuid) continue;
555 
556     UINT16_TO_STREAM(p, el.s_hdl);
557 
558     if (gatt_cb.last_service_handle &&
559         gatt_cb.last_service_handle == el.s_hdl) {
560       VLOG(1) << "Use 0xFFFF for the last primary attribute";
561       /* see GATT ERRATA 4065, 4063, ATT ERRATA 4062 */
562       UINT16_TO_STREAM(p, 0xFFFF);
563     } else {
564       UINT16_TO_STREAM(p, el.e_hdl);
565     }
566 
567     if (op_code == GATT_REQ_READ_BY_GRP_TYPE)
568       gatt_build_uuid_to_stream(&p, *p_uuid);
569 
570     status = GATT_SUCCESS;
571     p_msg->len += p_msg->offset;
572   }
573   p_msg->offset = L2CAP_MIN_OFFSET;
574 
575   return status;
576 }
577 
578 /**
579  * fill the find information response information in the given buffer.
580  *
581  * Returns          true: if data filled sucessfully.
582  *                  false: packet full, or format mismatch.
583  */
gatt_build_find_info_rsp(tGATT_SRV_LIST_ELEM & el,BT_HDR * p_msg,uint16_t & len,uint16_t s_hdl,uint16_t e_hdl)584 static tGATT_STATUS gatt_build_find_info_rsp(tGATT_SRV_LIST_ELEM& el,
585                                              BT_HDR* p_msg, uint16_t& len,
586                                              uint16_t s_hdl, uint16_t e_hdl) {
587   uint8_t info_pair_len[2] = {4, 18};
588 
589   if (!el.p_db) return GATT_NOT_FOUND;
590 
591   /* check the attribute database */
592 
593   uint8_t* p = (uint8_t*)(p_msg + 1) + L2CAP_MIN_OFFSET + p_msg->len;
594 
595   for (auto& attr : el.p_db->attr_list) {
596     if (attr.handle > e_hdl) break;
597 
598     if (attr.handle < s_hdl) continue;
599 
600     uint8_t uuid_len = attr.uuid.GetShortestRepresentationSize();
601     if (p_msg->offset == 0)
602       p_msg->offset = (uuid_len == Uuid::kNumBytes16) ? GATT_INFO_TYPE_PAIR_16
603                                                       : GATT_INFO_TYPE_PAIR_128;
604 
605     if (len < info_pair_len[p_msg->offset - 1]) return GATT_NO_RESOURCES;
606 
607     if (p_msg->offset == GATT_INFO_TYPE_PAIR_16 &&
608         uuid_len == Uuid::kNumBytes16) {
609       UINT16_TO_STREAM(p, attr.handle);
610       UINT16_TO_STREAM(p, attr.uuid.As16Bit());
611     } else if (p_msg->offset == GATT_INFO_TYPE_PAIR_128 &&
612                uuid_len == Uuid::kNumBytes128) {
613       UINT16_TO_STREAM(p, attr.handle);
614       ARRAY_TO_STREAM(p, attr.uuid.To128BitLE(), (int)Uuid::kNumBytes128);
615     } else if (p_msg->offset == GATT_INFO_TYPE_PAIR_128 &&
616                uuid_len == Uuid::kNumBytes32) {
617       UINT16_TO_STREAM(p, attr.handle);
618       ARRAY_TO_STREAM(p, attr.uuid.To128BitLE(), (int)Uuid::kNumBytes128);
619     } else {
620       LOG(ERROR) << "format mismatch";
621       return GATT_NO_RESOURCES;
622       /* format mismatch */
623     }
624     p_msg->len += info_pair_len[p_msg->offset - 1];
625     len -= info_pair_len[p_msg->offset - 1];
626     return GATT_SUCCESS;
627   }
628 
629   return GATT_NOT_FOUND;
630 }
631 
read_handles(uint16_t & len,uint8_t * & p,uint16_t & s_hdl,uint16_t & e_hdl)632 static tGATT_STATUS read_handles(uint16_t& len, uint8_t*& p, uint16_t& s_hdl,
633                                  uint16_t& e_hdl) {
634   if (len < 4) return GATT_INVALID_PDU;
635 
636   /* obtain starting handle, and ending handle */
637   STREAM_TO_UINT16(s_hdl, p);
638   STREAM_TO_UINT16(e_hdl, p);
639   len -= 4;
640 
641   if (s_hdl > e_hdl || !GATT_HANDLE_IS_VALID(s_hdl) ||
642       !GATT_HANDLE_IS_VALID(e_hdl)) {
643     return GATT_INVALID_HANDLE;
644   }
645 
646   return GATT_SUCCESS;
647 }
648 
gatts_validate_packet_format(uint8_t op_code,uint16_t & len,uint8_t * & p,Uuid * p_uuid,uint16_t & s_hdl,uint16_t & e_hdl)649 static tGATT_STATUS gatts_validate_packet_format(uint8_t op_code, uint16_t& len,
650                                                  uint8_t*& p, Uuid* p_uuid,
651                                                  uint16_t& s_hdl,
652                                                  uint16_t& e_hdl) {
653   tGATT_STATUS ret = read_handles(len, p, s_hdl, e_hdl);
654   if (ret != GATT_SUCCESS) return ret;
655 
656   if (len < 2) return GATT_INVALID_PDU;
657 
658   /* parse uuid now */
659   CHECK(p_uuid);
660   uint16_t uuid_len = (op_code == GATT_REQ_FIND_TYPE_VALUE) ? 2 : len;
661   if (!gatt_parse_uuid_from_cmd(p_uuid, uuid_len, &p)) {
662     VLOG(1) << "Bad UUID";
663     return GATT_INVALID_PDU;
664   }
665 
666   len -= uuid_len;
667   return GATT_SUCCESS;
668 }
669 
670 /*******************************************************************************
671  *
672  * Function         gatts_process_primary_service_req
673  *
674  * Description      Process ReadByGroupType/ReadByTypeValue request, for
675  *                  discovering all primary services or discover primary service
676  *                  by UUID request.
677  *
678  * Returns          void
679  *
680  ******************************************************************************/
gatts_process_primary_service_req(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t len,uint8_t * p_data)681 void gatts_process_primary_service_req(tGATT_TCB& tcb, uint16_t cid,
682                                        uint8_t op_code, uint16_t len,
683                                        uint8_t* p_data) {
684   uint16_t s_hdl = 0, e_hdl = 0;
685   Uuid uuid = Uuid::kEmpty;
686 
687   uint8_t reason =
688       gatts_validate_packet_format(op_code, len, p_data, &uuid, s_hdl, e_hdl);
689   if (reason != GATT_SUCCESS) {
690     gatt_send_error_rsp(tcb, cid, reason, op_code, s_hdl, false);
691     return;
692   }
693 
694   if (uuid != Uuid::From16Bit(GATT_UUID_PRI_SERVICE)) {
695     if (op_code == GATT_REQ_READ_BY_GRP_TYPE) {
696       gatt_send_error_rsp(tcb, cid, GATT_UNSUPPORT_GRP_TYPE, op_code, s_hdl,
697                           false);
698       VLOG(1) << StringPrintf("unexpected ReadByGrpType Group: %s",
699                               uuid.ToString().c_str());
700       return;
701     }
702 
703     // we do not support ReadByTypeValue with any non-primamry_service type
704     gatt_send_error_rsp(tcb, cid, GATT_NOT_FOUND, op_code, s_hdl, false);
705     VLOG(1) << StringPrintf("unexpected ReadByTypeValue type: %s",
706                             uuid.ToString().c_str());
707     return;
708   }
709 
710   // TODO: we assume theh value is UUID, there is no such requirement in spec
711   Uuid value = Uuid::kEmpty;
712   if (op_code == GATT_REQ_FIND_TYPE_VALUE) {
713     if (!gatt_parse_uuid_from_cmd(&value, len, &p_data)) {
714       gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, op_code, s_hdl, false);
715     }
716   }
717 
718   uint16_t payload_size = gatt_tcb_get_payload_size_tx(tcb, cid);
719 
720   uint16_t msg_len =
721       (uint16_t)(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET);
722   BT_HDR* p_msg = (BT_HDR*)osi_calloc(msg_len);
723   reason = gatt_build_primary_service_rsp(p_msg, tcb, cid, op_code, s_hdl,
724                                           e_hdl, p_data, value);
725   if (reason != GATT_SUCCESS) {
726     osi_free(p_msg);
727     gatt_send_error_rsp(tcb, cid, reason, op_code, s_hdl, false);
728     return;
729   }
730 
731   attp_send_sr_msg(tcb, cid, p_msg);
732 }
733 
734 /*******************************************************************************
735  *
736  * Function         gatts_process_find_info
737  *
738  * Description      process find information request, for discover character
739  *                  descriptors.
740  *
741  * Returns          void
742  *
743  ******************************************************************************/
gatts_process_find_info(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t len,uint8_t * p_data)744 static void gatts_process_find_info(tGATT_TCB& tcb, uint16_t cid,
745                                     uint8_t op_code, uint16_t len,
746                                     uint8_t* p_data) {
747   uint16_t s_hdl = 0, e_hdl = 0;
748   uint8_t reason = read_handles(len, p_data, s_hdl, e_hdl);
749   if (reason != GATT_SUCCESS) {
750     gatt_send_error_rsp(tcb, cid, reason, op_code, s_hdl, false);
751     return;
752   }
753 
754   uint16_t payload_size = gatt_tcb_get_payload_size_tx(tcb, cid);
755   uint16_t buf_len =
756       (uint16_t)(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET);
757 
758   BT_HDR* p_msg = (BT_HDR*)osi_calloc(buf_len);
759   reason = GATT_NOT_FOUND;
760 
761   uint8_t* p = (uint8_t*)(p_msg + 1) + L2CAP_MIN_OFFSET;
762   *p++ = op_code + 1;
763   p_msg->len = 2;
764 
765   buf_len = payload_size - 2;
766 
767   for (tGATT_SRV_LIST_ELEM& el : *gatt_cb.srv_list_info) {
768     if (el.s_hdl <= e_hdl && el.e_hdl >= s_hdl) {
769       reason = gatt_build_find_info_rsp(el, p_msg, buf_len, s_hdl, e_hdl);
770       if (reason == GATT_NO_RESOURCES) {
771         reason = GATT_SUCCESS;
772         break;
773       }
774     }
775   }
776 
777   *p = (uint8_t)p_msg->offset;
778 
779   p_msg->offset = L2CAP_MIN_OFFSET;
780 
781   if (reason != GATT_SUCCESS) {
782     osi_free(p_msg);
783     gatt_send_error_rsp(tcb, cid, reason, op_code, s_hdl, false);
784   } else
785     attp_send_sr_msg(tcb, cid, p_msg);
786 }
787 
788 /*******************************************************************************
789  *
790  * Function         gatts_process_mtu_req
791  *
792  * Description      This function is called to process excahnge MTU request.
793  *                  Only used on LE.
794  *
795  * Returns          void
796  *
797  ******************************************************************************/
gatts_process_mtu_req(tGATT_TCB & tcb,uint16_t cid,uint16_t len,uint8_t * p_data)798 static void gatts_process_mtu_req(tGATT_TCB& tcb, uint16_t cid, uint16_t len,
799                                   uint8_t* p_data) {
800   /* BR/EDR conenction, send error response */
801   if (cid != L2CAP_ATT_CID) {
802     gatt_send_error_rsp(tcb, cid, GATT_REQ_NOT_SUPPORTED, GATT_REQ_MTU, 0,
803                         false);
804     return;
805   }
806 
807   if (len < GATT_MTU_REQ_MIN_LEN) {
808     LOG(ERROR) << "invalid MTU request PDU received.";
809     gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, GATT_REQ_MTU, 0, false);
810     return;
811   }
812 
813   uint16_t mtu = 0;
814   uint8_t* p = p_data;
815   STREAM_TO_UINT16(mtu, p);
816   /* mtu must be greater than default MTU which is 23/48 */
817   if (mtu < GATT_DEF_BLE_MTU_SIZE)
818     tcb.payload_size = GATT_DEF_BLE_MTU_SIZE;
819   else if (mtu > GATT_MAX_MTU_SIZE)
820     tcb.payload_size = GATT_MAX_MTU_SIZE;
821   else
822     tcb.payload_size = mtu;
823 
824   LOG(INFO) << "MTU request PDU with MTU size " << +tcb.payload_size;
825 
826   BTM_SetBleDataLength(tcb.peer_bda, tcb.payload_size + L2CAP_PKT_OVERHEAD);
827 
828   tGATT_SR_MSG gatt_sr_msg;
829   gatt_sr_msg.mtu = tcb.payload_size;
830   BT_HDR* p_buf =
831       attp_build_sr_msg(tcb, GATT_RSP_MTU, &gatt_sr_msg, tcb.payload_size);
832   attp_send_sr_msg(tcb, cid, p_buf);
833 
834   tGATTS_DATA gatts_data;
835   gatts_data.mtu = tcb.payload_size;
836   /* Notify all registered applicaiton with new MTU size. Us a transaction ID */
837   /* of 0, as no response is allowed from applcations                    */
838   for (int i = 0; i < GATT_MAX_APPS; i++) {
839     if (gatt_cb.cl_rcb[i].in_use) {
840       uint16_t conn_id =
841           GATT_CREATE_CONN_ID(tcb.tcb_idx, gatt_cb.cl_rcb[i].gatt_if);
842       gatt_sr_send_req_callback(conn_id, 0, GATTS_REQ_TYPE_MTU, &gatts_data);
843     }
844   }
845 }
846 
847 /*******************************************************************************
848  *
849  * Function         gatts_process_read_by_type_req
850  *
851  * Description      process Read By type request.
852  *                  This PDU can be used to perform:
853  *                  - read characteristic value
854  *                  - read characteristic descriptor value
855  *                  - discover characteristic
856  *                  - discover characteristic by UUID
857  *                  - relationship discovery
858  *
859  * Returns          void
860  *
861  ******************************************************************************/
gatts_process_read_by_type_req(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t len,uint8_t * p_data)862 static void gatts_process_read_by_type_req(tGATT_TCB& tcb, uint16_t cid,
863                                            uint8_t op_code, uint16_t len,
864                                            uint8_t* p_data) {
865   Uuid uuid = Uuid::kEmpty;
866   uint16_t s_hdl = 0, e_hdl = 0, err_hdl = 0;
867   tGATT_STATUS reason =
868       gatts_validate_packet_format(op_code, len, p_data, &uuid, s_hdl, e_hdl);
869 
870 #if (GATT_CONFORMANCE_TESTING == TRUE)
871   if (gatt_cb.enable_err_rsp && gatt_cb.req_op_code == op_code) {
872     VLOG(1) << "Conformance tst: forced err rsp for ReadByType: error status="
873             << +gatt_cb.err_status;
874 
875     gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, gatt_cb.req_op_code,
876                         s_hdl, false);
877 
878     return;
879   }
880 #endif
881 
882   if (reason != GATT_SUCCESS) {
883     gatt_send_error_rsp(tcb, cid, reason, op_code, s_hdl, false);
884     return;
885   }
886 
887   uint16_t payload_size = gatt_tcb_get_payload_size_tx(tcb, cid);
888 
889   size_t msg_len = sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET;
890   BT_HDR* p_msg = (BT_HDR*)osi_calloc(msg_len);
891   uint8_t* p = (uint8_t*)(p_msg + 1) + L2CAP_MIN_OFFSET;
892 
893   *p++ = op_code + 1;
894   /* reserve length byte */
895   p_msg->len = 2;
896   uint16_t buf_len = payload_size - 2;
897 
898   reason = GATT_NOT_FOUND;
899   for (tGATT_SRV_LIST_ELEM& el : *gatt_cb.srv_list_info) {
900     if (el.s_hdl <= e_hdl && el.e_hdl >= s_hdl) {
901       tGATT_SEC_FLAG sec_flag;
902       uint8_t key_size;
903       gatt_sr_get_sec_info(tcb.peer_bda, tcb.transport, &sec_flag, &key_size);
904 
905       tGATT_STATUS ret = gatts_db_read_attr_value_by_type(
906           tcb, cid, el.p_db, op_code, p_msg, s_hdl, e_hdl, uuid, &buf_len,
907           sec_flag, key_size, 0, &err_hdl);
908       if (ret != GATT_NOT_FOUND) {
909         reason = ret;
910         if (ret == GATT_NO_RESOURCES) reason = GATT_SUCCESS;
911       }
912 
913       if (ret != GATT_SUCCESS && ret != GATT_NOT_FOUND) {
914         s_hdl = err_hdl;
915         break;
916       }
917     }
918   }
919   *p = (uint8_t)p_msg->offset;
920   p_msg->offset = L2CAP_MIN_OFFSET;
921 
922   if (reason != GATT_SUCCESS) {
923     osi_free(p_msg);
924 
925     /* in theroy BUSY is not possible(should already been checked), protected
926      * check */
927     if (reason != GATT_PENDING && reason != GATT_BUSY)
928       gatt_send_error_rsp(tcb, cid, reason, op_code, s_hdl, false);
929 
930     return;
931   }
932 
933   attp_send_sr_msg(tcb, cid, p_msg);
934 }
935 
936 /**
937  * This function is called to process the write request from client.
938  */
gatts_process_write_req(tGATT_TCB & tcb,uint16_t cid,tGATT_SRV_LIST_ELEM & el,uint16_t handle,uint8_t op_code,uint16_t len,uint8_t * p_data,bt_gatt_db_attribute_type_t gatt_type)939 static void gatts_process_write_req(tGATT_TCB& tcb, uint16_t cid,
940                                     tGATT_SRV_LIST_ELEM& el, uint16_t handle,
941                                     uint8_t op_code, uint16_t len,
942                                     uint8_t* p_data,
943                                     bt_gatt_db_attribute_type_t gatt_type) {
944   tGATTS_DATA sr_data;
945   uint32_t trans_id;
946   tGATT_STATUS status;
947   tGATT_SEC_FLAG sec_flag;
948   uint8_t key_size, *p = p_data;
949   uint16_t conn_id;
950 
951   memset(&sr_data, 0, sizeof(tGATTS_DATA));
952 
953   switch (op_code) {
954     case GATT_REQ_PREPARE_WRITE:
955       if (len < 2 || p == nullptr) {
956         LOG(ERROR) << __func__
957                    << ": Prepare write request was invalid - missing offset, "
958                       "sending error response";
959         gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, op_code, handle, false);
960         return;
961       }
962       sr_data.write_req.is_prep = true;
963       STREAM_TO_UINT16(sr_data.write_req.offset, p);
964       len -= 2;
965       FALLTHROUGH_INTENDED; /* FALLTHROUGH */
966     case GATT_SIGN_CMD_WRITE:
967       if (op_code == GATT_SIGN_CMD_WRITE) {
968         VLOG(1) << "Write CMD with data sigining";
969         len -= GATT_AUTH_SIGN_LEN;
970       }
971       FALLTHROUGH_INTENDED; /* FALLTHROUGH */
972     case GATT_CMD_WRITE:
973     case GATT_REQ_WRITE:
974       if (op_code == GATT_REQ_WRITE || op_code == GATT_REQ_PREPARE_WRITE)
975         sr_data.write_req.need_rsp = true;
976       sr_data.write_req.handle = handle;
977       if (len > GATT_MAX_ATTR_LEN) len = GATT_MAX_ATTR_LEN;
978       sr_data.write_req.len = len;
979       if (len != 0 && p != nullptr) {
980         memcpy(sr_data.write_req.value, p, len);
981       }
982       break;
983   }
984 
985   gatt_sr_get_sec_info(tcb.peer_bda, tcb.transport, &sec_flag, &key_size);
986 
987   status = gatts_write_attr_perm_check(el.p_db, op_code, handle,
988                                        sr_data.write_req.offset, p, len,
989                                        sec_flag, key_size);
990 
991   if (status == GATT_SUCCESS) {
992     trans_id = gatt_sr_enqueue_cmd(tcb, cid, op_code, handle);
993     if (trans_id != 0) {
994       conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, el.gatt_if);
995 
996       uint8_t opcode = 0;
997       if (gatt_type == BTGATT_DB_DESCRIPTOR) {
998         opcode = GATTS_REQ_TYPE_WRITE_DESCRIPTOR;
999       } else if (gatt_type == BTGATT_DB_CHARACTERISTIC) {
1000         opcode = GATTS_REQ_TYPE_WRITE_CHARACTERISTIC;
1001       } else {
1002         LOG(ERROR) << __func__
1003                    << "%s: Attempt to write attribute that's not tied with"
1004                       " characteristic or descriptor value.";
1005         status = GATT_ERROR;
1006       }
1007 
1008       if (opcode) {
1009         gatt_sr_send_req_callback(conn_id, trans_id, opcode, &sr_data);
1010         status = GATT_PENDING;
1011       }
1012     } else {
1013       LOG(ERROR) << "max pending command, send error";
1014       status = GATT_BUSY; /* max pending command, application error */
1015     }
1016   }
1017 
1018   /* in theroy BUSY is not possible(should already been checked), protected
1019    * check */
1020   if (status != GATT_PENDING && status != GATT_BUSY &&
1021       (op_code == GATT_REQ_PREPARE_WRITE || op_code == GATT_REQ_WRITE)) {
1022     gatt_send_error_rsp(tcb, cid, status, op_code, handle, false);
1023   }
1024   return;
1025 }
1026 
1027 /**
1028  * This function is called to process the read request from client.
1029  */
gatts_process_read_req(tGATT_TCB & tcb,uint16_t cid,tGATT_SRV_LIST_ELEM & el,uint8_t op_code,uint16_t handle,uint16_t len,uint8_t * p_data)1030 static void gatts_process_read_req(tGATT_TCB& tcb, uint16_t cid,
1031                                    tGATT_SRV_LIST_ELEM& el, uint8_t op_code,
1032                                    uint16_t handle, uint16_t len,
1033                                    uint8_t* p_data) {
1034   uint16_t payload_size = gatt_tcb_get_payload_size_tx(tcb, cid);
1035 
1036   size_t buf_len = sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET;
1037   uint16_t offset = 0;
1038 
1039   if (op_code == GATT_REQ_READ_BLOB && len < sizeof(uint16_t)) {
1040     /* Error: packet length is too short */
1041     LOG(ERROR) << __func__ << ": packet length=" << len
1042                << " too short. min=" << sizeof(uint16_t);
1043     gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, op_code, 0, false);
1044     return;
1045   }
1046 
1047   BT_HDR* p_msg = (BT_HDR*)osi_calloc(buf_len);
1048 
1049   if (op_code == GATT_REQ_READ_BLOB) STREAM_TO_UINT16(offset, p_data);
1050 
1051   uint8_t* p = (uint8_t*)(p_msg + 1) + L2CAP_MIN_OFFSET;
1052   *p++ = op_code + 1;
1053   p_msg->len = 1;
1054   buf_len = payload_size - 1;
1055 
1056   tGATT_SEC_FLAG sec_flag;
1057   uint8_t key_size;
1058   gatt_sr_get_sec_info(tcb.peer_bda, tcb.transport, &sec_flag, &key_size);
1059 
1060   uint16_t value_len = 0;
1061   tGATT_STATUS reason = gatts_read_attr_value_by_handle(
1062       tcb, cid, el.p_db, op_code, handle, offset, p, &value_len,
1063       (uint16_t)buf_len, sec_flag, key_size, 0);
1064   p_msg->len += value_len;
1065 
1066   if (reason != GATT_SUCCESS) {
1067     osi_free(p_msg);
1068 
1069     /* in theory BUSY is not possible(should already been checked), protected
1070      * check */
1071     if (reason != GATT_PENDING && reason != GATT_BUSY)
1072       gatt_send_error_rsp(tcb, cid, reason, op_code, handle, false);
1073 
1074     return;
1075   }
1076 
1077   attp_send_sr_msg(tcb, cid, p_msg);
1078 }
1079 
1080 /*******************************************************************************
1081  *
1082  * Function         gatts_process_attribute_req
1083  *
1084  * Description      This function is called to process the per attribute handle
1085  *                  request from client.
1086  *
1087  * Returns          void
1088  *
1089  ******************************************************************************/
gatts_process_attribute_req(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t len,uint8_t * p_data)1090 void gatts_process_attribute_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code,
1091                                  uint16_t len, uint8_t* p_data) {
1092   uint16_t handle = 0;
1093   uint8_t* p = p_data;
1094   tGATT_STATUS status = GATT_INVALID_HANDLE;
1095 
1096   if (len < 2) {
1097     LOG(ERROR) << "Illegal PDU length, discard request";
1098     status = GATT_INVALID_PDU;
1099   } else {
1100     STREAM_TO_UINT16(handle, p);
1101     len -= 2;
1102   }
1103 
1104 #if (GATT_CONFORMANCE_TESTING == TRUE)
1105   gatt_cb.handle = handle;
1106   if (gatt_cb.enable_err_rsp && gatt_cb.req_op_code == op_code) {
1107     VLOG(1) << "Conformance tst: forced err rsp: error status="
1108             << +gatt_cb.err_status;
1109 
1110     gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, cid, gatt_cb.req_op_code,
1111                         handle, false);
1112 
1113     return;
1114   }
1115 #endif
1116 
1117   if (GATT_HANDLE_IS_VALID(handle)) {
1118     for (auto& el : *gatt_cb.srv_list_info) {
1119       if (el.s_hdl <= handle && el.e_hdl >= handle) {
1120         for (const auto& attr : el.p_db->attr_list) {
1121           if (attr.handle == handle) {
1122             switch (op_code) {
1123               case GATT_REQ_READ: /* read char/char descriptor value */
1124               case GATT_REQ_READ_BLOB:
1125                 gatts_process_read_req(tcb, cid, el, op_code, handle, len, p);
1126                 break;
1127 
1128               case GATT_REQ_WRITE: /* write char/char descriptor value */
1129               case GATT_CMD_WRITE:
1130               case GATT_SIGN_CMD_WRITE:
1131               case GATT_REQ_PREPARE_WRITE:
1132                 gatts_process_write_req(tcb, cid, el, handle, op_code, len, p,
1133                                         attr.gatt_type);
1134                 break;
1135               default:
1136                 break;
1137             }
1138             status = GATT_SUCCESS;
1139             break;
1140           }
1141         }
1142         break;
1143       }
1144     }
1145   }
1146 
1147   if (status != GATT_SUCCESS && op_code != GATT_CMD_WRITE &&
1148       op_code != GATT_SIGN_CMD_WRITE)
1149     gatt_send_error_rsp(tcb, cid, status, op_code, handle, false);
1150 }
1151 
1152 /*******************************************************************************
1153  *
1154  * Function         gatts_proc_srv_chg_ind_ack
1155  *
1156  * Description      This function process the service changed indicaiton ACK
1157  *
1158  * Returns          void
1159  *
1160  ******************************************************************************/
gatts_proc_srv_chg_ind_ack(tGATT_TCB tcb)1161 void gatts_proc_srv_chg_ind_ack(tGATT_TCB tcb) {
1162   tGATTS_SRV_CHG_REQ req;
1163   tGATTS_SRV_CHG* p_buf = NULL;
1164 
1165   VLOG(1) << __func__;
1166 
1167   p_buf = gatt_is_bda_in_the_srv_chg_clt_list(tcb.peer_bda);
1168   if (p_buf != NULL) {
1169     VLOG(1) << "NV update set srv chg = false";
1170     p_buf->srv_changed = false;
1171     memcpy(&req.srv_chg, p_buf, sizeof(tGATTS_SRV_CHG));
1172     if (gatt_cb.cb_info.p_srv_chg_callback)
1173       (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_UPDATE_CLIENT,
1174                                             &req, NULL);
1175   }
1176 }
1177 
1178 /*******************************************************************************
1179  *
1180  * Function         gatts_chk_pending_ind
1181  *
1182  * Description      This function check any pending indication needs to be sent
1183  *                  if there is a pending indication then sent the indication
1184  *
1185  * Returns          void
1186  *
1187  ******************************************************************************/
gatts_chk_pending_ind(tGATT_TCB & tcb)1188 static void gatts_chk_pending_ind(tGATT_TCB& tcb) {
1189   VLOG(1) << __func__;
1190 
1191   tGATT_VALUE* p_buf =
1192       (tGATT_VALUE*)fixed_queue_try_peek_first(tcb.pending_ind_q);
1193   if (p_buf != NULL) {
1194     GATTS_HandleValueIndication(p_buf->conn_id, p_buf->handle, p_buf->len,
1195                                 p_buf->value);
1196     osi_free(fixed_queue_try_remove_from_queue(tcb.pending_ind_q, p_buf));
1197   }
1198 }
1199 
1200 /*******************************************************************************
1201  *
1202  * Function         gatts_proc_ind_ack
1203  *
1204  * Description      This function processes the Indication ack
1205  *
1206  * Returns          true continue to process the indication ack by the
1207  *                  application if the ACK is not a Service Changed Indication
1208  *
1209  ******************************************************************************/
gatts_proc_ind_ack(tGATT_TCB & tcb,uint16_t ack_handle)1210 static bool gatts_proc_ind_ack(tGATT_TCB& tcb, uint16_t ack_handle) {
1211   bool continue_processing = true;
1212 
1213   VLOG(1) << __func__ << " ack handle=%d" << ack_handle;
1214 
1215   if (ack_handle == gatt_cb.handle_of_h_r) {
1216     gatts_proc_srv_chg_ind_ack(tcb);
1217     /* there is no need to inform the application since srv chg is handled
1218      * internally by GATT */
1219     continue_processing = false;
1220 
1221     // After receiving ack of svc_chg_ind, reset client status
1222     gatt_sr_update_cl_status(tcb, /* chg_aware= */ true);
1223   }
1224 
1225   gatts_chk_pending_ind(tcb);
1226   return continue_processing;
1227 }
1228 
1229 /*******************************************************************************
1230  *
1231  * Function         gatts_process_value_conf
1232  *
1233  * Description      This function is called to process the handle value
1234  *                  confirmation.
1235  *
1236  * Returns          void
1237  *
1238  ******************************************************************************/
gatts_process_value_conf(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code)1239 void gatts_process_value_conf(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code) {
1240   uint16_t handle;
1241 
1242   if (!gatt_tcb_find_indicate_handle(tcb, cid, &handle)) {
1243     LOG(ERROR) << "unexpected handle value confirmation";
1244     return;
1245   }
1246 
1247   gatt_stop_conf_timer(tcb, cid);
1248 
1249   bool continue_processing = gatts_proc_ind_ack(tcb, handle);
1250 
1251   if (continue_processing) {
1252     tGATTS_DATA gatts_data;
1253     gatts_data.handle = handle;
1254     for (auto& el : *gatt_cb.srv_list_info) {
1255       if (el.s_hdl <= handle && el.e_hdl >= handle) {
1256         uint32_t trans_id = gatt_sr_enqueue_cmd(tcb, cid, op_code, handle);
1257         uint16_t conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, el.gatt_if);
1258         gatt_sr_send_req_callback(conn_id, trans_id, GATTS_REQ_TYPE_CONF,
1259                                   &gatts_data);
1260       }
1261     }
1262   }
1263 }
1264 
gatts_process_db_out_of_sync(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t len,uint8_t * p_data)1265 static bool gatts_process_db_out_of_sync(tGATT_TCB& tcb, uint16_t cid,
1266                                          uint8_t op_code, uint16_t len,
1267                                          uint8_t* p_data) {
1268   if (gatt_sr_is_cl_change_aware(tcb)) return false;
1269 
1270   // default value
1271   bool should_ignore = true;
1272   bool should_rsp = true;
1273 
1274   switch (op_code) {
1275     case GATT_REQ_READ_BY_TYPE: {
1276       // Check if read database hash by UUID
1277       Uuid uuid = Uuid::kEmpty;
1278       uint16_t s_hdl = 0, e_hdl = 0;
1279       uint16_t db_hash_handle = gatt_cb.handle_of_database_hash;
1280       tGATT_STATUS reason = gatts_validate_packet_format(op_code, len, p_data,
1281                                                          &uuid, s_hdl, e_hdl);
1282       if (reason == GATT_SUCCESS &&
1283           (s_hdl <= db_hash_handle && db_hash_handle <= e_hdl) &&
1284           (uuid == Uuid::From16Bit(GATT_UUID_DATABASE_HASH)))
1285         should_ignore = false;
1286 
1287     } break;
1288     case GATT_REQ_READ: {
1289       // Check if read database hash by handle
1290       uint16_t handle = 0;
1291       uint8_t* p = p_data;
1292       tGATT_STATUS status = GATT_SUCCESS;
1293 
1294       if (len < 2) {
1295         status = GATT_INVALID_PDU;
1296       } else {
1297         STREAM_TO_UINT16(handle, p);
1298         len -= 2;
1299       }
1300 
1301       if (status == GATT_SUCCESS && handle == gatt_cb.handle_of_database_hash)
1302         should_ignore = false;
1303 
1304     } break;
1305     case GATT_REQ_READ_BY_GRP_TYPE: /* discover primary services */
1306     case GATT_REQ_FIND_TYPE_VALUE:  /* discover service by UUID */
1307     case GATT_REQ_FIND_INFO:        /* discover char descrptor */
1308     case GATT_REQ_READ_BLOB:        /* read long char */
1309     case GATT_REQ_READ_MULTI:       /* read multi char*/
1310     case GATT_REQ_WRITE:            /* write char/char descriptor value */
1311     case GATT_REQ_PREPARE_WRITE:    /* write long char */
1312       // Use default value
1313       break;
1314     case GATT_CMD_WRITE:      /* cmd */
1315     case GATT_SIGN_CMD_WRITE: /* sign cmd */
1316       should_rsp = false;
1317       break;
1318     case GATT_REQ_MTU:           /* configure mtu */
1319     case GATT_REQ_EXEC_WRITE:    /* execute write */
1320     case GATT_HANDLE_VALUE_CONF: /* confirm for indication */
1321     default:
1322       should_ignore = false;
1323   }
1324 
1325   if (should_ignore) {
1326     if (should_rsp) {
1327       gatt_send_error_rsp(tcb, cid, GATT_DATABASE_OUT_OF_SYNC, op_code, 0x0000,
1328                           false);
1329     }
1330     LOG(INFO) << __func__ << ": database out of sync, device=" << tcb.peer_bda
1331               << ", op_code=" << loghex((uint16_t)op_code)
1332               << ", should_rsp=" << should_rsp;
1333     gatt_sr_update_cl_status(tcb, /* chg_aware= */ should_rsp);
1334   }
1335 
1336   return should_ignore;
1337 }
1338 
1339 /** This function is called to handle the client requests to server */
gatt_server_handle_client_req(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t len,uint8_t * p_data)1340 void gatt_server_handle_client_req(tGATT_TCB& tcb, uint16_t cid,
1341                                    uint8_t op_code, uint16_t len,
1342                                    uint8_t* p_data) {
1343   /* there is pending command, discard this one */
1344   if (!gatt_sr_cmd_empty(tcb, cid) && op_code != GATT_HANDLE_VALUE_CONF) return;
1345 
1346   /* the size of the message may not be bigger than the local max PDU size*/
1347   /* The message has to be smaller than the agreed MTU, len does not include op
1348    * code */
1349 
1350   uint16_t payload_size = gatt_tcb_get_payload_size_rx(tcb, cid);
1351   if (len >= payload_size) {
1352     LOG(ERROR) << StringPrintf("server receive invalid PDU size:%d pdu size:%d",
1353                                len + 1, payload_size);
1354     /* for invalid request expecting response, send it now */
1355     if (op_code != GATT_CMD_WRITE && op_code != GATT_SIGN_CMD_WRITE &&
1356         op_code != GATT_HANDLE_VALUE_CONF) {
1357       gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, op_code, 0, false);
1358     }
1359     /* otherwise, ignore the pkt */
1360   } else {
1361     // handle database out of sync
1362     if (gatts_process_db_out_of_sync(tcb, cid, op_code, len, p_data)) return;
1363 
1364     switch (op_code) {
1365       case GATT_REQ_READ_BY_GRP_TYPE: /* discover primary services */
1366       case GATT_REQ_FIND_TYPE_VALUE:  /* discover service by UUID */
1367         gatts_process_primary_service_req(tcb, cid, op_code, len, p_data);
1368         break;
1369 
1370       case GATT_REQ_FIND_INFO: /* discover char descrptor */
1371         gatts_process_find_info(tcb, cid, op_code, len, p_data);
1372         break;
1373 
1374       case GATT_REQ_READ_BY_TYPE: /* read characteristic value, char descriptor
1375                                      value */
1376         /* discover characteristic, discover char by UUID */
1377         gatts_process_read_by_type_req(tcb, cid, op_code, len, p_data);
1378         break;
1379 
1380       case GATT_REQ_READ: /* read char/char descriptor value */
1381       case GATT_REQ_READ_BLOB:
1382       case GATT_REQ_WRITE: /* write char/char descriptor value */
1383       case GATT_CMD_WRITE:
1384       case GATT_SIGN_CMD_WRITE:
1385       case GATT_REQ_PREPARE_WRITE:
1386         gatts_process_attribute_req(tcb, cid, op_code, len, p_data);
1387         break;
1388 
1389       case GATT_HANDLE_VALUE_CONF:
1390         gatts_process_value_conf(tcb, cid, op_code);
1391         break;
1392 
1393       case GATT_REQ_MTU:
1394         gatts_process_mtu_req(tcb, cid, len, p_data);
1395         break;
1396 
1397       case GATT_REQ_EXEC_WRITE:
1398         gatt_process_exec_write_req(tcb, cid, op_code, len, p_data);
1399         break;
1400 
1401       case GATT_REQ_READ_MULTI:
1402       case GATT_REQ_READ_MULTI_VAR:
1403         gatt_process_read_multi_req(tcb, cid, op_code, len, p_data);
1404         break;
1405 
1406       default:
1407         break;
1408     }
1409   }
1410 }
1411