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