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