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