xref: /btstack/src/ble/att_server.c (revision 328bed13c03f57cf13d3f649712ac965b9574ddc)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "att_server.c"
39 
40 
41 //
42 // ATT Server Globals
43 //
44 
45 #include <stdint.h>
46 #include <string.h>
47 #include <inttypes.h>
48 
49 #include "btstack_config.h"
50 
51 #include "ble/att_dispatch.h"
52 #include "ble/att_db.h"
53 #include "ble/att_server.h"
54 #include "ble/core.h"
55 #include "ble/le_device_db.h"
56 #include "ble/sm.h"
57 #include "btstack_debug.h"
58 #include "btstack_event.h"
59 #include "btstack_memory.h"
60 #include "btstack_run_loop.h"
61 #include "gap.h"
62 #include "hci.h"
63 #include "hci_dump.h"
64 #include "l2cap.h"
65 #include "btstack_tlv.h"
66 #ifdef ENABLE_LE_SIGNED_WRITE
67 #include "ble/sm.h"
68 #include "bluetooth_psm.h"
69 
70 #endif
71 
72 #ifdef ENABLE_TESTING_SUPPORT
73 #include <stdio.h>
74 #endif
75 
76 #ifndef NVN_NUM_GATT_SERVER_CCC
77 #define NVN_NUM_GATT_SERVER_CCC 20
78 #endif
79 
80 static void att_run_for_context(att_server_t * att_server, att_connection_t * att_connection);
81 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle);
82 static btstack_packet_handler_t att_server_packet_handler_for_handle(uint16_t handle);
83 static void att_server_handle_can_send_now(void);
84 static void att_server_persistent_ccc_restore(att_server_t * att_server, att_connection_t * att_connection);
85 static void att_server_persistent_ccc_clear(att_server_t * att_server);
86 static void att_server_handle_att_pdu(att_server_t * att_server, att_connection_t * att_connection, uint8_t * packet, uint16_t size);
87 
88 typedef enum {
89     ATT_SERVER_RUN_PHASE_1_REQUESTS = 0,
90     ATT_SERVER_RUN_PHASE_2_INDICATIONS,
91     ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS,
92 } att_server_run_phase_t;
93 
94 //
95 typedef struct {
96     uint32_t seq_nr;
97     uint16_t att_handle;
98     uint8_t  value;
99     uint8_t  device_index;
100 } persistent_ccc_entry_t;
101 
102 // global
103 static btstack_packet_callback_registration_t hci_event_callback_registration;
104 static btstack_packet_callback_registration_t sm_event_callback_registration;
105 static btstack_packet_handler_t               att_client_packet_handler;
106 static btstack_linked_list_t                  service_handlers;
107 static btstack_context_callback_registration_t att_client_waiting_for_can_send_registration;
108 
109 static att_read_callback_t                    att_server_client_read_callback;
110 static att_write_callback_t                   att_server_client_write_callback;
111 
112 // round robin
113 static hci_con_handle_t att_server_last_can_send_now = HCI_CON_HANDLE_INVALID;
114 
115 #ifdef ENABLE_GATT_OVER_EATT
116 typedef struct {
117     btstack_linked_item_t item;
118     att_server_t     att_server;
119     att_connection_t att_connection;
120     uint8_t * receive_buffer;
121     uint8_t * send_buffer;
122 } att_server_eatt_bearer_t;
123 static att_server_eatt_bearer_t * att_server_eatt_bearer_for_con_handle(hci_con_handle_t con_handle);
124 static btstack_linked_list_t att_server_eatt_bearer_pool;
125 static btstack_linked_list_t att_server_eatt_bearer_active;
126 #endif
127 
128 #ifdef ENABLE_LE_SIGNED_WRITE
129 static bool att_server_connections_for_state(att_server_state_t state, att_server_t ** att_server_out, att_connection_t ** att_connection_out){
130     btstack_linked_list_iterator_t it;
131     hci_connections_get_iterator(&it);
132     while(btstack_linked_list_iterator_has_next(&it)){
133         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
134         if (hci_connection->att_server.state == state) {
135             *att_server_out     = &hci_connection->att_server;
136             *att_connection_out = &hci_connection->att_connection;
137             return true;
138         }
139     }
140 
141 #ifdef ENABLE_GATT_OVER_EATT
142     btstack_linked_list_iterator_init(&it, &att_server_eatt_bearer_active);
143     while(btstack_linked_list_iterator_has_next(&it)){
144         att_server_eatt_bearer_t * eatt_bearer = (att_server_eatt_bearer_t *) btstack_linked_list_iterator_next(&it);
145         if (eatt_bearer->att_server.state == state) {
146             *att_server_out     = &eatt_bearer->att_server;
147             *att_connection_out = &eatt_bearer->att_connection;
148             return true;
149         }
150     }
151 #endif
152 
153     return false;
154 }
155 #endif
156 
157 static void att_server_request_can_send_now(att_server_t * att_server, att_connection_t * att_connection ){
158     switch (att_server->bearer_type){
159         case ATT_BEARER_UNENHANCED_LE:
160 #ifdef ENABLE_GATT_OVER_CLASSIC
161         case ATT_BEARER_UNENHANCED_CLASSIC:
162             /* fall through */
163 #endif
164             att_dispatch_server_request_can_send_now_event(att_connection->con_handle);
165             break;
166 #ifdef ENABLE_GATT_OVER_EATT
167         case ATT_BEARER_ENHANCED_LE:
168             l2cap_request_can_send_now_event(att_server->l2cap_cid);
169             break;
170 #endif
171         default:
172             btstack_unreachable();
173             break;
174     }
175 }
176 
177 static bool att_server_can_send_packet(att_server_t * att_server, att_connection_t * att_connection){
178     switch (att_server->bearer_type) {
179         case ATT_BEARER_UNENHANCED_LE:
180 #ifdef ENABLE_GATT_OVER_CLASSIC
181         case ATT_BEARER_UNENHANCED_CLASSIC:
182             /* fall through */
183 #endif
184             return att_dispatch_server_can_send_now(att_connection->con_handle);
185 #ifdef ENABLE_GATT_OVER_EATT
186         case ATT_BEARER_ENHANCED_LE:
187             return l2cap_can_send_packet_now(att_server->l2cap_cid);
188 #endif
189         default:
190             btstack_unreachable();
191             break;
192     }
193     return false;
194 }
195 
196 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
197     btstack_packet_handler_t packet_handler = att_server_packet_handler_for_handle(attribute_handle);
198     if (!packet_handler) return;
199 
200     uint8_t event[7];
201     int pos = 0;
202     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
203     event[pos++] = sizeof(event) - 2u;
204     event[pos++] = status;
205     little_endian_store_16(event, pos, client_handle);
206     pos += 2;
207     little_endian_store_16(event, pos, attribute_handle);
208     (*packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
209 }
210 
211 static void att_emit_event_to_all(const uint8_t * event, uint16_t size){
212     // dispatch to app level handler
213     if (att_client_packet_handler != NULL){
214         (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t*) event, size);
215     }
216 
217     // dispatch to service handlers
218     btstack_linked_list_iterator_t it;
219     btstack_linked_list_iterator_init(&it, &service_handlers);
220     while (btstack_linked_list_iterator_has_next(&it)){
221         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
222         if (!handler->packet_handler) continue;
223         (*handler->packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t*) event, size);
224     }
225 }
226 
227 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
228     uint8_t event[6];
229     int pos = 0;
230     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
231     event[pos++] = sizeof(event) - 2u;
232     little_endian_store_16(event, pos, con_handle);
233     pos += 2;
234     little_endian_store_16(event, pos, mtu);
235 
236     // also dispatch to GATT Clients
237     att_dispatch_server_mtu_exchanged(con_handle, mtu);
238 
239     // dispatch to app level handler and service handlers
240     att_emit_event_to_all(&event[0], sizeof(event));
241 }
242 
243 static void att_emit_can_send_now_event(void * context){
244     UNUSED(context);
245     if (!att_client_packet_handler) return;
246 
247     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
248     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
249 }
250 
251 static void att_emit_connected_event(att_server_t * att_server,  att_connection_t * att_connection){
252     uint8_t event[11];
253     int pos = 0;
254     event[pos++] = ATT_EVENT_CONNECTED;
255     event[pos++] = sizeof(event) - 2u;
256     event[pos++] = att_server->peer_addr_type;
257     reverse_bd_addr(att_server->peer_address, &event[pos]);
258     pos += 6;
259     little_endian_store_16(event, pos, att_connection->con_handle);
260     pos += 2;
261 
262     // dispatch to app level handler and service handlers
263     att_emit_event_to_all(&event[0], sizeof(event));
264 }
265 
266 
267 static void att_emit_disconnected_event(uint16_t con_handle){
268     uint8_t event[4];
269     int pos = 0;
270     event[pos++] = ATT_EVENT_DISCONNECTED;
271     event[pos++] = sizeof(event) - 2u;
272     little_endian_store_16(event, pos, con_handle);
273     pos += 2;
274 
275     // dispatch to app level handler and service handlers
276     att_emit_event_to_all(&event[0], sizeof(event));
277 }
278 
279 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
280     void * context = btstack_run_loop_get_timer_context(ts);
281     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) context;
282     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
283     if (!hci_connection) return;
284     // @note: after a transaction timeout, no more requests shall be sent over this ATT Bearer
285     // (that's why we don't reset the value_indication_handle)
286     att_server_t * att_server = &hci_connection->att_server;
287     uint16_t att_handle = att_server->value_indication_handle;
288     att_connection_t * att_connection = &hci_connection->att_connection;
289     att_handle_value_indication_notify_client((uint8_t)ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_connection->con_handle, att_handle);
290 }
291 
292 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
293 
294     UNUSED(channel); // ok: there is no channel
295     UNUSED(size);    // ok: handling own l2cap events
296 
297     att_server_t * att_server;
298     att_connection_t * att_connection;
299     hci_con_handle_t con_handle;
300     hci_connection_t * hci_connection;
301 #ifdef ENABLE_GATT_OVER_CLASSIC
302     bd_addr_t address;
303     btstack_linked_list_iterator_t it;
304 #endif
305 
306     switch (packet_type) {
307 
308         case HCI_EVENT_PACKET:
309             switch (hci_event_packet_get_type(packet)) {
310 
311 #ifdef ENABLE_GATT_OVER_CLASSIC
312                 case L2CAP_EVENT_CHANNEL_OPENED:
313                     con_handle = l2cap_event_channel_opened_get_handle(packet);
314                     hci_connection = hci_connection_for_handle(con_handle);
315                     if (!hci_connection) break;
316                     att_server = &hci_connection->att_server;
317                     // store connection info
318                     att_server->bearer_type = ATT_BEARER_UNENHANCED_CLASSIC;
319                     att_server->peer_addr_type = BD_ADDR_TYPE_ACL;
320                     l2cap_event_channel_opened_get_address(packet, att_server->peer_address);
321                     att_connection = &hci_connection->att_connection;
322                     att_connection->con_handle = con_handle;
323                     att_server->l2cap_cid = l2cap_event_channel_opened_get_local_cid(packet);
324                     // reset connection properties
325                     att_server->state = ATT_SERVER_IDLE;
326                     att_connection->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
327                     att_connection->max_mtu = l2cap_max_mtu();
328                     if (att_connection->max_mtu > ATT_REQUEST_BUFFER_SIZE){
329                         att_connection->max_mtu = ATT_REQUEST_BUFFER_SIZE;
330                     }
331 
332                     log_info("Connection opened %s, l2cap cid %04x, mtu %u", bd_addr_to_str(address), att_server->l2cap_cid, att_connection->mtu);
333 
334                     // update security params
335                     att_connection->encryption_key_size = gap_encryption_key_size(con_handle);
336                     att_connection->authenticated = gap_authenticated(con_handle);
337                     att_connection->secure_connection = gap_secure_connection(con_handle);
338                     log_info("encrypted key size %u, authenticated %u, secure connection %u",
339                         att_connection->encryption_key_size, att_connection->authenticated, att_connection->secure_connection);
340 
341                     // notify connection opened
342                     att_emit_connected_event(att_server, att_connection);
343 
344                     // restore persisten ccc if encrypted
345                     if ( gap_security_level(con_handle) >= LEVEL_2){
346                         att_server_persistent_ccc_restore(att_server, att_connection);
347                     }
348                     // TODO: what to do about le device db?
349                     att_server->pairing_active = 0;
350                     break;
351                 case L2CAP_EVENT_CAN_SEND_NOW:
352                     att_server_handle_can_send_now();
353                     break;
354 
355 #endif
356                 case HCI_EVENT_LE_META:
357                     switch (packet[2]) {
358                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
359                             con_handle = little_endian_read_16(packet, 4);
360                             hci_connection = hci_connection_for_handle(con_handle);
361                             if (!hci_connection) break;
362                             att_server = &hci_connection->att_server;
363                         	// store connection info
364                         	att_server->peer_addr_type = packet[7];
365                             reverse_bd_addr(&packet[8], att_server->peer_address);
366                             att_connection = &hci_connection->att_connection;
367                             att_connection->con_handle = con_handle;
368                             // reset connection properties
369                             att_server->state = ATT_SERVER_IDLE;
370                             att_server->bearer_type = ATT_BEARER_UNENHANCED_LE;
371                             att_connection->mtu = ATT_DEFAULT_MTU;
372                             att_connection->max_mtu = l2cap_max_le_mtu();
373                             if (att_connection->max_mtu > ATT_REQUEST_BUFFER_SIZE){
374                                 att_connection->max_mtu = ATT_REQUEST_BUFFER_SIZE;
375                             }
376                             att_connection->encryption_key_size = 0u;
377                             att_connection->authenticated = 0u;
378 		                	att_connection->authorized = 0u;
379                             // workaround: identity resolving can already be complete, at least store result
380                             att_server->ir_le_device_db_index = sm_le_device_index(con_handle);
381                             att_server->ir_lookup_active = 0u;
382                             att_server->pairing_active = 0u;
383                             // notify all - old
384                             att_emit_event_to_all(packet, size);
385                             // notify all - new
386                             att_emit_connected_event(att_server, att_connection);
387                             break;
388 
389                         default:
390                             break;
391                     }
392                     break;
393 
394                 case HCI_EVENT_ENCRYPTION_CHANGE:
395                 case HCI_EVENT_ENCRYPTION_CHANGE_V2:
396                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
397                 	// check handle
398                     con_handle = little_endian_read_16(packet, 3);
399                     hci_connection = hci_connection_for_handle(con_handle);
400                     if (!hci_connection) break;
401                     if (gap_get_connection_type(con_handle) != GAP_CONNECTION_LE) break;
402                     // update security params
403                     att_server = &hci_connection->att_server;
404                     att_connection = &hci_connection->att_connection;
405                     att_connection->encryption_key_size = gap_encryption_key_size(con_handle);
406                     att_connection->authenticated = gap_authenticated(con_handle) ? 1 : 0;
407                     att_connection->secure_connection = gap_secure_connection(con_handle) ? 1 : 0;
408                     log_info("encrypted key size %u, authenticated %u, secure connection %u",
409                         att_connection->encryption_key_size, att_connection->authenticated, att_connection->secure_connection);
410                     if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE){
411                         // restore CCC values when encrypted for LE Connections
412                         if (hci_event_encryption_change_get_encryption_enabled(packet) != 0){
413                             att_server_persistent_ccc_restore(att_server, att_connection);
414                         }
415                     }
416                     att_run_for_context(att_server, att_connection);
417                     break;
418 
419                 case HCI_EVENT_DISCONNECTION_COMPLETE:
420                     // check handle
421                     con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
422                     hci_connection = hci_connection_for_handle(con_handle);
423                     if (!hci_connection) break;
424                     att_server = &hci_connection->att_server;
425                     att_connection = &hci_connection->att_connection;
426                     att_clear_transaction_queue(att_connection);
427                     att_connection->con_handle = 0;
428                     att_server->pairing_active = 0;
429                     att_server->state = ATT_SERVER_IDLE;
430                     if (att_server->value_indication_handle != 0u){
431                         btstack_run_loop_remove_timer(&att_server->value_indication_timer);
432                         uint16_t att_handle = att_server->value_indication_handle;
433                         att_server->value_indication_handle = 0u; // reset error state
434                         att_handle_value_indication_notify_client((uint8_t)ATT_HANDLE_VALUE_INDICATION_DISCONNECT, att_connection->con_handle, att_handle);
435                     }
436                     // notify all - new
437                     att_emit_disconnected_event(con_handle);
438                     // notify all - old
439                     att_emit_event_to_all(packet, size);
440                     break;
441 
442                 // Identity Resolving
443                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
444                     con_handle = sm_event_identity_resolving_started_get_handle(packet);
445                     hci_connection = hci_connection_for_handle(con_handle);
446                     if (!hci_connection) break;
447                     att_server = &hci_connection->att_server;
448                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
449                     att_server->ir_lookup_active = 1;
450                     break;
451                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
452                     con_handle = sm_event_identity_created_get_handle(packet);
453                     hci_connection = hci_connection_for_handle(con_handle);
454                     if (!hci_connection) return;
455                     att_connection = &hci_connection->att_connection;
456                     att_server = &hci_connection->att_server;
457                     att_server->ir_lookup_active = 0;
458                     att_server->ir_le_device_db_index = sm_event_identity_resolving_succeeded_get_index(packet);
459                     log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED");
460                     att_run_for_context(att_server, att_connection);
461                     break;
462                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
463                     con_handle = sm_event_identity_resolving_failed_get_handle(packet);
464                     hci_connection = hci_connection_for_handle(con_handle);
465                     if (!hci_connection) break;
466                     att_connection = &hci_connection->att_connection;
467                     att_server = &hci_connection->att_server;
468                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
469                     att_server->ir_lookup_active = 0;
470                     att_server->ir_le_device_db_index = -1;
471                     att_run_for_context(att_server, att_connection);
472                     break;
473 
474                 // Pairing started - delete stored CCC values
475                 // - assumes pairing indicates either new device or re-pairing, in both cases there should be no stored CCC values
476                 // - assumes that all events have the con handle as the first field
477                 case SM_EVENT_JUST_WORKS_REQUEST:
478                 case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
479                 case SM_EVENT_PASSKEY_INPUT_NUMBER:
480                 case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
481                     con_handle = sm_event_just_works_request_get_handle(packet);
482                     hci_connection = hci_connection_for_handle(con_handle);
483                     if (!hci_connection) break;
484                     att_server = &hci_connection->att_server;
485                     log_info("SM Pairing started");
486                     att_server->pairing_active = 1;
487                     if (att_server->ir_le_device_db_index < 0) break;
488                     att_server_persistent_ccc_clear(att_server);
489                     // index not valid anymore
490                     att_server->ir_le_device_db_index = -1;
491                     break;
492 
493                 // Bonding completed
494                 case SM_EVENT_IDENTITY_CREATED:
495                     con_handle = sm_event_identity_created_get_handle(packet);
496                     hci_connection = hci_connection_for_handle(con_handle);
497                     if (!hci_connection) return;
498                     att_connection = &hci_connection->att_connection;
499                     att_server = &hci_connection->att_server;
500                     att_server->pairing_active = 0;
501                     att_server->ir_le_device_db_index = sm_event_identity_created_get_index(packet);
502                     att_run_for_context(att_server, att_connection);
503                     break;
504 
505                 // Pairing complete (with/without bonding=storing of pairing information)
506                 case SM_EVENT_PAIRING_COMPLETE:
507                     con_handle = sm_event_pairing_complete_get_handle(packet);
508                     hci_connection = hci_connection_for_handle(con_handle);
509                     if (!hci_connection) return;
510                     att_connection = &hci_connection->att_connection;
511                     att_server = &hci_connection->att_server;
512                     att_server->pairing_active = 0;
513                     att_run_for_context(att_server, att_connection);
514                     break;
515 
516                 // Authorization
517                 case SM_EVENT_AUTHORIZATION_RESULT: {
518                     con_handle = sm_event_authorization_result_get_handle(packet);
519                     hci_connection = hci_connection_for_handle(con_handle);
520                     if (!hci_connection) break;
521                     att_connection = &hci_connection->att_connection;
522                     att_server = &hci_connection->att_server;
523                     att_connection->authorized = sm_event_authorization_result_get_authorization_result(packet);
524                     att_server_request_can_send_now(att_server, att_connection);
525                 	break;
526                 }
527                 default:
528                     break;
529             }
530             break;
531 #ifdef ENABLE_GATT_OVER_CLASSIC
532         case L2CAP_DATA_PACKET:
533             hci_connections_get_iterator(&it);
534             while(btstack_linked_list_iterator_has_next(&it)){
535                 hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
536                 att_server = &hci_connection->att_server;
537                 att_connection = &hci_connection->att_connection;
538                 if (att_server->l2cap_cid == channel) {
539                     att_server_handle_att_pdu(att_server, att_connection, packet, size);
540                     break;
541                 }
542             }
543             break;
544 #endif
545 
546         default:
547             break;
548     }
549 }
550 
551 static uint8_t
552 att_server_send_prepared(const att_server_t *att_server, const att_connection_t *att_connection, uint8_t *buffer,
553                          uint16_t size) {
554     uint8_t status = ERROR_CODE_SUCCESS;
555     switch (att_server->bearer_type) {
556         case ATT_BEARER_UNENHANCED_LE:
557             status = l2cap_send_prepared_connectionless(att_connection->con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
558             break;
559 #ifdef ENABLE_GATT_OVER_CLASSIC
560         case ATT_BEARER_UNENHANCED_CLASSIC:
561             status = l2cap_send_prepared(att_server->l2cap_cid, size);
562             break;
563 #endif
564 #ifdef ENABLE_GATT_OVER_EATT
565         case ATT_BEARER_ENHANCED_LE:
566             btstack_assert(buffer != NULL);
567             status = l2cap_send(att_server->l2cap_cid, buffer, size);
568             break;
569 #endif
570         default:
571             btstack_unreachable();
572             break;
573     }
574     return status;
575 }
576 
577 #ifdef ENABLE_LE_SIGNED_WRITE
578 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
579     att_server_t * att_server = NULL;
580     att_connection_t * att_connection = NULL;
581     bool found = att_server_connections_for_state(ATT_SERVER_W4_SIGNED_WRITE_VALIDATION, &att_server, &att_connection);
582 
583     if (found == false){
584         return;
585     }
586 
587     uint8_t hash_flipped[8];
588     reverse_64(hash, hash_flipped);
589     if (memcmp(hash_flipped, &att_server->request_buffer[att_server->request_size-8], 8) != 0){
590         log_info("ATT Signed Write, invalid signature");
591 #ifdef ENABLE_TESTING_SUPPORT
592         printf("ATT Signed Write, invalid signature\n");
593 #endif
594         att_server->state = ATT_SERVER_IDLE;
595         return;
596     }
597     log_info("ATT Signed Write, valid signature");
598 #ifdef ENABLE_TESTING_SUPPORT
599     printf("ATT Signed Write, valid signature\n");
600 #endif
601 
602     // update sequence number
603     uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
604     le_device_db_remote_counter_set(att_server->ir_le_device_db_index, counter_packet+1);
605     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
606     att_server_request_can_send_now(att_server, att_connection);
607 }
608 #endif
609 
610 // pre: att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
611 // pre: can send now
612 // uses l2cap outgoing buffer if no eatt_buffer provided
613 // returns: 1 if packet was sent
614 static int
615 att_server_process_validated_request(att_server_t *att_server, att_connection_t *att_connection, uint8_t *eatt_buffer) {
616 
617     uint8_t * att_response_buffer;
618     if (eatt_buffer != NULL){
619         att_response_buffer = eatt_buffer;
620     } else {
621         l2cap_reserve_packet_buffer();
622         att_response_buffer = l2cap_get_outgoing_buffer();
623     }
624 
625     uint16_t  att_response_size = 0;
626     // Send Error Response for MTU Request over connection-oriented channel
627     if ((att_server->bearer_type != ATT_BEARER_UNENHANCED_LE) && (att_server->request_buffer[0] == ATT_EXCHANGE_MTU_REQUEST)){
628         att_response_size = 5;
629         att_response_buffer[0] = ATT_ERROR_RESPONSE;
630         att_response_buffer[1] = ATT_EXCHANGE_MTU_REQUEST;
631         att_response_buffer[2] = 0;
632         att_response_buffer[3] = 0;
633         att_response_buffer[4] = ATT_ERROR_REQUEST_NOT_SUPPORTED;
634     } else {
635         att_response_size = att_handle_request(att_connection, att_server->request_buffer, att_server->request_size, att_response_buffer);
636     }
637 
638 #ifdef ENABLE_ATT_DELAYED_RESPONSE
639     if ((att_response_size == ATT_READ_RESPONSE_PENDING) || (att_response_size == ATT_INTERNAL_WRITE_RESPONSE_PENDING)){
640         // update state
641         att_server->state = ATT_SERVER_RESPONSE_PENDING;
642 
643         // callback with handle ATT_READ_RESPONSE_PENDING for reads
644         if (att_response_size == ATT_READ_RESPONSE_PENDING){
645             att_server_client_read_callback(att_connection->con_handle, ATT_READ_RESPONSE_PENDING, 0, NULL, 0);
646         }
647 
648         // free reserved buffer
649         if (eatt_buffer == NULL){
650             l2cap_release_packet_buffer();
651         }
652         return 0;
653     }
654 #endif
655 
656     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
657     if ((att_response_size     >= 4u)
658     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
659     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
660     && (att_connection->authenticated != 0u)){
661 
662         switch (gap_authorization_state(att_connection->con_handle)){
663             case AUTHORIZATION_UNKNOWN:
664                 if (eatt_buffer == NULL){
665                     l2cap_release_packet_buffer();
666                 }
667                 sm_request_pairing(att_connection->con_handle);
668                 return 0;
669             case AUTHORIZATION_PENDING:
670                 if (eatt_buffer == NULL){
671                     l2cap_release_packet_buffer();
672                 }
673                 return 0;
674             default:
675                 break;
676         }
677     }
678 
679     att_server->state = ATT_SERVER_IDLE;
680     if (att_response_size == 0u) {
681         if (eatt_buffer == NULL){
682             l2cap_release_packet_buffer();
683         }
684         return 0;
685     }
686 
687     (void) att_server_send_prepared(att_server, att_connection, eatt_buffer, att_response_size);
688 
689     // notify client about MTU exchange result
690     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
691         att_emit_mtu_event(att_connection->con_handle, att_connection->mtu);
692     }
693     return 1;
694 }
695 
696 #ifdef ENABLE_ATT_DELAYED_RESPONSE
697 uint8_t att_server_response_ready(hci_con_handle_t con_handle){
698     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
699     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
700     att_server_t * att_server = &hci_connection->att_server;
701     att_connection_t * att_connection = &hci_connection->att_connection;
702     if (att_server->state != ATT_SERVER_RESPONSE_PENDING)   return ERROR_CODE_COMMAND_DISALLOWED;
703 
704     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
705     att_server_request_can_send_now(att_server, att_connection);
706     return ERROR_CODE_SUCCESS;
707 }
708 #endif
709 
710 static void att_run_for_context(att_server_t * att_server, att_connection_t * att_connection){
711     switch (att_server->state){
712         case ATT_SERVER_REQUEST_RECEIVED:
713             switch (att_server->bearer_type){
714                 case ATT_BEARER_UNENHANCED_LE:
715                     // wait until re-encryption as central is complete
716                     if (gap_reconnect_security_setup_active(att_connection->con_handle)) {
717                         return;
718                     };
719                     break;
720 #if defined(ENABLE_GATT_OVER_CLASSIC) || defined (ENABLE_GATT_OVER_EATT)
721 #ifdef ENABLE_GATT_OVER_CLASSIC
722                 case ATT_BEARER_UNENHANCED_CLASSIC:
723                     /* fall through */
724 #endif
725 #ifdef ENABLE_GATT_OVER_EATT
726                 case ATT_BEARER_ENHANCED_LE:
727 #endif
728                     // ok
729                     break;
730 #endif
731                 default:
732                     btstack_unreachable();
733                     break;
734             }
735 
736             // wait until pairing is complete
737             if (att_server->pairing_active) break;
738 
739 #ifdef ENABLE_LE_SIGNED_WRITE
740             if (att_server->request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
741                 log_info("ATT Signed Write!");
742                 if (!sm_cmac_ready()) {
743                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
744                     att_server->state = ATT_SERVER_IDLE;
745                     return;
746                 }
747                 if (att_server->request_size < (3 + 12)) {
748                     log_info("ATT Signed Write, request to short. Abort.");
749                     att_server->state = ATT_SERVER_IDLE;
750                     return;
751                 }
752                 if (att_server->ir_lookup_active){
753                     return;
754                 }
755                 if (att_server->ir_le_device_db_index < 0){
756                     log_info("ATT Signed Write, CSRK not available");
757                     att_server->state = ATT_SERVER_IDLE;
758                     return;
759                 }
760 
761                 // check counter
762                 uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
763                 uint32_t counter_db     = le_device_db_remote_counter_get(att_server->ir_le_device_db_index);
764                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
765                 if (counter_packet < counter_db){
766                     log_info("ATT Signed Write, db reports higher counter, abort");
767                     att_server->state = ATT_SERVER_IDLE;
768                     return;
769                 }
770 
771                 // signature is { sequence counter, secure hash }
772                 sm_key_t csrk;
773                 le_device_db_remote_csrk_get(att_server->ir_le_device_db_index, csrk);
774                 att_server->state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
775                 log_info("Orig Signature: ");
776                 log_info_hexdump( &att_server->request_buffer[att_server->request_size-8], 8);
777                 uint16_t attribute_handle = little_endian_read_16(att_server->request_buffer, 1);
778                 sm_cmac_signed_write_start(csrk, att_server->request_buffer[0], attribute_handle, att_server->request_size - 15, &att_server->request_buffer[3], counter_packet, att_signed_write_handle_cmac_result);
779                 return;
780             }
781 #endif
782             // move on
783             att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
784             att_server_request_can_send_now(att_server, att_connection);
785             break;
786 
787         default:
788             break;
789     }
790 }
791 
792 static bool att_server_data_ready_for_phase(att_server_t * att_server,  att_server_run_phase_t phase){
793     switch (phase){
794         case ATT_SERVER_RUN_PHASE_1_REQUESTS:
795             return att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
796         case ATT_SERVER_RUN_PHASE_2_INDICATIONS:
797              return (!btstack_linked_list_empty(&att_server->indication_requests) && (att_server->value_indication_handle == 0u));
798         case ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS:
799             return (!btstack_linked_list_empty(&att_server->notification_requests));
800         default:
801             btstack_assert(false);
802             return false;
803     }
804 }
805 
806 static void att_server_trigger_send_for_phase(att_server_t * att_server, att_connection_t * att_connection, att_server_run_phase_t phase){
807     btstack_context_callback_registration_t * client;
808     switch (phase){
809         case ATT_SERVER_RUN_PHASE_1_REQUESTS:
810             att_server_process_validated_request(att_server, att_connection, NULL);
811             break;
812         case ATT_SERVER_RUN_PHASE_2_INDICATIONS:
813             client = (btstack_context_callback_registration_t*) att_server->indication_requests;
814             btstack_linked_list_remove(&att_server->indication_requests, (btstack_linked_item_t *) client);
815             client->callback(client->context);
816             break;
817        case ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS:
818             client = (btstack_context_callback_registration_t*) att_server->notification_requests;
819             btstack_linked_list_remove(&att_server->notification_requests, (btstack_linked_item_t *) client);
820             client->callback(client->context);
821             break;
822         default:
823             btstack_assert(false);
824             break;
825     }
826 }
827 
828 static void att_server_handle_can_send_now(void){
829 
830     hci_con_handle_t last_send_con_handle = HCI_CON_HANDLE_INVALID;
831     hci_connection_t * request_hci_connection   = NULL;
832     bool can_send_now = true;
833     uint8_t phase_index;
834 
835     for (phase_index = ATT_SERVER_RUN_PHASE_1_REQUESTS; phase_index <= ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS; phase_index++){
836         att_server_run_phase_t phase = (att_server_run_phase_t) phase_index;
837         hci_con_handle_t skip_connections_until = att_server_last_can_send_now;
838         while (true){
839             btstack_linked_list_iterator_t it;
840             hci_connections_get_iterator(&it);
841             while(btstack_linked_list_iterator_has_next(&it)){
842                 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
843                 att_server_t * att_server = &connection->att_server;
844                 att_connection_t * att_connection = &connection->att_connection;
845 
846                 bool data_ready = att_server_data_ready_for_phase(att_server, phase);
847 
848                 // log_debug("phase %u, handle 0x%04x, skip until 0x%04x, data ready %u", phase, att_connection->con_handle, skip_connections_until, data_ready);
849 
850                 // skip until last sender found (which is also skipped)
851                 if (skip_connections_until != HCI_CON_HANDLE_INVALID){
852                     if (data_ready && (request_hci_connection == NULL)){
853                         request_hci_connection = connection;
854                     }
855                     if (skip_connections_until == att_connection->con_handle){
856                         skip_connections_until = HCI_CON_HANDLE_INVALID;
857                     }
858                     continue;
859                 };
860 
861                 if (data_ready){
862                     if (can_send_now){
863                         att_server_trigger_send_for_phase(att_server, att_connection, phase);
864                         last_send_con_handle = att_connection->con_handle;
865                         can_send_now = att_server_can_send_packet(att_server, att_connection);
866                         data_ready = att_server_data_ready_for_phase(att_server, phase);
867                         if (data_ready && (request_hci_connection == NULL)){
868                             request_hci_connection = connection;
869                         }
870                     } else {
871                         request_hci_connection = connection;
872                         break;
873                     }
874                 }
875             }
876 
877             // stop skipping (handles disconnect by last send connection)
878             skip_connections_until = HCI_CON_HANDLE_INVALID;
879 
880             // Exit loop, if we cannot send
881             if (!can_send_now) break;
882 
883             // Exit loop, if we can send but there are also no further request
884             if (request_hci_connection == NULL) break;
885 
886             // Finally, if we still can send and there are requests, just try again
887             request_hci_connection = NULL;
888         }
889         // update last send con handle for round robin
890         if (last_send_con_handle != HCI_CON_HANDLE_INVALID){
891             att_server_last_can_send_now = last_send_con_handle;
892         }
893     }
894 
895     if (request_hci_connection == NULL) return;
896 
897     att_server_t * att_server = &request_hci_connection->att_server;
898     att_connection_t * att_connection = &request_hci_connection->att_connection;
899     att_server_request_can_send_now(att_server, att_connection);
900 }
901 
902 static void att_server_handle_att_pdu(att_server_t * att_server, att_connection_t * att_connection, uint8_t * packet, uint16_t size){
903 
904     uint8_t opcode  = packet[0u];
905     uint8_t method  = opcode & 0x03fu;
906     bool invalid = method > ATT_MULTIPLE_HANDLE_VALUE_NTF;
907     bool command = (opcode & 0x40u) != 0u;
908 
909     // ignore invalid commands
910     if (invalid && command){
911         return;
912     }
913 
914     // handle value indication confirms
915     if ((opcode == ATT_HANDLE_VALUE_CONFIRMATION) && (att_server->value_indication_handle != 0u)){
916         btstack_run_loop_remove_timer(&att_server->value_indication_timer);
917         uint16_t att_handle = att_server->value_indication_handle;
918         att_server->value_indication_handle = 0u;
919         att_handle_value_indication_notify_client(0u, att_connection->con_handle, att_handle);
920         att_server_request_can_send_now(att_server, att_connection);
921         return;
922     }
923 
924     // directly process command
925     // note: signed write cannot be handled directly as authentication needs to be verified
926     if (opcode == ATT_WRITE_COMMAND){
927         att_handle_request(att_connection, packet, size, NULL);
928         return;
929     }
930 
931     // check size
932     if (size > sizeof(att_server->request_buffer)) {
933         log_info("drop att pdu 0x%02x as size %u > att_server->request_buffer %u", packet[0], size, (int) sizeof(att_server->request_buffer));
934         return;
935     }
936 
937 #ifdef ENABLE_LE_SIGNED_WRITE
938     // abort signed write validation if a new request comes in (but finish previous signed write if possible)
939     if (att_server->state == ATT_SERVER_W4_SIGNED_WRITE_VALIDATION){
940         if (packet[0] == ATT_SIGNED_WRITE_COMMAND){
941             log_info("skip new signed write request as previous is in validation");
942             return;
943         } else {
944             log_info("abort signed write validation to process new request");
945             att_server->state = ATT_SERVER_IDLE;
946         }
947     }
948 #endif
949     // last request still in processing?
950     if (att_server->state != ATT_SERVER_IDLE){
951         log_info("skip att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state);
952         return;
953     }
954 
955     // store request
956     att_server->state = ATT_SERVER_REQUEST_RECEIVED;
957     att_server->request_size = size;
958     (void)memcpy(att_server->request_buffer, packet, size);
959 
960     att_run_for_context(att_server, att_connection);
961 }
962 
963 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
964     hci_connection_t * hci_connection;
965     att_connection_t * att_connection;
966     att_server_t     * att_server;
967 
968     switch (packet_type){
969         case HCI_EVENT_PACKET:
970             switch (packet[0]){
971                 case L2CAP_EVENT_CAN_SEND_NOW:
972                     att_server_handle_can_send_now();
973                     break;
974                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
975                     // GATT client has negotiated the mtu for this connection
976                     hci_connection = hci_connection_for_handle(handle);
977                     if (!hci_connection) break;
978                     att_connection = &hci_connection->att_connection;
979                     att_connection->mtu = little_endian_read_16(packet, 4);
980                     break;
981                 default:
982                     break;
983             }
984             break;
985 
986         case ATT_DATA_PACKET:
987             log_debug("ATT Packet, handle 0x%04x", handle);
988             hci_connection = hci_connection_for_handle(handle);
989             if (!hci_connection) break;
990 
991             att_server = &hci_connection->att_server;
992             att_connection = &hci_connection->att_connection;
993             att_server_handle_att_pdu(att_server, att_connection, packet, size);
994             break;
995 
996         default:
997             break;
998     }
999 }
1000 
1001 // ---------------------
1002 // persistent CCC writes
1003 static uint32_t att_server_persistent_ccc_tag_for_index(uint8_t index){
1004     return ('B' << 24u) | ('T' << 16u) | ('C' << 8u) | index;
1005 }
1006 
1007 static void att_server_persistent_ccc_write(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t value){
1008     // lookup att_server instance
1009     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1010     if (!hci_connection) return;
1011     att_server_t * att_server = &hci_connection->att_server;
1012     int le_device_index = att_server->ir_le_device_db_index;
1013     log_info("Store CCC value 0x%04x for handle 0x%04x of remote %s, le device id %d", value, att_handle, bd_addr_to_str(att_server->peer_address), le_device_index);
1014 
1015     // check if bonded
1016     if (le_device_index < 0) return;
1017 
1018     // get btstack_tlv
1019     const btstack_tlv_t * tlv_impl = NULL;
1020     void * tlv_context;
1021     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
1022     if (!tlv_impl) return;
1023 
1024     // update ccc tag
1025     int index;
1026     uint32_t highest_seq_nr = 0;
1027     uint32_t lowest_seq_nr = 0;
1028     uint32_t tag_for_lowest_seq_nr = 0;
1029     uint32_t tag_for_empty = 0;
1030     persistent_ccc_entry_t entry;
1031     for (index=0; index<NVN_NUM_GATT_SERVER_CCC; index++){
1032         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
1033         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1034 
1035         // empty/invalid tag
1036         if (len != sizeof(persistent_ccc_entry_t)){
1037             tag_for_empty = tag;
1038             continue;
1039         }
1040         // update highest seq nr
1041         if (entry.seq_nr > highest_seq_nr){
1042             highest_seq_nr = entry.seq_nr;
1043         }
1044         // find entry with lowest seq nr
1045         if ((tag_for_lowest_seq_nr == 0u) || (entry.seq_nr < lowest_seq_nr)){
1046             tag_for_lowest_seq_nr = tag;
1047             lowest_seq_nr = entry.seq_nr;
1048         }
1049 
1050         if (entry.device_index != le_device_index) continue;
1051         if (entry.att_handle   != att_handle)      continue;
1052 
1053         // found matching entry
1054         if (value != 0){
1055             // update
1056             if (entry.value == value) {
1057                 log_info("CCC Index %u: Up-to-date", index);
1058                 return;
1059             }
1060             entry.value = (uint8_t) value;
1061             entry.seq_nr = highest_seq_nr + 1u;
1062             log_info("CCC Index %u: Store", index);
1063             int result = tlv_impl->store_tag(tlv_context, tag, (const uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1064             if (result != 0){
1065                 log_error("Store tag index %u failed", index);
1066             }
1067         } else {
1068             // delete
1069             log_info("CCC Index %u: Delete", index);
1070             tlv_impl->delete_tag(tlv_context, tag);
1071         }
1072         return;
1073     }
1074 
1075     log_info("tag_for_empty %"PRIx32", tag_for_lowest_seq_nr %"PRIx32, tag_for_empty, tag_for_lowest_seq_nr);
1076 
1077     if (value == 0u){
1078         // done
1079         return;
1080     }
1081 
1082     uint32_t tag_to_use = 0u;
1083     if (tag_for_empty != 0u){
1084         tag_to_use = tag_for_empty;
1085     } else if (tag_for_lowest_seq_nr){
1086         tag_to_use = tag_for_lowest_seq_nr;
1087     } else {
1088         // should not happen
1089         return;
1090     }
1091     // store ccc tag
1092     entry.seq_nr       = highest_seq_nr + 1u;
1093     entry.device_index = le_device_index;
1094     entry.att_handle   = att_handle;
1095     entry.value        = (uint8_t) value;
1096     int result = tlv_impl->store_tag(tlv_context, tag_to_use, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1097     if (result != 0){
1098         log_error("Store tag index %u failed", index);
1099     }
1100 }
1101 
1102 static void att_server_persistent_ccc_clear(att_server_t * att_server){
1103     int le_device_index = att_server->ir_le_device_db_index;
1104     log_info("Clear CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
1105     // check if bonded
1106     if (le_device_index < 0) return;
1107     // get btstack_tlv
1108     const btstack_tlv_t * tlv_impl = NULL;
1109     void * tlv_context;
1110     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
1111     if (!tlv_impl) return;
1112     // get all ccc tag
1113     int index;
1114     persistent_ccc_entry_t entry;
1115     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
1116         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
1117         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1118         if (len != sizeof(persistent_ccc_entry_t)) continue;
1119         if (entry.device_index != le_device_index) continue;
1120         // delete entry
1121         log_info("CCC Index %u: Delete", index);
1122         tlv_impl->delete_tag(tlv_context, tag);
1123     }
1124 }
1125 
1126 static void att_server_persistent_ccc_restore(att_server_t * att_server, att_connection_t * att_connection){
1127     int le_device_index = att_server->ir_le_device_db_index;
1128     log_info("Restore CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
1129     // check if bonded
1130     if (le_device_index < 0) return;
1131     // get btstack_tlv
1132     const btstack_tlv_t * tlv_impl = NULL;
1133     void * tlv_context;
1134     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
1135     if (!tlv_impl) return;
1136     // get all ccc tag
1137     int index;
1138     persistent_ccc_entry_t entry;
1139     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
1140         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
1141         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1142         if (len != sizeof(persistent_ccc_entry_t)) continue;
1143         if (entry.device_index != le_device_index) continue;
1144         // simulate write callback
1145         uint16_t attribute_handle = entry.att_handle;
1146         uint8_t  value[2];
1147         little_endian_store_16(value, 0, entry.value);
1148         att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
1149         if (!callback) continue;
1150         log_info("CCC Index %u: Set Attribute handle 0x%04x to value 0x%04x", index, attribute_handle, entry.value );
1151         (*callback)(att_connection->con_handle, attribute_handle, ATT_TRANSACTION_MODE_NONE, 0, value, sizeof(value));
1152     }
1153 }
1154 
1155 // persistent CCC writes
1156 // ---------------------
1157 
1158 // gatt service management
1159 static att_service_handler_t * att_service_handler_for_handle(uint16_t handle){
1160     btstack_linked_list_iterator_t it;
1161     btstack_linked_list_iterator_init(&it, &service_handlers);
1162     while (btstack_linked_list_iterator_has_next(&it)){
1163         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1164         if (handler->start_handle > handle) continue;
1165         if (handler->end_handle   < handle) continue;
1166         return handler;
1167     }
1168     return NULL;
1169 }
1170 static att_read_callback_t att_server_read_callback_for_handle(uint16_t handle){
1171     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1172     if (handler != NULL) return handler->read_callback;
1173     return att_server_client_read_callback;
1174 }
1175 
1176 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle){
1177     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1178     if (handler != NULL) return handler->write_callback;
1179     return att_server_client_write_callback;
1180 }
1181 
1182 static btstack_packet_handler_t att_server_packet_handler_for_handle(uint16_t handle){
1183     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1184     if (handler != NULL) return handler->packet_handler;
1185     return att_client_packet_handler;
1186 }
1187 
1188 static void att_notify_write_callbacks(hci_con_handle_t con_handle, uint16_t transaction_mode){
1189     // notify all callbacks
1190     btstack_linked_list_iterator_t it;
1191     btstack_linked_list_iterator_init(&it, &service_handlers);
1192     while (btstack_linked_list_iterator_has_next(&it)){
1193         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1194         if (!handler->write_callback) continue;
1195         (*handler->write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
1196     }
1197     if (!att_server_client_write_callback) return;
1198     (*att_server_client_write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
1199 }
1200 
1201 // returns first reported error or 0
1202 static uint8_t att_validate_prepared_write(hci_con_handle_t con_handle){
1203     btstack_linked_list_iterator_t it;
1204     btstack_linked_list_iterator_init(&it, &service_handlers);
1205     while (btstack_linked_list_iterator_has_next(&it)){
1206         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1207         if (!handler->write_callback) continue;
1208         uint8_t error_code = (*handler->write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1209         if (error_code != 0u) return error_code;
1210     }
1211     if (!att_server_client_write_callback) return 0;
1212     return (*att_server_client_write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1213 }
1214 
1215 static uint16_t att_server_read_callback(hci_con_handle_t con_handle, uint16_t attribute_handle, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1216     att_read_callback_t callback = att_server_read_callback_for_handle(attribute_handle);
1217     if (!callback) return 0;
1218     return (*callback)(con_handle, attribute_handle, offset, buffer, buffer_size);
1219 }
1220 
1221 static int att_server_write_callback(hci_con_handle_t con_handle, uint16_t attribute_handle, uint16_t transaction_mode, uint16_t offset, uint8_t *buffer, uint16_t buffer_size){
1222     switch (transaction_mode){
1223         case ATT_TRANSACTION_MODE_VALIDATE:
1224             return att_validate_prepared_write(con_handle);
1225         case ATT_TRANSACTION_MODE_EXECUTE:
1226         case ATT_TRANSACTION_MODE_CANCEL:
1227             att_notify_write_callbacks(con_handle, transaction_mode);
1228             return 0;
1229         default:
1230             break;
1231     }
1232 
1233     // track CCC writes
1234     if (att_is_persistent_ccc(attribute_handle) && (offset == 0u) && (buffer_size == 2u)){
1235         att_server_persistent_ccc_write(con_handle, attribute_handle, little_endian_read_16(buffer, 0));
1236     }
1237 
1238     att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
1239     if (!callback) return 0;
1240     return (*callback)(con_handle, attribute_handle, transaction_mode, offset, buffer, buffer_size);
1241 }
1242 
1243 /**
1244  * @brief register read/write callbacks for specific handle range
1245  * @param att_service_handler_t
1246  */
1247 void att_server_register_service_handler(att_service_handler_t * handler){
1248     bool att_server_registered = false;
1249     if (att_service_handler_for_handle(handler->start_handle)){
1250         att_server_registered = true;
1251     }
1252 
1253     if (att_service_handler_for_handle(handler->end_handle)){
1254         att_server_registered = true;
1255     }
1256 
1257     if (att_server_registered){
1258         log_error("handler for range 0x%04x-0x%04x already registered", handler->start_handle, handler->end_handle);
1259         return;
1260     }
1261     btstack_linked_list_add(&service_handlers, (btstack_linked_item_t*) handler);
1262 }
1263 
1264 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
1265 
1266     // store callbacks
1267     att_server_client_read_callback  = read_callback;
1268     att_server_client_write_callback = write_callback;
1269 
1270     // register for HCI Events
1271     hci_event_callback_registration.callback = &att_event_packet_handler;
1272     hci_add_event_handler(&hci_event_callback_registration);
1273 
1274     // register for SM events
1275     sm_event_callback_registration.callback = &att_event_packet_handler;
1276     sm_add_event_handler(&sm_event_callback_registration);
1277 
1278     // and L2CAP ATT Server PDUs
1279     att_dispatch_register_server(att_packet_handler);
1280 
1281 #ifdef ENABLE_GATT_OVER_CLASSIC
1282     // setup l2cap service
1283     att_dispatch_classic_register_service();
1284 #endif
1285 
1286     att_set_db(db);
1287     att_set_read_callback(att_server_read_callback);
1288     att_set_write_callback(att_server_write_callback);
1289 }
1290 
1291 void att_server_register_packet_handler(btstack_packet_handler_t handler){
1292     att_client_packet_handler = handler;
1293 }
1294 
1295 
1296 // to be deprecated
1297 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
1298     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1299     if (!hci_connection) return 0;
1300     att_server_t * att_server = &hci_connection->att_server;
1301     att_connection_t * att_connection = &hci_connection->att_connection;
1302     return att_server_can_send_packet(att_server, att_connection);
1303 }
1304 
1305 uint8_t att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1306     return att_server_request_to_send_notification(callback_registration, con_handle);
1307 }
1308 
1309 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
1310     att_client_waiting_for_can_send_registration.callback = &att_emit_can_send_now_event;
1311     att_server_request_to_send_notification(&att_client_waiting_for_can_send_registration, con_handle);
1312 }
1313 // end of deprecated
1314 
1315 uint8_t att_server_request_to_send_notification(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1316     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1317     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1318     att_server_t * att_server = &hci_connection->att_server;
1319     att_connection_t * att_connection = &hci_connection->att_connection;
1320     bool added = btstack_linked_list_add_tail(&att_server->notification_requests, (btstack_linked_item_t*) callback_registration);
1321     att_server_request_can_send_now(att_server, att_connection);
1322     if (added){
1323         return ERROR_CODE_SUCCESS;
1324     } else {
1325         return ERROR_CODE_COMMAND_DISALLOWED;
1326     }
1327 }
1328 
1329 uint8_t att_server_request_to_send_indication(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1330     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1331     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1332     att_server_t * att_server = &hci_connection->att_server;
1333     att_connection_t * att_connection = &hci_connection->att_connection;
1334     bool added = btstack_linked_list_add_tail(&att_server->indication_requests, (btstack_linked_item_t*) callback_registration);
1335     att_server_request_can_send_now(att_server, att_connection);
1336     if (added){
1337         return ERROR_CODE_SUCCESS;
1338     } else {
1339         return ERROR_CODE_COMMAND_DISALLOWED;
1340     }
1341 }
1342 
1343 static uint8_t att_server_prepare_server_message(hci_con_handle_t con_handle, att_server_t ** out_att_server, att_connection_t ** out_att_connection, uint8_t ** out_packet_buffer){
1344 
1345     att_server_t *     att_server = NULL;
1346     att_connection_t * att_connection = NULL;
1347     uint8_t *          packet_buffer = NULL;
1348 
1349     // prefer enhanced bearer
1350 #ifdef ENABLE_GATT_OVER_EATT
1351     att_server_eatt_bearer_t * eatt_bearer = att_server_eatt_bearer_for_con_handle(con_handle);
1352     if (eatt_bearer != NULL){
1353         att_server     = &eatt_bearer->att_server;
1354         att_connection = &eatt_bearer->att_connection;
1355         packet_buffer  = eatt_bearer->send_buffer;
1356     } else
1357 #endif
1358     {
1359         hci_connection_t *hci_connection = hci_connection_for_handle(con_handle);
1360         if (hci_connection != NULL) {
1361             att_server     = &hci_connection->att_server;
1362             att_connection = &hci_connection->att_connection;
1363         }
1364     }
1365 
1366     if (att_server == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1367     if (!att_server_can_send_packet(att_server, att_connection)) return BTSTACK_ACL_BUFFERS_FULL;
1368 
1369     if (packet_buffer == NULL){
1370         l2cap_reserve_packet_buffer();
1371         packet_buffer = l2cap_get_outgoing_buffer();
1372     }
1373 
1374     *out_att_connection = att_connection;
1375     *out_att_server = att_server;
1376     *out_packet_buffer = packet_buffer;
1377     return ERROR_CODE_SUCCESS;
1378 }
1379 
1380 uint8_t att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, const uint8_t *value, uint16_t value_len){
1381     att_server_t * att_server = NULL;
1382     att_connection_t * att_connection = NULL;
1383     uint8_t * packet_buffer = NULL;
1384 
1385     uint8_t status = att_server_prepare_server_message(con_handle, &att_server, &att_connection, &packet_buffer);
1386     if (status != ERROR_CODE_SUCCESS){
1387         return status;
1388     }
1389 
1390     uint16_t size = att_prepare_handle_value_notification(att_connection, attribute_handle, value, value_len, packet_buffer);
1391 
1392     return att_server_send_prepared(att_server, att_connection, NULL, size);
1393 }
1394 
1395 /**
1396  * @brief notify client about multiple attribute value changes
1397  * @param con_handle
1398  * @param num_attributes
1399  * @param attribute_handles[]
1400  * @param values_data[]
1401  * @param values_len[]
1402  * @return 0 if ok, error otherwise
1403  */
1404 uint8_t att_server_multiple_notify(hci_con_handle_t con_handle, uint8_t num_attributes,
1405                                    const uint16_t * attribute_handles, const uint8_t ** values_data, const uint16_t * values_len){
1406 
1407     att_server_t * att_server = NULL;
1408     att_connection_t * att_connection = NULL;
1409     uint8_t * packet_buffer = NULL;
1410 
1411     uint8_t status = att_server_prepare_server_message(con_handle, &att_server, &att_connection, &packet_buffer);
1412     if (status != ERROR_CODE_SUCCESS){
1413         return status;
1414     }
1415 
1416     uint16_t size = att_prepare_handle_value_multiple_notification(att_connection, num_attributes, attribute_handles, values_data, values_len, packet_buffer);
1417 
1418     return att_server_send_prepared(att_server, att_connection, packet_buffer, size);
1419 }
1420 
1421 uint8_t att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, const uint8_t *value, uint16_t value_len){
1422 
1423     att_server_t * att_server = NULL;
1424     att_connection_t * att_connection = NULL;
1425     uint8_t * packet_buffer = NULL;
1426 
1427     uint8_t status = att_server_prepare_server_message(con_handle, &att_server, &att_connection, &packet_buffer);
1428     if (status != ERROR_CODE_SUCCESS){
1429         return status;
1430     }
1431 
1432     if (att_server->value_indication_handle != 0u) {
1433         // free reserved packet buffer
1434         if (att_server->bearer_type == ATT_BEARER_ENHANCED_LE){
1435             l2cap_release_packet_buffer();
1436         }
1437         return ATT_HANDLE_VALUE_INDICATION_IN_PROGRESS;
1438     }
1439 
1440     // track indication
1441     att_server->value_indication_handle = attribute_handle;
1442     btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout);
1443     btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
1444     btstack_run_loop_add_timer(&att_server->value_indication_timer);
1445 
1446     uint16_t size = att_prepare_handle_value_indication(att_connection, attribute_handle, value, value_len, packet_buffer);
1447 
1448     return att_server_send_prepared(att_server, att_connection, NULL, size);
1449 }
1450 
1451 uint16_t att_server_get_mtu(hci_con_handle_t con_handle){
1452     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1453     if (!hci_connection) return 0;
1454     att_connection_t * att_connection = &hci_connection->att_connection;
1455     return att_connection->mtu;
1456 }
1457 
1458 void att_server_deinit(void){
1459     att_server_client_read_callback  = NULL;
1460     att_server_client_write_callback = NULL;
1461     att_client_packet_handler = NULL;
1462     service_handlers = NULL;
1463 }
1464 
1465 #ifdef ENABLE_GATT_OVER_EATT
1466 
1467 #define MAX_NR_EATT_CHANNELS 5
1468 
1469 static uint16_t att_server_eatt_receive_buffer_size;
1470 static uint16_t att_server_eatt_send_buffer_size;
1471 
1472 static att_server_eatt_bearer_t * att_server_eatt_bearer_for_cid(uint16_t cid){
1473     btstack_linked_list_iterator_t it;
1474     btstack_linked_list_iterator_init(&it, &att_server_eatt_bearer_active);
1475     while(btstack_linked_list_iterator_has_next(&it)){
1476         att_server_eatt_bearer_t * eatt_bearer = (att_server_eatt_bearer_t *) btstack_linked_list_iterator_next(&it);
1477         if (eatt_bearer->att_server.l2cap_cid == cid) {
1478             return eatt_bearer;
1479         }
1480     }
1481     return NULL;
1482 }
1483 
1484 static att_server_eatt_bearer_t * att_server_eatt_bearer_for_con_handle(hci_con_handle_t con_handle){
1485     btstack_linked_list_iterator_t it;
1486     btstack_linked_list_iterator_init(&it, &att_server_eatt_bearer_active);
1487     while(btstack_linked_list_iterator_has_next(&it)){
1488         att_server_eatt_bearer_t * eatt_bearer = (att_server_eatt_bearer_t *) btstack_linked_list_iterator_next(&it);
1489         if (eatt_bearer->att_connection.con_handle == con_handle) {
1490             return eatt_bearer;
1491         }
1492     }
1493     return NULL;
1494 }
1495 
1496 static void att_server_eatt_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1497     uint16_t cid;
1498     uint8_t status;
1499     uint16_t remote_mtu;
1500 
1501     uint8_t i;
1502     uint8_t num_requested_bearers;
1503     uint8_t num_accepted_bearers;
1504     uint16_t initial_credits = L2CAP_LE_AUTOMATIC_CREDITS;
1505     uint8_t * receive_buffers[MAX_NR_EATT_CHANNELS];
1506     uint16_t cids[MAX_NR_EATT_CHANNELS];
1507     att_server_eatt_bearer_t * eatt_bearers[MAX_NR_EATT_CHANNELS];
1508     att_server_eatt_bearer_t * eatt_bearer;
1509     att_server_t * att_server;
1510     att_connection_t * att_connection;
1511 
1512     switch (packet_type) {
1513 
1514         case L2CAP_DATA_PACKET:
1515             eatt_bearer = att_server_eatt_bearer_for_cid(channel);
1516             btstack_assert(eatt_bearer != NULL);
1517             att_server = &eatt_bearer->att_server;
1518             att_connection = &eatt_bearer->att_connection;
1519             att_server_handle_att_pdu(att_server, att_connection, packet, size);
1520             break;
1521 
1522         case HCI_EVENT_PACKET:
1523             switch (packet[0]) {
1524 
1525                 case L2CAP_EVENT_CAN_SEND_NOW:
1526                     cid = l2cap_event_packet_sent_get_local_cid(packet);
1527                     eatt_bearer = att_server_eatt_bearer_for_cid(cid);
1528                     btstack_assert(eatt_bearer != NULL);
1529                     att_server = &eatt_bearer->att_server;
1530                     att_connection = &eatt_bearer->att_connection;
1531                     // only used for EATT request responses
1532                     btstack_assert(att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED);
1533                     att_server_process_validated_request(att_server, att_connection, eatt_bearer->send_buffer);
1534                     break;
1535 
1536                 case L2CAP_EVENT_PACKET_SENT:
1537                     cid = l2cap_event_packet_sent_get_local_cid(packet);
1538                     eatt_bearer = att_server_eatt_bearer_for_cid(cid);
1539                     btstack_assert(eatt_bearer != NULL);
1540                     att_server = &eatt_bearer->att_server;
1541                     att_connection = &eatt_bearer->att_connection;
1542                     att_server_handle_att_pdu(att_server, att_connection, packet, size);
1543                     break;
1544 
1545                 case L2CAP_EVENT_ECBM_INCOMING_CONNECTION:
1546                     cid = l2cap_event_ecbm_incoming_connection_get_local_cid(packet);
1547                     num_requested_bearers = l2cap_event_ecbm_incoming_connection_get_num_channels(packet);
1548                     for (i = 0; i < num_requested_bearers; i++){
1549                         eatt_bearers[i] = (att_server_eatt_bearer_t *) btstack_linked_list_pop(&att_server_eatt_bearer_pool);
1550                         if (eatt_bearers[i] == NULL) {
1551                             break;
1552                         }
1553                         eatt_bearers[i]->att_connection.con_handle = l2cap_event_ecbm_incoming_connection_get_handle(packet);
1554                         eatt_bearers[i]->att_server.bearer_type = ATT_BEARER_ENHANCED_LE;
1555                         receive_buffers[i] = eatt_bearers[i]->receive_buffer;
1556                         btstack_linked_list_add(&att_server_eatt_bearer_active, (btstack_linked_item_t *) eatt_bearers[i]);
1557                     }
1558                     num_accepted_bearers = i;
1559                     status = l2cap_ecbm_accept_channels(cid, num_accepted_bearers, initial_credits, att_server_eatt_receive_buffer_size, receive_buffers, cids);
1560                     btstack_assert(status == ERROR_CODE_SUCCESS);
1561                     log_info("requested %u, accepted %u", num_requested_bearers, num_accepted_bearers);
1562                     for (i=0;i<num_accepted_bearers;i++){
1563                         log_info("eatt l2cap cid: 0x%04x", cids[i]);
1564                         eatt_bearers[i]->att_server.l2cap_cid = cids[i];
1565                     }
1566                     break;
1567 
1568                 case L2CAP_EVENT_ECBM_CHANNEL_OPENED:
1569                     cid         = l2cap_event_ecbm_channel_opened_get_local_cid(packet);
1570                     status      = l2cap_event_ecbm_channel_opened_get_status(packet);
1571                     remote_mtu  = l2cap_event_ecbm_channel_opened_get_remote_mtu(packet);
1572                     eatt_bearer = att_server_eatt_bearer_for_cid(cid);
1573                     btstack_assert(eatt_bearer != NULL);
1574                     eatt_bearer->att_connection.mtu_exchanged = true;
1575                     eatt_bearer->att_connection.mtu = remote_mtu;
1576                     eatt_bearer->att_connection.max_mtu = remote_mtu;
1577                     log_info("L2CAP_EVENT_ECBM_CHANNEL_OPENED - cid 0x%04x mtu %u, status 0x%02x", cid, remote_mtu, status);
1578                     break;
1579 
1580                 case L2CAP_EVENT_ECBM_RECONFIGURED:
1581                     break;
1582 
1583                 case L2CAP_EVENT_CHANNEL_CLOSED:
1584                     eatt_bearer = att_server_eatt_bearer_for_cid(l2cap_event_channel_closed_get_local_cid(packet));
1585                     btstack_assert(eatt_bearers != NULL);
1586 
1587                     // TODO: finalize - abort queued writes
1588 
1589                     btstack_linked_list_remove(&att_server_eatt_bearer_active, (btstack_linked_item_t  *) eatt_bearer);
1590                     btstack_linked_list_add(&att_server_eatt_bearer_pool, (btstack_linked_item_t  *) eatt_bearer);
1591                     break;
1592                 default:
1593                     break;
1594             }
1595             break;
1596         default:
1597             btstack_unreachable();
1598             break;
1599     }
1600 }
1601 
1602 // create eatt bearers
1603 uint8_t att_server_eatt_init(uint8_t num_eatt_bearers, uint8_t * storage_buffer, uint16_t storage_size){
1604     uint16_t size_for_structs = num_eatt_bearers * sizeof(att_server_eatt_bearer_t);
1605     if (storage_size < size_for_structs) {
1606         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
1607     }
1608 
1609     // TODO: The minimum ATT_MTU for an Enhanced ATT bearer is 64 octets.
1610 
1611     memset(storage_buffer, 0, storage_size);
1612     uint16_t buffer_size_per_bearer = ((storage_size - size_for_structs) / num_eatt_bearers);
1613     att_server_eatt_receive_buffer_size = buffer_size_per_bearer / 2;
1614     att_server_eatt_send_buffer_size    = buffer_size_per_bearer / 2;
1615     uint8_t * bearer_buffer = &storage_buffer[size_for_structs];
1616     uint8_t i;
1617     att_server_eatt_bearer_t * eatt_bearer = (att_server_eatt_bearer_t *) storage_buffer;
1618     log_info("%u EATT bearers with receive buffer size %u",
1619              num_eatt_bearers, att_server_eatt_receive_buffer_size);
1620     for (i=0;i<num_eatt_bearers;i++){
1621         eatt_bearer->att_connection.con_handle = HCI_CON_HANDLE_INVALID;
1622         eatt_bearer->receive_buffer = bearer_buffer;
1623         bearer_buffer += att_server_eatt_receive_buffer_size;
1624         eatt_bearer->send_buffer = bearer_buffer;
1625         bearer_buffer += att_server_eatt_send_buffer_size;
1626         btstack_linked_list_add(&att_server_eatt_bearer_pool, (btstack_linked_item_t *) eatt_bearer);
1627         eatt_bearer++;
1628     }
1629     // TODO: define minimum EATT MTU
1630     l2cap_ecbm_register_service(att_server_eatt_handler, BLUETOOTH_PSM_EATT, 64, 0, false);
1631 
1632     return 0;
1633 }
1634 #endif