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