xref: /btstack/src/ble/att_server.c (revision 68591e36e97ed1ccb3a86672f9f79114713a1e1c)
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 MATTHIAS
24  * RINGWALD 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 "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 #endif
69 
70 #ifndef NVN_NUM_GATT_SERVER_CCC
71 #define NVN_NUM_GATT_SERVER_CCC 20
72 #endif
73 
74 static void att_run_for_context(hci_connection_t * hci_connection);
75 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle);
76 static btstack_packet_handler_t att_server_packet_handler_for_handle(uint16_t handle);
77 static void att_server_handle_can_send_now(void);
78 static void att_server_persistent_ccc_restore(hci_connection_t * hci_connection);
79 static void att_server_persistent_ccc_clear(hci_connection_t * hci_connection);
80 static void att_server_handle_att_pdu(hci_connection_t * hci_connection, uint8_t * packet, uint16_t size);
81 
82 typedef enum {
83     ATT_SERVER_RUN_PHASE_1_REQUESTS,
84     ATT_SERVER_RUN_PHASE_2_INDICATIONS,
85     ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS,
86 } att_server_run_phase_t;
87 
88 //
89 typedef struct {
90     uint32_t seq_nr;
91     uint16_t att_handle;
92     uint8_t  value;
93     uint8_t  device_index;
94 } persistent_ccc_entry_t;
95 
96 // global
97 static btstack_packet_callback_registration_t hci_event_callback_registration;
98 static btstack_packet_callback_registration_t sm_event_callback_registration;
99 static btstack_packet_handler_t               att_client_packet_handler = NULL;
100 static btstack_linked_list_t                  service_handlers;
101 static btstack_context_callback_registration_t att_client_waiting_for_can_send_registration;
102 
103 static att_read_callback_t                    att_server_client_read_callback;
104 static att_write_callback_t                   att_server_client_write_callback;
105 
106 // round robin
107 static hci_con_handle_t att_server_last_can_send_now = HCI_CON_HANDLE_INVALID;
108 
109 #ifdef ENABLE_LE_SIGNED_WRITE
110 static hci_connection_t * hci_connection_for_state(att_server_state_t state){
111     btstack_linked_list_iterator_t it;
112     hci_connections_get_iterator(&it);
113     while(btstack_linked_list_iterator_has_next(&it)){
114         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
115         att_server_t * att_server = &connection->att_server;
116         if (att_server->state == state) return connection;
117     }
118     return NULL;
119 }
120 #endif
121 
122 static void att_server_request_can_send_now(hci_connection_t * hci_connection){
123     att_server_t * att_server = &hci_connection->att_server;
124 #ifdef ENABLE_GATT_OVER_CLASSIC
125     if (att_server->l2cap_cid != 0){
126         l2cap_request_can_send_now_event(att_server->l2cap_cid);
127         return;
128     }
129 #endif
130     att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
131 }
132 
133 static int att_server_can_send_packet(hci_connection_t * hci_connection){
134     att_server_t * att_server = &hci_connection->att_server;
135 #ifdef ENABLE_GATT_OVER_CLASSIC
136     if (att_server->l2cap_cid != 0){
137         return l2cap_can_send_packet_now(att_server->l2cap_cid);
138     }
139 #endif
140     return att_dispatch_server_can_send_now(att_server->connection.con_handle);
141 }
142 
143 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
144     btstack_packet_handler_t packet_handler = att_server_packet_handler_for_handle(attribute_handle);
145     if (!packet_handler) return;
146 
147     uint8_t event[7];
148     int pos = 0;
149     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
150     event[pos++] = sizeof(event) - 2u;
151     event[pos++] = status;
152     little_endian_store_16(event, pos, client_handle);
153     pos += 2;
154     little_endian_store_16(event, pos, attribute_handle);
155     (*packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
156 }
157 
158 static void att_emit_event_to_all(const uint8_t * event, uint16_t size){
159     // dispatch to app level handler
160     if (att_client_packet_handler){
161         (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t*) event, size);
162     }
163 
164     // dispatch to service handlers
165     btstack_linked_list_iterator_t it;
166     btstack_linked_list_iterator_init(&it, &service_handlers);
167     while (btstack_linked_list_iterator_has_next(&it)){
168         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
169         if (!handler->packet_handler) continue;
170         (*handler->packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t*) event, size);
171     }
172 }
173 
174 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
175     uint8_t event[6];
176     int pos = 0;
177     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
178     event[pos++] = sizeof(event) - 2u;
179     little_endian_store_16(event, pos, con_handle);
180     pos += 2;
181     little_endian_store_16(event, pos, mtu);
182 
183     // also dispatch to GATT Clients
184     att_dispatch_server_mtu_exchanged(con_handle, mtu);
185 
186     // dispatch to app level handler and service handlers
187     att_emit_event_to_all(&event[0], sizeof(event));
188 }
189 
190 static void att_emit_can_send_now_event(void * context){
191     UNUSED(context);
192     if (!att_client_packet_handler) return;
193 
194     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
195     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
196 }
197 
198 static void att_emit_connected_event(hci_connection_t * hci_connection){
199     att_server_t * att_server = &hci_connection->att_server;
200     uint8_t event[11];
201     int pos = 0;
202     event[pos++] = ATT_EVENT_CONNECTED;
203     event[pos++] = sizeof(event) - 2u;
204     event[pos++] = att_server->peer_addr_type;
205     reverse_bd_addr(att_server->peer_address, &event[pos]);
206     pos += 6;
207     little_endian_store_16(event, pos, att_server->connection.con_handle);
208     pos += 2;
209 
210     // dispatch to app level handler and service handlers
211     att_emit_event_to_all(&event[0], sizeof(event));
212 }
213 
214 
215 static void att_emit_disconnected_event(uint16_t con_handle){
216     uint8_t event[4];
217     int pos = 0;
218     event[pos++] = ATT_EVENT_DISCONNECTED;
219     event[pos++] = sizeof(event) - 2u;
220     little_endian_store_16(event, pos, con_handle);
221     pos += 2;
222 
223     // dispatch to app level handler and service handlers
224     att_emit_event_to_all(&event[0], sizeof(event));
225 }
226 
227 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
228     void * context = btstack_run_loop_get_timer_context(ts);
229     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) context;
230     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
231     if (!hci_connection) return;
232     att_server_t * att_server = &hci_connection->att_server;
233     // @note: after a transaction timeout, no more requests shall be sent over this ATT Bearer
234     // (that's why we don't reset the value_indication_handle)
235     uint16_t att_handle = att_server->value_indication_handle;
236     att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_server->connection.con_handle, att_handle);
237 }
238 
239 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
240 
241     UNUSED(channel); // ok: there is no channel
242     UNUSED(size);    // ok: handling own l2cap events
243 
244     att_server_t * att_server;
245     hci_con_handle_t con_handle;
246     hci_connection_t * hci_connection;
247 #ifdef ENABLE_GATT_OVER_CLASSIC
248     bd_addr_t address;
249     btstack_linked_list_iterator_t it;
250 #endif
251 
252     switch (packet_type) {
253 
254         case HCI_EVENT_PACKET:
255             switch (hci_event_packet_get_type(packet)) {
256 
257 #ifdef ENABLE_GATT_OVER_CLASSIC
258                 case L2CAP_EVENT_INCOMING_CONNECTION:
259                     l2cap_event_incoming_connection_get_address(packet, address);
260                     l2cap_accept_connection(channel);
261                     log_info("Accept incoming connection from %s", bd_addr_to_str(address));
262                     break;
263                 case L2CAP_EVENT_CHANNEL_OPENED:
264                     con_handle = l2cap_event_channel_opened_get_handle(packet);
265                     hci_connection = hci_connection_for_handle(con_handle);
266                     if (!hci_connection) break;
267                     att_server = &hci_connection->att_server;
268                     // store connection info
269                     att_server->peer_addr_type = BD_ADDR_TYPE_ACL;
270                     l2cap_event_channel_opened_get_address(packet, att_server->peer_address);
271                     att_server->connection.con_handle = con_handle;
272                     att_server->l2cap_cid = l2cap_event_channel_opened_get_local_cid(packet);
273                     // reset connection properties
274                     att_server->state = ATT_SERVER_IDLE;
275                     att_server->connection.mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
276                     att_server->connection.max_mtu = l2cap_max_mtu();
277                     if (att_server->connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){
278                         att_server->connection.max_mtu = ATT_REQUEST_BUFFER_SIZE;
279                     }
280 
281                     log_info("Connection opened %s, l2cap cid %04x, mtu %u", bd_addr_to_str(address), att_server->l2cap_cid, att_server->connection.mtu);
282 
283                     // update security params
284                     att_server->connection.encryption_key_size = gap_encryption_key_size(con_handle);
285                     att_server->connection.authenticated = gap_authenticated(con_handle);
286                     att_server->connection.secure_connection = gap_secure_connection(con_handle);
287                     log_info("encrypted key size %u, authenticated %u, secure connection %u",
288                         att_server->connection.encryption_key_size, att_server->connection.authenticated, att_server->connection.secure_connection);
289 
290                     // notify connection opened
291                     att_emit_connected_event(hci_connection);
292 
293                     // restore persisten ccc if encrypted
294                     if ( gap_security_level(con_handle) >= LEVEL_2){
295                         att_server_persistent_ccc_restore(hci_connection);
296                     }
297                     // TODO: what to do about le device db?
298                     att_server->pairing_active = 0;
299                     break;
300                 case L2CAP_EVENT_CAN_SEND_NOW:
301                     att_server_handle_can_send_now();
302                     break;
303 
304 #endif
305                 case HCI_EVENT_LE_META:
306                     switch (packet[2]) {
307                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
308                             con_handle = little_endian_read_16(packet, 4);
309                             hci_connection = hci_connection_for_handle(con_handle);
310                             if (!hci_connection) break;
311                             att_server = &hci_connection->att_server;
312                         	// store connection info
313                         	att_server->peer_addr_type = packet[7];
314                             reverse_bd_addr(&packet[8], att_server->peer_address);
315                             att_server->connection.con_handle = con_handle;
316                             // reset connection properties
317                             att_server->state = ATT_SERVER_IDLE;
318                             att_server->connection.mtu = ATT_DEFAULT_MTU;
319                             att_server->connection.max_mtu = l2cap_max_le_mtu();
320                             if (att_server->connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){
321                                 att_server->connection.max_mtu = ATT_REQUEST_BUFFER_SIZE;
322                             }
323                             att_server->connection.encryption_key_size = 0;
324                             att_server->connection.authenticated = 0;
325 		                	att_server->connection.authorized = 0;
326                             // workaround: identity resolving can already be complete, at least store result
327                             att_server->ir_le_device_db_index = sm_le_device_index(con_handle);
328                             att_server->ir_lookup_active = 0;
329                             att_server->pairing_active = 0;
330                             // notify all - old
331                             att_emit_event_to_all(packet, size);
332                             // notify all - new
333                             att_emit_connected_event(hci_connection);
334                             break;
335 
336                         default:
337                             break;
338                     }
339                     break;
340 
341                 case HCI_EVENT_ENCRYPTION_CHANGE:
342                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
343                 	// check handle
344                     con_handle = little_endian_read_16(packet, 3);
345                     hci_connection = hci_connection_for_handle(con_handle);
346                     if (!hci_connection) break;
347                     if (gap_get_connection_type(con_handle) != GAP_CONNECTION_LE) break;
348                     // update security params
349                     att_server = &hci_connection->att_server;
350                     att_server->connection.encryption_key_size = gap_encryption_key_size(con_handle);
351                     att_server->connection.authenticated = gap_authenticated(con_handle);
352                     att_server->connection.secure_connection = gap_secure_connection(con_handle);
353                     log_info("encrypted key size %u, authenticated %u, secure connection %u",
354                         att_server->connection.encryption_key_size, att_server->connection.authenticated, att_server->connection.secure_connection);
355                     if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE){
356                         // restore CCC values when encrypted for LE Connections
357                         if (hci_event_encryption_change_get_encryption_enabled(packet)){
358                             att_server_persistent_ccc_restore(hci_connection);
359                         }
360                     }
361                     att_run_for_context(hci_connection);
362                     break;
363 
364                 case HCI_EVENT_DISCONNECTION_COMPLETE:
365                     // check handle
366                     con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
367                     hci_connection = hci_connection_for_handle(con_handle);
368                     if (!hci_connection) break;
369                     att_server = &hci_connection->att_server;
370                     att_clear_transaction_queue(&att_server->connection);
371                     att_server->connection.con_handle = 0;
372                     att_server->pairing_active = 0;
373                     att_server->state = ATT_SERVER_IDLE;
374                     if (att_server->value_indication_handle){
375                         btstack_run_loop_remove_timer(&att_server->value_indication_timer);
376                         uint16_t att_handle = att_server->value_indication_handle;
377                         att_server->value_indication_handle = 0; // reset error state
378                         att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_DISCONNECT, att_server->connection.con_handle, att_handle);
379                     }
380                     // notify all - new
381                     att_emit_disconnected_event(con_handle);
382                     // notify all - old
383                     att_emit_event_to_all(packet, size);
384                     break;
385 
386                 // Identity Resolving
387                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
388                     con_handle = sm_event_identity_resolving_started_get_handle(packet);
389                     hci_connection = hci_connection_for_handle(con_handle);
390                     if (!hci_connection) break;
391                     att_server = &hci_connection->att_server;
392                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
393                     att_server->ir_lookup_active = 1;
394                     break;
395                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
396                     con_handle = sm_event_identity_created_get_handle(packet);
397                     hci_connection = hci_connection_for_handle(con_handle);
398                     if (!hci_connection) return;
399                     att_server = &hci_connection->att_server;
400                     att_server->ir_lookup_active = 0;
401                     att_server->ir_le_device_db_index = sm_event_identity_resolving_succeeded_get_index(packet);
402                     log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED");
403                     att_run_for_context(hci_connection);
404                     break;
405                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
406                     con_handle = sm_event_identity_resolving_failed_get_handle(packet);
407                     hci_connection = hci_connection_for_handle(con_handle);
408                     if (!hci_connection) break;
409                     att_server = &hci_connection->att_server;
410                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
411                     att_server->ir_lookup_active = 0;
412                     att_server->ir_le_device_db_index = -1;
413                     att_run_for_context(hci_connection);
414                     break;
415 
416                 // Pairing started - delete stored CCC values
417                 // - assumes pairing indicates either new device or re-pairing, in both cases there should be no stored CCC values
418                 // - assumes that all events have the con handle as the first field
419                 case SM_EVENT_JUST_WORKS_REQUEST:
420                 case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
421                 case SM_EVENT_PASSKEY_INPUT_NUMBER:
422                 case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
423                     con_handle = sm_event_just_works_request_get_handle(packet);
424                     hci_connection = hci_connection_for_handle(con_handle);
425                     if (!hci_connection) break;
426                     att_server = &hci_connection->att_server;
427                     att_server->pairing_active = 1;
428                     log_info("SM Pairing started");
429                     if (att_server->ir_le_device_db_index < 0) break;
430                     att_server_persistent_ccc_clear(hci_connection);
431                     // index not valid anymore
432                     att_server->ir_le_device_db_index = -1;
433                     break;
434 
435                 // Bonding completed
436                 case SM_EVENT_IDENTITY_CREATED:
437                     con_handle = sm_event_identity_created_get_handle(packet);
438                     hci_connection = hci_connection_for_handle(con_handle);
439                     if (!hci_connection) return;
440                     att_server = &hci_connection->att_server;
441                     att_server->pairing_active = 0;
442                     att_server->ir_le_device_db_index = sm_event_identity_created_get_index(packet);
443                     att_run_for_context(hci_connection);
444                     break;
445 
446                 // Pairing complete (with/without bonding=storing of pairing information)
447                 case SM_EVENT_PAIRING_COMPLETE:
448                     con_handle = sm_event_pairing_complete_get_handle(packet);
449                     hci_connection = hci_connection_for_handle(con_handle);
450                     if (!hci_connection) return;
451                     att_server = &hci_connection->att_server;
452                     att_server->pairing_active = 0;
453                     att_run_for_context(hci_connection);
454                     break;
455 
456                 // Authorization
457                 case SM_EVENT_AUTHORIZATION_RESULT: {
458                     con_handle = sm_event_authorization_result_get_handle(packet);
459                     hci_connection = hci_connection_for_handle(con_handle);
460                     if (!hci_connection) break;
461                     att_server = &hci_connection->att_server;
462                     att_server->connection.authorized = sm_event_authorization_result_get_authorization_result(packet);
463                     att_server_request_can_send_now(hci_connection);
464                 	break;
465                 }
466                 default:
467                     break;
468             }
469             break;
470 #ifdef ENABLE_GATT_OVER_CLASSIC
471         case L2CAP_DATA_PACKET:
472             hci_connections_get_iterator(&it);
473             while(btstack_linked_list_iterator_has_next(&it)){
474                 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
475                 att_server = &connection->att_server;
476                 if (att_server->l2cap_cid == channel) {
477                     att_server_handle_att_pdu(connection, packet, size);
478                     break;
479                 }
480             }
481             break;
482 #endif
483 
484         default:
485             break;
486     }
487 }
488 
489 #ifdef ENABLE_LE_SIGNED_WRITE
490 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
491 
492     hci_connection_t * hci_connection = hci_connection_for_state(ATT_SERVER_W4_SIGNED_WRITE_VALIDATION);
493     if (!hci_connection) return;
494     att_server_t * att_server = &hci_connection->att_server;
495 
496     uint8_t hash_flipped[8];
497     reverse_64(hash, hash_flipped);
498     if (memcmp(hash_flipped, &att_server->request_buffer[att_server->request_size-8], 8)){
499         log_info("ATT Signed Write, invalid signature");
500         att_server->state = ATT_SERVER_IDLE;
501         return;
502     }
503     log_info("ATT Signed Write, valid signature");
504 
505     // update sequence number
506     uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
507     le_device_db_remote_counter_set(att_server->ir_le_device_db_index, counter_packet+1);
508     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
509     att_server_request_can_send_now(hci_connection);
510 }
511 #endif
512 
513 // pre: att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
514 // pre: can send now
515 // returns: 1 if packet was sent
516 static int att_server_process_validated_request(hci_connection_t * hci_connection){
517     att_server_t * att_server = & hci_connection->att_server;
518 
519     l2cap_reserve_packet_buffer();
520     uint8_t * att_response_buffer = l2cap_get_outgoing_buffer();
521     uint16_t  att_response_size   = att_handle_request(&att_server->connection, att_server->request_buffer, att_server->request_size, att_response_buffer);
522 
523 #ifdef ENABLE_ATT_DELAYED_RESPONSE
524     if ((att_response_size == ATT_READ_RESPONSE_PENDING) || (att_response_size == ATT_INTERNAL_WRITE_RESPONSE_PENDING)){
525         // update state
526         att_server->state = ATT_SERVER_RESPONSE_PENDING;
527 
528         // callback with handle ATT_READ_RESPONSE_PENDING for reads
529         if (att_response_size == ATT_READ_RESPONSE_PENDING){
530             att_server_client_read_callback(att_server->connection.con_handle, ATT_READ_RESPONSE_PENDING, 0, NULL, 0);
531         }
532 
533         // free reserved buffer
534         l2cap_release_packet_buffer();
535         return 0;
536     }
537 #endif
538 
539     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
540     if ((att_response_size     >= 4u)
541     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
542     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
543     && (att_server->connection.authenticated)){
544 
545         switch (gap_authorization_state(att_server->connection.con_handle)){
546             case AUTHORIZATION_UNKNOWN:
547                 l2cap_release_packet_buffer();
548                 sm_request_pairing(att_server->connection.con_handle);
549                 return 0;
550             case AUTHORIZATION_PENDING:
551                 l2cap_release_packet_buffer();
552                 return 0;
553             default:
554                 break;
555         }
556     }
557 
558     att_server->state = ATT_SERVER_IDLE;
559     if (att_response_size == 0u) {
560         l2cap_release_packet_buffer();
561         return 0;
562     }
563 
564 #ifdef ENABLE_GATT_OVER_CLASSIC
565     if (att_server->l2cap_cid != 0){
566         l2cap_send_prepared(att_server->l2cap_cid, att_response_size);
567     } else
568 #endif
569     {
570         l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size);
571     }
572 
573     // notify client about MTU exchange result
574     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
575         att_emit_mtu_event(att_server->connection.con_handle, att_server->connection.mtu);
576     }
577     return 1;
578 }
579 
580 #ifdef ENABLE_ATT_DELAYED_RESPONSE
581 int att_server_response_ready(hci_con_handle_t con_handle){
582     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
583     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
584     att_server_t * att_server = &hci_connection->att_server;
585 
586     if (att_server->state != ATT_SERVER_RESPONSE_PENDING)   return ERROR_CODE_COMMAND_DISALLOWED;
587 
588     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
589     att_server_request_can_send_now(hci_connection);
590     return ERROR_CODE_SUCCESS;
591 }
592 #endif
593 
594 static void att_run_for_context(hci_connection_t * hci_connection){
595     att_server_t * att_server = &hci_connection->att_server;
596     switch (att_server->state){
597         case ATT_SERVER_REQUEST_RECEIVED:
598 
599 #ifdef ENABLE_GATT_OVER_CLASSIC
600             if (att_server->l2cap_cid != 0){
601                 // ok
602             } else
603 #endif
604             {
605                 // wait until re-encryption as central is complete
606                 if (gap_reconnect_security_setup_active(att_server->connection.con_handle)) break;
607             }
608 
609             // wait until pairing is complete
610             if (att_server->pairing_active) break;
611 
612 #ifdef ENABLE_LE_SIGNED_WRITE
613             if (att_server->request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
614                 log_info("ATT Signed Write!");
615                 if (!sm_cmac_ready()) {
616                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
617                     att_server->state = ATT_SERVER_IDLE;
618                     return;
619                 }
620                 if (att_server->request_size < (3 + 12)) {
621                     log_info("ATT Signed Write, request to short. Abort.");
622                     att_server->state = ATT_SERVER_IDLE;
623                     return;
624                 }
625                 if (att_server->ir_lookup_active){
626                     return;
627                 }
628                 if (att_server->ir_le_device_db_index < 0){
629                     log_info("ATT Signed Write, CSRK not available");
630                     att_server->state = ATT_SERVER_IDLE;
631                     return;
632                 }
633 
634                 // check counter
635                 uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
636                 uint32_t counter_db     = le_device_db_remote_counter_get(att_server->ir_le_device_db_index);
637                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
638                 if (counter_packet < counter_db){
639                     log_info("ATT Signed Write, db reports higher counter, abort");
640                     att_server->state = ATT_SERVER_IDLE;
641                     return;
642                 }
643 
644                 // signature is { sequence counter, secure hash }
645                 sm_key_t csrk;
646                 le_device_db_remote_csrk_get(att_server->ir_le_device_db_index, csrk);
647                 att_server->state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
648                 log_info("Orig Signature: ");
649                 log_info_hexdump( &att_server->request_buffer[att_server->request_size-8], 8);
650                 uint16_t attribute_handle = little_endian_read_16(att_server->request_buffer, 1);
651                 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);
652                 return;
653             }
654 #endif
655             // move on
656             att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
657             att_server_request_can_send_now(hci_connection);
658             break;
659 
660         default:
661             break;
662     }
663 }
664 
665 static int att_server_data_ready_for_phase(att_server_t * att_server,  att_server_run_phase_t phase){
666     switch (phase){
667         case ATT_SERVER_RUN_PHASE_1_REQUESTS:
668             return att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
669         case ATT_SERVER_RUN_PHASE_2_INDICATIONS:
670              return (!btstack_linked_list_empty(&att_server->indication_requests) && (att_server->value_indication_handle == 0));
671         case ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS:
672             return (!btstack_linked_list_empty(&att_server->notification_requests));
673         default:
674             btstack_assert(false);
675             return 0;
676     }
677 }
678 
679 static void att_server_trigger_send_for_phase(hci_connection_t * hci_connection,  att_server_run_phase_t phase){
680     btstack_context_callback_registration_t * client;
681     att_server_t * att_server = &hci_connection->att_server;
682     switch (phase){
683         case ATT_SERVER_RUN_PHASE_1_REQUESTS:
684             att_server_process_validated_request(hci_connection);
685             break;
686         case ATT_SERVER_RUN_PHASE_2_INDICATIONS:
687             client = (btstack_context_callback_registration_t*) att_server->indication_requests;
688             btstack_linked_list_remove(&att_server->indication_requests, (btstack_linked_item_t *) client);
689             client->callback(client->context);
690             break;
691        case ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS:
692             client = (btstack_context_callback_registration_t*) att_server->notification_requests;
693             btstack_linked_list_remove(&att_server->notification_requests, (btstack_linked_item_t *) client);
694             client->callback(client->context);
695             break;
696         default:
697             btstack_assert(false);
698             break;
699     }
700 }
701 
702 static void att_server_handle_can_send_now(void){
703 
704     hci_con_handle_t last_send_con_handle = HCI_CON_HANDLE_INVALID;
705     hci_connection_t * request_hci_connection   = NULL;
706     int can_send_now = 1;
707     int phase_index;
708 
709     for (phase_index = ATT_SERVER_RUN_PHASE_1_REQUESTS; phase_index <= ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS; phase_index++){
710         att_server_run_phase_t phase = (att_server_run_phase_t) phase_index;
711         hci_con_handle_t skip_connections_until = att_server_last_can_send_now;
712         while (true){
713             btstack_linked_list_iterator_t it;
714             hci_connections_get_iterator(&it);
715             while(btstack_linked_list_iterator_has_next(&it)){
716                 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
717                 att_server_t * att_server = &connection->att_server;
718 
719                 int data_ready = att_server_data_ready_for_phase(att_server, phase);
720 
721                 // log_debug("phase %u, handle 0x%04x, skip until 0x%04x, data ready %u", phase, att_server->connection.con_handle, skip_connections_until, data_ready);
722 
723                 // skip until last sender found (which is also skipped)
724                 if (skip_connections_until != HCI_CON_HANDLE_INVALID){
725                     if (data_ready && (request_hci_connection == NULL)){
726                         request_hci_connection = connection;
727                     }
728                     if (skip_connections_until == att_server->connection.con_handle){
729                         skip_connections_until = HCI_CON_HANDLE_INVALID;
730                     }
731                     continue;
732                 };
733 
734                 if (data_ready){
735                     if (can_send_now){
736                         att_server_trigger_send_for_phase(connection, phase);
737                         last_send_con_handle = att_server->connection.con_handle;
738                         can_send_now = att_server_can_send_packet(connection);
739                         data_ready = att_server_data_ready_for_phase(att_server, phase);
740                         if (data_ready && (request_hci_connection == NULL)){
741                             request_hci_connection = connection;
742                         }
743                     } else {
744                         request_hci_connection = connection;
745                         break;
746                     }
747                 }
748             }
749 
750             // stop skipping (handles disconnect by last send connection)
751             skip_connections_until = HCI_CON_HANDLE_INVALID;
752 
753             // Exit loop, if we cannot send
754             if (!can_send_now) break;
755 
756             // Exit loop, if we can send but there are also no further request
757             if (request_hci_connection == NULL) break;
758 
759             // Finally, if we still can send and there are requests, just try again
760             request_hci_connection = NULL;
761         }
762         // update last send con handle for round robin
763         if (last_send_con_handle != HCI_CON_HANDLE_INVALID){
764             att_server_last_can_send_now = last_send_con_handle;
765         }
766     }
767 
768     if (request_hci_connection == NULL) return;
769     att_server_request_can_send_now(request_hci_connection);
770 }
771 
772 static void att_server_handle_att_pdu(hci_connection_t * hci_connection, uint8_t * packet, uint16_t size){
773     att_server_t * att_server = &hci_connection->att_server;
774 
775     // handle value indication confirms
776     if ((packet[0] == ATT_HANDLE_VALUE_CONFIRMATION) && att_server->value_indication_handle){
777         btstack_run_loop_remove_timer(&att_server->value_indication_timer);
778         uint16_t att_handle = att_server->value_indication_handle;
779         att_server->value_indication_handle = 0;
780         att_handle_value_indication_notify_client(0, att_server->connection.con_handle, att_handle);
781         att_server_request_can_send_now(hci_connection);
782         return;
783     }
784 
785     // directly process command
786     // note: signed write cannot be handled directly as authentication needs to be verified
787     if (packet[0] == ATT_WRITE_COMMAND){
788         att_handle_request(&att_server->connection, packet, size, NULL);
789         return;
790     }
791 
792     // check size
793     if (size > sizeof(att_server->request_buffer)) {
794         log_info("drop att pdu 0x%02x as size %u > att_server->request_buffer %u", packet[0], size, (int) sizeof(att_server->request_buffer));
795         return;
796     }
797 
798 #ifdef ENABLE_LE_SIGNED_WRITE
799     // abort signed write validation if a new request comes in (but finish previous signed write if possible)
800     if (att_server->state == ATT_SERVER_W4_SIGNED_WRITE_VALIDATION){
801         if (packet[0] == ATT_SIGNED_WRITE_COMMAND){
802             log_info("skip new signed write request as previous is in validation");
803             return;
804         } else {
805             log_info("abort signed write validation to process new request");
806             att_server->state = ATT_SERVER_IDLE;
807         }
808     }
809 #endif
810     // last request still in processing?
811     if (att_server->state != ATT_SERVER_IDLE){
812         log_info("skip att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state);
813         return;
814     }
815 
816     // store request
817     att_server->state = ATT_SERVER_REQUEST_RECEIVED;
818     att_server->request_size = size;
819     (void)memcpy(att_server->request_buffer, packet, size);
820 
821     att_run_for_context(hci_connection);
822 }
823 
824 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
825     att_server_t * att_server;
826     hci_connection_t * hci_connection;
827 
828     switch (packet_type){
829         case HCI_EVENT_PACKET:
830             switch (packet[0]){
831                 case L2CAP_EVENT_CAN_SEND_NOW:
832                     att_server_handle_can_send_now();
833                     break;
834                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
835                     // GATT client has negotiated the mtu for this connection
836                     hci_connection = hci_connection_for_handle(handle);
837                     if (!hci_connection) break;
838                     att_server = &hci_connection->att_server;
839                     att_server->connection.mtu = little_endian_read_16(packet, 4);
840                     break;
841                 default:
842                     break;
843             }
844             break;
845 
846         case ATT_DATA_PACKET:
847             log_debug("ATT Packet, handle 0x%04x", handle);
848             hci_connection = hci_connection_for_handle(handle);
849             if (!hci_connection) break;
850 
851             att_server_handle_att_pdu(hci_connection, packet, size);
852             break;
853 
854         default:
855             break;
856     }
857 }
858 
859 // ---------------------
860 // persistent CCC writes
861 static uint32_t att_server_persistent_ccc_tag_for_index(uint8_t index){
862     return ('B' << 24u) | ('T' << 16u) | ('C' << 8u) | index;
863 }
864 
865 static void att_server_persistent_ccc_write(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t value){
866     // lookup att_server instance
867     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
868     if (!hci_connection) return;
869     att_server_t * att_server = &hci_connection->att_server;
870     int le_device_index = att_server->ir_le_device_db_index;
871     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);
872 
873     // check if bonded
874     if (le_device_index < 0) return;
875 
876     // get btstack_tlv
877     const btstack_tlv_t * tlv_impl = NULL;
878     void * tlv_context;
879     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
880     if (!tlv_impl) return;
881 
882     // update ccc tag
883     int index;
884     uint32_t highest_seq_nr = 0;
885     uint32_t lowest_seq_nr = 0;
886     uint32_t tag_for_lowest_seq_nr = 0;
887     uint32_t tag_for_empty = 0;
888     persistent_ccc_entry_t entry;
889     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
890         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
891         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
892 
893         // empty/invalid tag
894         if (len != sizeof(persistent_ccc_entry_t)){
895             tag_for_empty = tag;
896             continue;
897         }
898         // update highest seq nr
899         if (entry.seq_nr > highest_seq_nr){
900             highest_seq_nr = entry.seq_nr;
901         }
902         // find entry with lowest seq nr
903         if ((tag_for_lowest_seq_nr == 0u) || (entry.seq_nr < lowest_seq_nr)){
904             tag_for_lowest_seq_nr = tag;
905             lowest_seq_nr = entry.seq_nr;
906         }
907 
908         if (entry.device_index != le_device_index) continue;
909         if (entry.att_handle   != att_handle)      continue;
910 
911         // found matching entry
912         if (value){
913             // update
914             if (entry.value == value) {
915                 log_info("CCC Index %u: Up-to-date", index);
916                 return;
917             }
918             entry.value = value;
919             entry.seq_nr = highest_seq_nr + 1u;
920             log_info("CCC Index %u: Store", index);
921             int result = tlv_impl->store_tag(tlv_context, tag, (const uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
922             if (result != 0){
923                 log_error("Store tag index %u failed", index);
924             }
925         } else {
926             // delete
927             log_info("CCC Index %u: Delete", index);
928             tlv_impl->delete_tag(tlv_context, tag);
929         }
930         return;
931     }
932 
933     log_info("tag_for_empty %"PRIx32", tag_for_lowest_seq_nr %"PRIx32, tag_for_empty, tag_for_lowest_seq_nr);
934 
935     if (value == 0u){
936         // done
937         return;
938     }
939 
940     uint32_t tag_to_use = 0;
941     if (tag_for_empty){
942         tag_to_use = tag_for_empty;
943     } else if (tag_for_lowest_seq_nr){
944         tag_to_use = tag_for_lowest_seq_nr;
945     } else {
946         // should not happen
947         return;
948     }
949     // store ccc tag
950     entry.seq_nr       = highest_seq_nr + 1u;
951     entry.device_index = le_device_index;
952     entry.att_handle   = att_handle;
953     entry.value        = value;
954     int result = tlv_impl->store_tag(tlv_context, tag_to_use, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
955     if (result != 0){
956         log_error("Store tag index %u failed", index);
957     }
958 }
959 
960 static void att_server_persistent_ccc_clear(hci_connection_t * hci_connection){
961     if (!hci_connection) return;
962     att_server_t * att_server = &hci_connection->att_server;
963 
964     int le_device_index = att_server->ir_le_device_db_index;
965     log_info("Clear CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
966     // check if bonded
967     if (le_device_index < 0) return;
968     // get btstack_tlv
969     const btstack_tlv_t * tlv_impl = NULL;
970     void * tlv_context;
971     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
972     if (!tlv_impl) return;
973     // get all ccc tag
974     int index;
975     persistent_ccc_entry_t entry;
976     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
977         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
978         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
979         if (len != sizeof(persistent_ccc_entry_t)) continue;
980         if (entry.device_index != le_device_index) continue;
981         // delete entry
982         log_info("CCC Index %u: Delete", index);
983         tlv_impl->delete_tag(tlv_context, tag);
984     }
985 }
986 
987 static void att_server_persistent_ccc_restore(hci_connection_t * hci_connection){
988     if (!hci_connection) return;
989     att_server_t * att_server = &hci_connection->att_server;
990 
991     int le_device_index = att_server->ir_le_device_db_index;
992     log_info("Restore CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
993     // check if bonded
994     if (le_device_index < 0) return;
995     // get btstack_tlv
996     const btstack_tlv_t * tlv_impl = NULL;
997     void * tlv_context;
998     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
999     if (!tlv_impl) return;
1000     // get all ccc tag
1001     int index;
1002     persistent_ccc_entry_t entry;
1003     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
1004         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
1005         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1006         if (len != sizeof(persistent_ccc_entry_t)) continue;
1007         if (entry.device_index != le_device_index) continue;
1008         // simulate write callback
1009         uint16_t attribute_handle = entry.att_handle;
1010         uint8_t  value[2];
1011         little_endian_store_16(value, 0, entry.value);
1012         att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
1013         if (!callback) continue;
1014         log_info("CCC Index %u: Set Attribute handle 0x%04x to value 0x%04x", index, attribute_handle, entry.value );
1015         (*callback)(att_server->connection.con_handle, attribute_handle, ATT_TRANSACTION_MODE_NONE, 0, value, sizeof(value));
1016     }
1017 }
1018 
1019 // persistent CCC writes
1020 // ---------------------
1021 
1022 // gatt service management
1023 static att_service_handler_t * att_service_handler_for_handle(uint16_t handle){
1024     btstack_linked_list_iterator_t it;
1025     btstack_linked_list_iterator_init(&it, &service_handlers);
1026     while (btstack_linked_list_iterator_has_next(&it)){
1027         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1028         if (handler->start_handle > handle) continue;
1029         if (handler->end_handle   < handle) continue;
1030         return handler;
1031     }
1032     return NULL;
1033 }
1034 static att_read_callback_t att_server_read_callback_for_handle(uint16_t handle){
1035     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1036     if (handler) return handler->read_callback;
1037     return att_server_client_read_callback;
1038 }
1039 
1040 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle){
1041     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1042     if (handler) return handler->write_callback;
1043     return att_server_client_write_callback;
1044 }
1045 
1046 static btstack_packet_handler_t att_server_packet_handler_for_handle(uint16_t handle){
1047     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1048     if (handler) return handler->packet_handler;
1049     return att_client_packet_handler;
1050 }
1051 
1052 static void att_notify_write_callbacks(hci_con_handle_t con_handle, uint16_t transaction_mode){
1053     // notify all callbacks
1054     btstack_linked_list_iterator_t it;
1055     btstack_linked_list_iterator_init(&it, &service_handlers);
1056     while (btstack_linked_list_iterator_has_next(&it)){
1057         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1058         if (!handler->write_callback) continue;
1059         (*handler->write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
1060     }
1061     if (!att_server_client_write_callback) return;
1062     (*att_server_client_write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
1063 }
1064 
1065 // returns first reported error or 0
1066 static uint8_t att_validate_prepared_write(hci_con_handle_t con_handle){
1067     btstack_linked_list_iterator_t it;
1068     btstack_linked_list_iterator_init(&it, &service_handlers);
1069     while (btstack_linked_list_iterator_has_next(&it)){
1070         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1071         if (!handler->write_callback) continue;
1072         uint8_t error_code = (*handler->write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1073         if (error_code) return error_code;
1074     }
1075     if (!att_server_client_write_callback) return 0;
1076     return (*att_server_client_write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1077 }
1078 
1079 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){
1080     att_read_callback_t callback = att_server_read_callback_for_handle(attribute_handle);
1081     if (!callback) return 0;
1082     return (*callback)(con_handle, attribute_handle, offset, buffer, buffer_size);
1083 }
1084 
1085 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){
1086     switch (transaction_mode){
1087         case ATT_TRANSACTION_MODE_VALIDATE:
1088             return att_validate_prepared_write(con_handle);
1089         case ATT_TRANSACTION_MODE_EXECUTE:
1090         case ATT_TRANSACTION_MODE_CANCEL:
1091             att_notify_write_callbacks(con_handle, transaction_mode);
1092             return 0;
1093         default:
1094             break;
1095     }
1096 
1097     // track CCC writes
1098     if (att_is_persistent_ccc(attribute_handle) && (offset == 0u) && (buffer_size == 2u)){
1099         att_server_persistent_ccc_write(con_handle, attribute_handle, little_endian_read_16(buffer, 0));
1100     }
1101 
1102     att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
1103     if (!callback) return 0;
1104     return (*callback)(con_handle, attribute_handle, transaction_mode, offset, buffer, buffer_size);
1105 }
1106 
1107 /**
1108  * @brief register read/write callbacks for specific handle range
1109  * @param att_service_handler_t
1110  */
1111 void att_server_register_service_handler(att_service_handler_t * handler){
1112     if (att_service_handler_for_handle(handler->start_handle) ||
1113         att_service_handler_for_handle(handler->end_handle)){
1114         log_error("handler for range 0x%04x-0x%04x already registered", handler->start_handle, handler->end_handle);
1115         return;
1116     }
1117     btstack_linked_list_add(&service_handlers, (btstack_linked_item_t*) handler);
1118 }
1119 
1120 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
1121 
1122     // store callbacks
1123     att_server_client_read_callback  = read_callback;
1124     att_server_client_write_callback = write_callback;
1125 
1126     // register for HCI Events
1127     hci_event_callback_registration.callback = &att_event_packet_handler;
1128     hci_add_event_handler(&hci_event_callback_registration);
1129 
1130     // register for SM events
1131     sm_event_callback_registration.callback = &att_event_packet_handler;
1132     sm_add_event_handler(&sm_event_callback_registration);
1133 
1134     // and L2CAP ATT Server PDUs
1135     att_dispatch_register_server(att_packet_handler);
1136 
1137 #ifdef ENABLE_GATT_OVER_CLASSIC
1138     // setup l2cap service
1139     l2cap_register_service(&att_event_packet_handler, PSM_ATT, 0xffff, LEVEL_2);
1140 #endif
1141 
1142     att_set_db(db);
1143     att_set_read_callback(att_server_read_callback);
1144     att_set_write_callback(att_server_write_callback);
1145 }
1146 
1147 void att_server_register_packet_handler(btstack_packet_handler_t handler){
1148     att_client_packet_handler = handler;
1149 }
1150 
1151 
1152 // to be deprecated
1153 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
1154     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1155     if (!hci_connection) return 0;
1156     return att_server_can_send_packet(hci_connection);
1157 }
1158 
1159 int att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1160     return att_server_request_to_send_notification(callback_registration, con_handle);
1161 }
1162 
1163 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
1164     att_client_waiting_for_can_send_registration.callback = &att_emit_can_send_now_event;
1165     att_server_request_to_send_notification(&att_client_waiting_for_can_send_registration, con_handle);
1166 }
1167 // end of deprecated
1168 
1169 int att_server_request_to_send_notification(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1170     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1171     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1172     att_server_t * att_server = &hci_connection->att_server;
1173     bool added = btstack_linked_list_add_tail(&att_server->notification_requests, (btstack_linked_item_t*) callback_registration);
1174     att_server_request_can_send_now(hci_connection);
1175     if (added){
1176         return ERROR_CODE_SUCCESS;
1177     } else {
1178         return ERROR_CODE_COMMAND_DISALLOWED;
1179     }
1180 }
1181 
1182 int att_server_request_to_send_indication(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1183     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1184     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1185     att_server_t * att_server = &hci_connection->att_server;
1186     bool added = btstack_linked_list_add_tail(&att_server->indication_requests, (btstack_linked_item_t*) callback_registration);
1187     att_server_request_can_send_now(hci_connection);
1188     if (added){
1189         return ERROR_CODE_SUCCESS;
1190     } else {
1191         return ERROR_CODE_COMMAND_DISALLOWED;
1192     }
1193 }
1194 
1195 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, const uint8_t *value, uint16_t value_len){
1196     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1197     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1198     att_server_t * att_server = &hci_connection->att_server;
1199 
1200     if (!att_server_can_send_packet(hci_connection)) return BTSTACK_ACL_BUFFERS_FULL;
1201 
1202     l2cap_reserve_packet_buffer();
1203     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
1204     uint16_t size = att_prepare_handle_value_notification(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
1205 	return l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
1206 }
1207 
1208 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, const uint8_t *value, uint16_t value_len){
1209     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1210     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1211     att_server_t * att_server = &hci_connection->att_server;
1212 
1213     if (att_server->value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PROGRESS;
1214     if (!att_server_can_send_packet(hci_connection)) return BTSTACK_ACL_BUFFERS_FULL;
1215 
1216     // track indication
1217     att_server->value_indication_handle = attribute_handle;
1218     btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout);
1219     btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
1220     btstack_run_loop_add_timer(&att_server->value_indication_timer);
1221 
1222     l2cap_reserve_packet_buffer();
1223     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
1224     uint16_t size = att_prepare_handle_value_indication(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
1225 	l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
1226     return 0;
1227 }
1228 
1229 uint16_t att_server_get_mtu(hci_con_handle_t con_handle){
1230     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1231     if (!hci_connection) return 0;
1232     att_server_t * att_server = &hci_connection->att_server;
1233     return att_server->connection.mtu;
1234 }
1235