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