1 /******************************************************************************
2  *
3  *  Copyright 2009-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 GATT database building and query functions
22  *
23  ******************************************************************************/
24 
25 #include <bluetooth/log.h>
26 #include <string.h>
27 
28 #include "gatt_int.h"
29 #include "l2c_api.h"
30 #include "osi/include/osi.h"
31 #include "stack/include/bt_hdr.h"
32 #include "stack/include/bt_types.h"
33 #include "types/bluetooth/uuid.h"
34 
35 using bluetooth::Uuid;
36 using namespace bluetooth;
37 
38 /*******************************************************************************
39  *             L O C A L    F U N C T I O N     P R O T O T Y P E S            *
40  ******************************************************************************/
41 static tGATT_ATTR& allocate_attr_in_db(tGATT_SVC_DB& db, const Uuid& uuid,
42                                        tGATT_PERM perm);
43 static tGATT_STATUS gatts_send_app_read_request(
44     tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t handle,
45     uint16_t offset, uint32_t trans_id, bt_gatt_db_attribute_type_t gatt_type);
46 
47 /**
48  * Initialize a memory space to be a service database.
49  */
gatts_init_service_db(tGATT_SVC_DB & db,const Uuid & service_uuid,bool is_pri,uint16_t s_hdl,uint16_t num_handle)50 void gatts_init_service_db(tGATT_SVC_DB& db, const Uuid& service_uuid,
51                            bool is_pri, uint16_t s_hdl, uint16_t num_handle) {
52   db.attr_list.reserve(num_handle);
53 
54   log::verbose("s_hdl= {} num_handle= {}", s_hdl, num_handle);
55 
56   /* update service database information */
57   db.next_handle = s_hdl;
58   db.end_handle = s_hdl + num_handle;
59 
60   /* add service declration record */
61   Uuid uuid =
62       Uuid::From16Bit(is_pri ? GATT_UUID_PRI_SERVICE : GATT_UUID_SEC_SERVICE);
63   tGATT_ATTR& attr = allocate_attr_in_db(db, uuid, GATT_PERM_READ);
64   attr.p_value.reset(new tGATT_ATTR_VALUE);
65   attr.p_value->uuid = service_uuid;
66 }
67 
gatts_get_service_uuid(tGATT_SVC_DB * p_db)68 Uuid* gatts_get_service_uuid(tGATT_SVC_DB* p_db) {
69   if (!p_db || p_db->attr_list.empty()) {
70     log::error("service DB empty");
71     return NULL;
72   } else {
73     return &p_db->attr_list[0].p_value->uuid;
74   }
75 }
76 
77 /** Check attribute readability. Returns status of operation. */
gatts_check_attr_readability(const tGATT_ATTR & attr,uint16_t,bool read_long,tGATT_SEC_FLAG sec_flag,uint8_t key_size)78 static tGATT_STATUS gatts_check_attr_readability(const tGATT_ATTR& attr,
79                                                  uint16_t /* offset */,
80                                                  bool read_long,
81                                                  tGATT_SEC_FLAG sec_flag,
82                                                  uint8_t key_size) {
83   uint16_t min_key_size;
84   tGATT_PERM perm = attr.permission;
85 
86   min_key_size = (((perm & GATT_ENCRYPT_KEY_SIZE_MASK) >> 12));
87   if (min_key_size != 0) {
88     min_key_size += 6;
89   }
90 
91   if (!(perm & GATT_READ_ALLOWED)) {
92     log::error("GATT_READ_NOT_PERMIT");
93     return GATT_READ_NOT_PERMIT;
94   }
95 
96   if ((perm & GATT_READ_AUTH_REQUIRED) && !sec_flag.is_link_key_known &&
97       !sec_flag.is_encrypted) {
98     log::error("GATT_INSUF_AUTHENTICATION");
99     return GATT_INSUF_AUTHENTICATION;
100   }
101 
102   if ((perm & GATT_READ_MITM_REQUIRED) && !sec_flag.is_link_key_authed) {
103     log::error("GATT_INSUF_AUTHENTICATION: MITM Required");
104     return GATT_INSUF_AUTHENTICATION;
105   }
106 
107   if ((perm & GATT_READ_ENCRYPTED_REQUIRED) && !sec_flag.is_encrypted) {
108     log::error("GATT_INSUF_ENCRYPTION");
109     return GATT_INSUF_ENCRYPTION;
110   }
111 
112   if ((perm & GATT_READ_ENCRYPTED_REQUIRED) && sec_flag.is_encrypted &&
113       (key_size < min_key_size)) {
114     log::error("GATT_INSUF_KEY_SIZE");
115     return GATT_INSUF_KEY_SIZE;
116   }
117 
118   if (perm & GATT_PERM_READ_IF_ENCRYPTED_OR_DISCOVERABLE) {
119     if (sec_flag.can_read_discoverable_characteristics) {
120       // no checks here
121     } else {
122       if (!sec_flag.is_link_key_known || !sec_flag.is_encrypted) {
123         return GATT_INSUF_AUTHENTICATION;
124       }
125       if (key_size < min_key_size) {
126         return GATT_INSUF_KEY_SIZE;
127       }
128     }
129   }
130 
131   if (read_long && attr.uuid.Is16Bit()) {
132     switch (attr.uuid.As16Bit()) {
133       case GATT_UUID_PRI_SERVICE:
134       case GATT_UUID_SEC_SERVICE:
135       case GATT_UUID_CHAR_DECLARE:
136       case GATT_UUID_INCLUDE_SERVICE:
137       case GATT_UUID_CHAR_EXT_PROP:
138       case GATT_UUID_CHAR_CLIENT_CONFIG:
139       case GATT_UUID_CHAR_SRVR_CONFIG:
140       case GATT_UUID_CHAR_PRESENT_FORMAT:
141         log::error("GATT_NOT_LONG");
142         return GATT_NOT_LONG;
143 
144       default:
145         break;
146     }
147   }
148 
149   return GATT_SUCCESS;
150 }
151 
152 /*******************************************************************************
153  *
154  * Function         read_attr_value
155  *
156  * Description      Utility function to read an attribute value.
157  *
158  * Parameter        attr16: pointer to the attribute to read.
159  *                  offset: read offset.
160  *                  p_data: output parameter to carry out the attribute value.
161  *                  read_long: this is a read blob request.
162  *                  mtu: MTU
163  *                  p_len: output parameter to carry out the attribute length.
164  *                   sec_flag: current link security status.
165  *                  key_size: encryption key size.
166  *
167  * Returns          status of operation.
168  *
169  ******************************************************************************/
read_attr_value(tGATT_ATTR & attr16,uint16_t offset,uint8_t ** p_data,bool read_long,uint16_t mtu,uint16_t * p_len,tGATT_SEC_FLAG sec_flag,uint8_t key_size)170 static tGATT_STATUS read_attr_value(tGATT_ATTR& attr16, uint16_t offset,
171                                     uint8_t** p_data, bool read_long,
172                                     uint16_t mtu, uint16_t* p_len,
173                                     tGATT_SEC_FLAG sec_flag, uint8_t key_size) {
174   uint8_t* p = *p_data;
175 
176   log::verbose("uuid={} perm=0x{:02x} offset={} read_long={}", attr16.uuid,
177                attr16.permission, offset, read_long);
178 
179   tGATT_STATUS status = gatts_check_attr_readability(attr16, offset, read_long,
180                                                      sec_flag, key_size);
181   if (status != GATT_SUCCESS) return status;
182 
183   if (!attr16.uuid.Is16Bit()) {
184     /* characteristic description or characteristic value */
185     return GATT_PENDING;
186   }
187 
188   uint16_t uuid16 = attr16.uuid.As16Bit();
189 
190   if (uuid16 == GATT_UUID_PRI_SERVICE || uuid16 == GATT_UUID_SEC_SERVICE) {
191     *p_len = gatt_build_uuid_to_stream_len(attr16.p_value->uuid);
192     if (mtu < *p_len) return GATT_NO_RESOURCES;
193 
194     gatt_build_uuid_to_stream(&p, attr16.p_value->uuid);
195     *p_data = p;
196     return GATT_SUCCESS;
197   }
198 
199   if (uuid16 == GATT_UUID_CHAR_DECLARE) {
200     tGATT_ATTR* val_attr = &attr16 + 1;
201     uint8_t val_len = val_attr->uuid.GetShortestRepresentationSize();
202     *p_len = (val_len == Uuid::kNumBytes16) ? 5 : 19;
203 
204     if (mtu < *p_len) return GATT_NO_RESOURCES;
205 
206     UINT8_TO_STREAM(p, attr16.p_value->char_decl.property);
207     UINT16_TO_STREAM(p, attr16.p_value->char_decl.char_val_handle);
208 
209     if (val_len == Uuid::kNumBytes16) {
210       UINT16_TO_STREAM(p, val_attr->uuid.As16Bit());
211     } else {
212       /* if 32 bit UUID, convert to 128 bit */
213       ARRAY_TO_STREAM(p, val_attr->uuid.To128BitLE(), (int)Uuid::kNumBytes128);
214     }
215     *p_data = p;
216     return GATT_SUCCESS;
217   }
218 
219   if (uuid16 == GATT_UUID_INCLUDE_SERVICE) {
220     tGATT_INCL_SRVC& incl_handle = attr16.p_value->incl_handle;
221     if (incl_handle.service_type.Is16Bit())
222       *p_len = 6;
223     else
224       *p_len = 4;
225 
226     if (mtu < *p_len) return GATT_NO_RESOURCES;
227 
228     UINT16_TO_STREAM(p, incl_handle.s_handle);
229     UINT16_TO_STREAM(p, incl_handle.e_handle);
230 
231     if (incl_handle.service_type.Is16Bit()) {
232       UINT16_TO_STREAM(p, incl_handle.service_type.As16Bit());
233     }
234     *p_data = p;
235     return GATT_SUCCESS;
236   }
237 
238   if (uuid16 == GATT_UUID_CHAR_EXT_PROP) {
239     // sometimes this descriptor is added by users manually, we need to check if
240     // the p_value is nullptr.
241     uint16_t char_ext_prop =
242         attr16.p_value ? attr16.p_value->char_ext_prop : 0x0000;
243     *p_len = 2;
244 
245     if (mtu < *p_len) {
246       return GATT_NO_RESOURCES;
247     }
248 
249     UINT16_TO_STREAM(p, char_ext_prop);
250     *p_data = p;
251     return GATT_SUCCESS;
252   }
253 
254   /* characteristic descriptor or characteristic value (again) */
255   return GATT_PENDING;
256 }
257 
258 /*******************************************************************************
259  *
260  * Function         gatts_db_read_attr_value_by_type
261  *
262  * Description      Query attribute value by attribute type.
263  *
264  * Parameter        p_db: pointer to the attribute database.
265  *                  p_rsp: Read By type response data.
266  *                  s_handle: starting handle of the range we are looking for.
267  *                  e_handle: ending handle of the range we are looking for.
268  *                  type: Attribute type.
269  *                  mtu: MTU.
270  *                  sec_flag: current link security status.
271  *                  key_size: encryption key size.
272  *
273  * Returns          Status of the operation.
274  *
275  ******************************************************************************/
gatts_db_read_attr_value_by_type(tGATT_TCB & tcb,uint16_t cid,tGATT_SVC_DB * p_db,uint8_t op_code,BT_HDR * p_rsp,uint16_t s_handle,uint16_t,const Uuid & type,uint16_t * p_len,tGATT_SEC_FLAG sec_flag,uint8_t key_size,uint32_t trans_id,uint16_t * p_cur_handle)276 tGATT_STATUS gatts_db_read_attr_value_by_type(
277     tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, uint8_t op_code,
278     BT_HDR* p_rsp, uint16_t s_handle, uint16_t /* e_handle */, const Uuid& type,
279     uint16_t* p_len, tGATT_SEC_FLAG sec_flag, uint8_t key_size,
280     uint32_t trans_id, uint16_t* p_cur_handle) {
281   tGATT_STATUS status = GATT_NOT_FOUND;
282   uint16_t len = 0;
283   uint8_t* p = (uint8_t*)(p_rsp + 1) + p_rsp->len + L2CAP_MIN_OFFSET;
284 
285   if (p_db) {
286     for (tGATT_ATTR& attr : p_db->attr_list) {
287       if (attr.handle >= s_handle && type == attr.uuid) {
288         if (*p_len <= 2) {
289           status = GATT_NO_RESOURCES;
290           break;
291         }
292 
293         UINT16_TO_STREAM(p, attr.handle);
294 
295         status = read_attr_value(attr, 0, &p, false, (uint16_t)(*p_len - 2),
296                                  &len, sec_flag, key_size);
297 
298         if (status == GATT_PENDING) {
299           status = gatts_send_app_read_request(tcb, cid, op_code, attr.handle,
300                                                0, trans_id, attr.gatt_type);
301 
302           /* one callback at a time */
303           break;
304         } else if (status == GATT_SUCCESS) {
305           if (p_rsp->offset == 0) p_rsp->offset = len + 2;
306 
307           if (p_rsp->offset == len + 2) {
308             p_rsp->len += (len + 2);
309             *p_len -= (len + 2);
310           } else {
311             log::error("format mismatch");
312             status = GATT_NO_RESOURCES;
313             break;
314           }
315         } else {
316           *p_cur_handle = attr.handle;
317           break;
318         }
319       }
320     }
321   }
322 
323   return status;
324 }
325 
326 /**
327  * This function adds an included service into a database.
328  *
329  * Parameter        db: database pointer.
330  *                  inc_srvc_type: included service type.
331  *
332  * Returns          Status of the operation.
333  *
334  */
gatts_add_included_service(tGATT_SVC_DB & db,uint16_t s_handle,uint16_t e_handle,const Uuid & service)335 uint16_t gatts_add_included_service(tGATT_SVC_DB& db, uint16_t s_handle,
336                                     uint16_t e_handle, const Uuid& service) {
337   Uuid uuid = Uuid::From16Bit(GATT_UUID_INCLUDE_SERVICE);
338 
339   log::verbose("s_hdl=0x{:04x} e_hdl=0x{:04x} service uuid = {}", s_handle,
340                e_handle, service);
341 
342   if (service.IsEmpty() || s_handle == 0 || e_handle == 0) {
343     log::error("Illegal Params.");
344     return 0;
345   }
346 
347   tGATT_ATTR& attr = allocate_attr_in_db(db, uuid, GATT_PERM_READ);
348 
349   attr.p_value.reset(new tGATT_ATTR_VALUE);
350   attr.p_value->incl_handle.s_handle = s_handle;
351   attr.p_value->incl_handle.e_handle = e_handle;
352   attr.p_value->incl_handle.service_type = service;
353 
354   return attr.handle;
355 }
356 
357 /*******************************************************************************
358  *
359  * Function         gatts_add_characteristic
360  *
361  * Description      This function add a characteristics and its descriptor into
362  *                  a servce identified by the service database pointer.
363  *
364  * Parameter        db: database.
365  *                  perm: permission (authentication and key size requirements)
366  *                  property: property of the characteristic.
367  *                  extended_properties: characteristic extended properties.
368  *                  p_char: characteristic value information.
369  *
370  * Returns          Status of te operation.
371  *
372  ******************************************************************************/
gatts_add_characteristic(tGATT_SVC_DB & db,tGATT_PERM perm,tGATT_CHAR_PROP property,const Uuid & char_uuid)373 uint16_t gatts_add_characteristic(tGATT_SVC_DB& db, tGATT_PERM perm,
374                                   tGATT_CHAR_PROP property,
375                                   const Uuid& char_uuid) {
376   Uuid uuid = Uuid::From16Bit(GATT_UUID_CHAR_DECLARE);
377 
378   log::verbose("perm=0x{:0x} property=0x{:0x}", perm, property);
379 
380   tGATT_ATTR& char_decl = allocate_attr_in_db(db, uuid, GATT_PERM_READ);
381   tGATT_ATTR& char_val = allocate_attr_in_db(db, char_uuid, perm);
382 
383   char_decl.p_value.reset(new tGATT_ATTR_VALUE);
384   char_decl.p_value->char_decl.property = property;
385   char_decl.p_value->char_decl.char_val_handle = char_val.handle;
386   char_val.gatt_type = BTGATT_DB_CHARACTERISTIC;
387 
388   return char_val.handle;
389 }
390 
391 /*******************************************************************************
392  *
393  * Function         gatts_add_char_ext_prop_descr
394  *
395  * Description      add a characteristics extended properties descriptor.
396  *
397  * Parameter        db: database pointer.
398  *                  extended_properties: characteristic descriptors values.
399  *
400  * Returns          Status of the operation.
401  *
402  ******************************************************************************/
gatts_add_char_ext_prop_descr(tGATT_SVC_DB & db,uint16_t extended_properties)403 uint16_t gatts_add_char_ext_prop_descr(
404     tGATT_SVC_DB& db, uint16_t extended_properties) {
405   Uuid descr_uuid = Uuid::From16Bit(GATT_UUID_CHAR_EXT_PROP);
406 
407   log::verbose("gatts_add_char_ext_prop_descr uuid={}", descr_uuid.ToString());
408 
409   tGATT_ATTR& char_dscptr = allocate_attr_in_db(db, descr_uuid, GATT_PERM_READ);
410   char_dscptr.gatt_type = BTGATT_DB_DESCRIPTOR;
411   char_dscptr.p_value.reset(new tGATT_ATTR_VALUE);
412   char_dscptr.p_value->char_ext_prop = extended_properties;
413 
414   return char_dscptr.handle;
415 }
416 
417 /*******************************************************************************
418  *
419  * Function         gatts_add_char_descr
420  *
421  * Description      This function add a characteristics descriptor.
422  *
423  * Parameter        p_db: database pointer.
424  *                  perm: characteristic descriptor permission type.
425  *                  char_dscp_tpye: the characteristic descriptor masks.
426  *                  p_dscp_params: characteristic descriptors values.
427  *
428  * Returns          Status of the operation.
429  *
430  ******************************************************************************/
gatts_add_char_descr(tGATT_SVC_DB & db,tGATT_PERM perm,const Uuid & descr_uuid)431 uint16_t gatts_add_char_descr(tGATT_SVC_DB& db, tGATT_PERM perm,
432                               const Uuid& descr_uuid) {
433   log::verbose("gatts_add_char_descr uuid={}", descr_uuid.ToString());
434 
435   /* Add characteristic descriptors */
436   tGATT_ATTR& char_dscptr = allocate_attr_in_db(db, descr_uuid, perm);
437   char_dscptr.gatt_type = BTGATT_DB_DESCRIPTOR;
438   return char_dscptr.handle;
439 }
440 
441 /******************************************************************************/
442 /* Service Attribute Database Query Utility Functions */
443 /******************************************************************************/
find_attr_by_handle(tGATT_SVC_DB * p_db,uint16_t handle)444 tGATT_ATTR* find_attr_by_handle(tGATT_SVC_DB* p_db, uint16_t handle) {
445   if (!p_db) return nullptr;
446 
447   for (auto& attr : p_db->attr_list) {
448     if (attr.handle == handle) return &attr;
449     if (attr.handle > handle) return nullptr;
450   }
451 
452   return nullptr;
453 }
454 
455 /*******************************************************************************
456  *
457  * Function         gatts_read_attr_value_by_handle
458  *
459  * Description      Query attribute value by attribute handle.
460  *
461  * Parameter        p_db: pointer to the attribute database.
462  *                  handle: Attribute handle to read.
463  *                  offset: Read offset.
464  *                  p_value: output parameter to carry out the attribute value.
465  *                  p_len: output parameter as attribute length read.
466  *                  read_long: this is a read blob request.
467  *                  mtu: MTU.
468  *                  sec_flag: current link security status.
469  *                  key_size: encryption key size
470  *
471  * Returns          Status of operation.
472  *
473  ******************************************************************************/
gatts_read_attr_value_by_handle(tGATT_TCB & tcb,uint16_t cid,tGATT_SVC_DB * p_db,uint8_t op_code,uint16_t handle,uint16_t offset,uint8_t * p_value,uint16_t * p_len,uint16_t mtu,tGATT_SEC_FLAG sec_flag,uint8_t key_size,uint32_t trans_id)474 tGATT_STATUS gatts_read_attr_value_by_handle(
475     tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, uint8_t op_code,
476     uint16_t handle, uint16_t offset, uint8_t* p_value, uint16_t* p_len,
477     uint16_t mtu, tGATT_SEC_FLAG sec_flag, uint8_t key_size,
478     uint32_t trans_id) {
479   tGATT_ATTR* p_attr = find_attr_by_handle(p_db, handle);
480   if (!p_attr) return GATT_NOT_FOUND;
481 
482   uint8_t* pp = p_value;
483   tGATT_STATUS status = read_attr_value(*p_attr, offset, &pp,
484                                         (bool)(op_code == GATT_REQ_READ_BLOB),
485                                         mtu, p_len, sec_flag, key_size);
486 
487   if (status == GATT_PENDING) {
488     status = gatts_send_app_read_request(tcb, cid, op_code, p_attr->handle,
489                                          offset, trans_id, p_attr->gatt_type);
490   }
491   return status;
492 }
493 
494 /*******************************************************************************
495  *
496  * Function         gatts_read_attr_perm_check
497  *
498  * Description      Check attribute readability.
499  *
500  * Parameter        p_db: pointer to the attribute database.
501  *                  handle: Attribute handle to read.
502  *                  offset: Read offset.
503  *                  p_value: output parameter to carry out the attribute value.
504  *                  p_len: output parameter as attribute length read.
505  *                  read_long: this is a read blob request.
506  *                  mtu: MTU.
507  *                  sec_flag: current link security status.
508  *                  key_size: encryption key size
509  *
510  * Returns          Status of operation.
511  *
512  ******************************************************************************/
gatts_read_attr_perm_check(tGATT_SVC_DB * p_db,bool is_long,uint16_t handle,tGATT_SEC_FLAG sec_flag,uint8_t key_size)513 tGATT_STATUS gatts_read_attr_perm_check(tGATT_SVC_DB* p_db, bool is_long,
514                                         uint16_t handle,
515                                         tGATT_SEC_FLAG sec_flag,
516                                         uint8_t key_size) {
517   tGATT_ATTR* p_attr = find_attr_by_handle(p_db, handle);
518   if (!p_attr) return GATT_NOT_FOUND;
519 
520   return gatts_check_attr_readability(*p_attr, 0, is_long, sec_flag, key_size);
521 }
522 
523 /*******************************************************************************
524  *
525  * Function         gatts_write_attr_perm_check
526  *
527  * Description      Write attribute value into database.
528  *
529  * Parameter        p_db: pointer to the attribute database.
530  *                  op_code:op code of this write.
531  *                  handle: handle of the attribute to write.
532  *                  offset: Write offset if write op code is write blob.
533  *                  p_data: Attribute value to write.
534  *                  len: attribute data length.
535  *                  sec_flag: current link security status.
536  *                  key_size: encryption key size
537  *
538  * Returns          Status of the operation.
539  *
540  ******************************************************************************/
gatts_write_attr_perm_check(tGATT_SVC_DB * p_db,uint8_t op_code,uint16_t handle,uint16_t offset,uint8_t * p_data,uint16_t len,tGATT_SEC_FLAG sec_flag,uint8_t key_size)541 tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code,
542                                          uint16_t handle, uint16_t offset,
543                                          uint8_t* p_data, uint16_t len,
544                                          tGATT_SEC_FLAG sec_flag,
545                                          uint8_t key_size) {
546   log::verbose("op_code=0x{:x} handle=0x{:04x} offset={} len={} key_size={}",
547                op_code, handle, offset, len, key_size);
548 
549   tGATT_ATTR* p_attr = find_attr_by_handle(p_db, handle);
550   if (!p_attr) return GATT_NOT_FOUND;
551 
552   tGATT_PERM perm = p_attr->permission;
553   uint16_t min_key_size = (((perm & GATT_ENCRYPT_KEY_SIZE_MASK) >> 12));
554   if (min_key_size != 0) {
555     min_key_size += 6;
556   }
557   log::verbose("p_attr->permission =0x{:04x} min_key_size==0x{:04x}",
558                p_attr->permission, min_key_size);
559 
560   if ((op_code == GATT_CMD_WRITE || op_code == GATT_REQ_WRITE) &&
561       (perm & GATT_WRITE_SIGNED_PERM)) {
562     /* use the rules for the mixed security see section 10.2.3*/
563     /* use security mode 1 level 2 when the following condition follows */
564     /* LE security mode 2 level 1 and LE security mode 1 level 2 */
565     if ((perm & GATT_PERM_WRITE_SIGNED) && (perm & GATT_PERM_WRITE_ENCRYPTED)) {
566       perm = GATT_PERM_WRITE_ENCRYPTED;
567     }
568     /* use security mode 1 level 3 when the following condition follows */
569     /* LE security mode 2 level 2 and security mode 1 and LE */
570     else if (((perm & GATT_PERM_WRITE_SIGNED_MITM) &&
571               (perm & GATT_PERM_WRITE_ENCRYPTED)) ||
572              /* LE security mode 2 and security mode 1 level 3 */
573              ((perm & GATT_WRITE_SIGNED_PERM) &&
574               (perm & GATT_PERM_WRITE_ENC_MITM))) {
575       perm = GATT_PERM_WRITE_ENC_MITM;
576     }
577   }
578 
579   tGATT_STATUS status = GATT_NOT_FOUND;
580   if ((op_code == GATT_SIGN_CMD_WRITE) && !(perm & GATT_WRITE_SIGNED_PERM)) {
581     status = GATT_WRITE_NOT_PERMIT;
582     log::verbose("sign cmd write not allowed");
583   }
584   if ((op_code == GATT_SIGN_CMD_WRITE) && sec_flag.is_encrypted) {
585     status = GATT_INVALID_PDU;
586     log::error("Error!! sign cmd write sent on a encypted link");
587   } else if (!(perm & GATT_WRITE_ALLOWED)) {
588     status = GATT_WRITE_NOT_PERMIT;
589     log::error("GATT_WRITE_NOT_PERMIT");
590   }
591   /* require authentication, but not been authenticated */
592   else if ((perm & GATT_WRITE_AUTH_REQUIRED) && !sec_flag.is_link_key_known) {
593     status = GATT_INSUF_AUTHENTICATION;
594     log::error("GATT_INSUF_AUTHENTICATION");
595   } else if ((perm & GATT_WRITE_MITM_REQUIRED) &&
596              !sec_flag.is_link_key_authed) {
597     status = GATT_INSUF_AUTHENTICATION;
598     log::error("GATT_INSUF_AUTHENTICATION: MITM required");
599   } else if ((perm & GATT_WRITE_ENCRYPTED_PERM) && !sec_flag.is_encrypted) {
600     status = GATT_INSUF_ENCRYPTION;
601     log::error("GATT_INSUF_ENCRYPTION");
602   } else if ((perm & GATT_WRITE_ENCRYPTED_PERM) && sec_flag.is_encrypted &&
603              (key_size < min_key_size)) {
604     status = GATT_INSUF_KEY_SIZE;
605     log::error("GATT_INSUF_KEY_SIZE");
606   }
607   /* LE security mode 2 attribute  */
608   else if (perm & GATT_WRITE_SIGNED_PERM && op_code != GATT_SIGN_CMD_WRITE &&
609            !sec_flag.is_encrypted && (perm & GATT_WRITE_ALLOWED) == 0) {
610     status = GATT_INSUF_AUTHENTICATION;
611     log::error("GATT_INSUF_AUTHENTICATION: LE security mode 2 required");
612   } else /* writable: must be char value declaration or char descritpors */
613   {
614     uint16_t max_size = 0;
615 
616     if (p_attr->uuid.IsEmpty()) {
617       status = GATT_INVALID_PDU;
618     } else if (p_attr->uuid.Is16Bit()) {
619       switch (p_attr->uuid.As16Bit()) {
620         case GATT_UUID_CHAR_PRESENT_FORMAT: /* should be readable only */
621         case GATT_UUID_CHAR_EXT_PROP:       /* should be readable only */
622         case GATT_UUID_CHAR_AGG_FORMAT:     /* should be readable only */
623         case GATT_UUID_CHAR_VALID_RANGE:
624           status = GATT_WRITE_NOT_PERMIT;
625           break;
626 
627         case GATT_UUID_CHAR_CLIENT_CONFIG:
628           FALLTHROUGH_INTENDED; /* FALLTHROUGH */
629         case GATT_UUID_CHAR_SRVR_CONFIG:
630           max_size = 2;
631           FALLTHROUGH_INTENDED; /* FALLTHROUGH */
632         case GATT_UUID_CHAR_DESCRIPTION:
633         default: /* any other must be character value declaration */
634           status = GATT_SUCCESS;
635           break;
636       }
637     } else {  // 32 or 128 bit UUID
638       status = GATT_SUCCESS;
639     }
640 
641     if (p_data == NULL && len > 0) {
642       return GATT_INVALID_PDU;
643     }
644 
645     /* these attribute does not allow write blob */
646     if (p_attr->uuid.Is16Bit() &&
647         (p_attr->uuid.As16Bit() == GATT_UUID_CHAR_CLIENT_CONFIG ||
648          p_attr->uuid.As16Bit() == GATT_UUID_CHAR_SRVR_CONFIG)) {
649       if (op_code == GATT_REQ_PREPARE_WRITE && offset != 0) {
650         /* does not allow write blob */
651         status = GATT_NOT_LONG;
652         log::error("GATT_NOT_LONG");
653       } else if (len != max_size) {
654         /* data does not match the required format */
655         status = GATT_INVALID_ATTR_LEN;
656         log::error("GATT_INVALID_PDU");
657       } else {
658         return GATT_SUCCESS;
659       }
660     }
661   }
662 
663   return status;
664 }
665 
666 /**
667  * Description      Allocate a memory space for a new attribute, and link this
668  *                  attribute into the database attribute list.
669  *
670  *
671  * Parameter        p_db    : database pointer.
672  *                  uuid:     attribute UUID
673  *
674  * Returns          pointer to the newly allocated attribute.
675  *
676  */
allocate_attr_in_db(tGATT_SVC_DB & db,const Uuid & uuid,tGATT_PERM perm)677 static tGATT_ATTR& allocate_attr_in_db(tGATT_SVC_DB& db, const Uuid& uuid,
678                                        tGATT_PERM perm) {
679   if (db.next_handle >= db.end_handle) {
680     log::fatal("wrong number of handles! handle_max = {}, next_handle = {}",
681                db.end_handle, db.next_handle);
682   }
683 
684   db.attr_list.emplace_back();
685   tGATT_ATTR& attr = db.attr_list.back();
686   attr.handle = db.next_handle++;
687   attr.uuid = uuid;
688   attr.permission = perm;
689   return attr;
690 }
691 
692 /*******************************************************************************
693  *
694  * Function         gatts_send_app_read_request
695  *
696  * Description      Send application read request callback
697  *
698  * Returns          status of operation.
699  *
700  ******************************************************************************/
gatts_send_app_read_request(tGATT_TCB & tcb,uint16_t cid,uint8_t op_code,uint16_t handle,uint16_t offset,uint32_t trans_id,bt_gatt_db_attribute_type_t gatt_type)701 static tGATT_STATUS gatts_send_app_read_request(
702     tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t handle,
703     uint16_t offset, uint32_t trans_id, bt_gatt_db_attribute_type_t gatt_type) {
704   tGATT_SRV_LIST_ELEM& el = *gatt_sr_find_i_rcb_by_handle(handle);
705   uint16_t conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, el.gatt_if);
706 
707   if (trans_id == 0) {
708     trans_id = gatt_sr_enqueue_cmd(tcb, cid, op_code, handle);
709     gatt_sr_update_cback_cnt(tcb, cid, el.gatt_if, true, true);
710   }
711 
712   if (trans_id != 0) {
713     tGATTS_DATA sr_data;
714     memset(&sr_data, 0, sizeof(tGATTS_DATA));
715 
716     sr_data.read_req.handle = handle;
717     sr_data.read_req.is_long = (bool)(op_code == GATT_REQ_READ_BLOB);
718     sr_data.read_req.offset = offset;
719 
720     uint8_t opcode;
721     if (gatt_type == BTGATT_DB_DESCRIPTOR) {
722       opcode = GATTS_REQ_TYPE_READ_DESCRIPTOR;
723     } else if (gatt_type == BTGATT_DB_CHARACTERISTIC) {
724       opcode = GATTS_REQ_TYPE_READ_CHARACTERISTIC;
725     } else {
726       log::error(
727           "Attempt to read attribute that's not tied with characteristic or "
728           "descriptor value.");
729       return GATT_ERROR;
730     }
731 
732     gatt_sr_send_req_callback(conn_id, trans_id, opcode, &sr_data);
733     return (tGATT_STATUS)GATT_PENDING;
734   } else
735     return (tGATT_STATUS)GATT_BUSY; /* max pending command, application error */
736 }
737