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