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