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