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