xref: /btstack/src/ble/att_server.c (revision 5f141511e0794c41ca75f0b098484e7ece6d3665)
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 <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <inttypes.h>
50 
51 #include "btstack_config.h"
52 
53 #include "att_dispatch.h"
54 #include "ble/att_db.h"
55 #include "ble/att_server.h"
56 #include "ble/core.h"
57 #include "ble/le_device_db.h"
58 #include "ble/sm.h"
59 #include "btstack_debug.h"
60 #include "btstack_event.h"
61 #include "btstack_memory.h"
62 #include "btstack_run_loop.h"
63 #include "gap.h"
64 #include "hci.h"
65 #include "hci_dump.h"
66 #include "l2cap.h"
67 #include "btstack_tlv.h"
68 #ifdef ENABLE_LE_SIGNED_WRITE
69 #include "ble/sm.h"
70 #endif
71 
72 #ifndef NVN_NUM_GATT_SERVER_CCC
73 #define NVN_NUM_GATT_SERVER_CCC 20
74 #endif
75 
76 static void att_run_for_context(att_server_t * att_server);
77 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle);
78 static void att_server_persistent_ccc_restore(att_server_t * att_server);
79 static void att_server_persistent_ccc_clear(att_server_t * att_server);
80 
81 //
82 typedef struct {
83     uint32_t seq_nr;
84     uint16_t att_handle;
85     uint8_t  value;
86     uint8_t  device_index;
87 } persistent_ccc_entry_t;
88 
89 // global
90 static btstack_packet_callback_registration_t hci_event_callback_registration;
91 static btstack_packet_callback_registration_t sm_event_callback_registration;
92 static btstack_packet_handler_t               att_client_packet_handler = NULL;
93 static btstack_linked_list_t                  can_send_now_clients;
94 static btstack_linked_list_t                  service_handlers;
95 static btstack_context_callback_registration_t att_client_waiting_for_can_send_registration;
96 
97 static att_read_callback_t                    att_server_client_read_callback;
98 static att_write_callback_t                   att_server_client_write_callback;
99 
100 // track CCC 1-entry cache
101 // static att_server_t *    att_persistent_ccc_server;
102 // static hci_con_handle_t  att_persistent_ccc_con_handle;
103 
104 static att_server_t * att_server_for_handle(hci_con_handle_t con_handle){
105     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
106     if (!hci_connection) return NULL;
107     return &hci_connection->att_server;
108 }
109 
110 #ifdef ENABLE_LE_SIGNED_WRITE
111 static att_server_t * att_server_for_state(att_server_state_t state){
112     btstack_linked_list_iterator_t it;
113     hci_connections_get_iterator(&it);
114     while(btstack_linked_list_iterator_has_next(&it)){
115         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
116         att_server_t * att_server = &connection->att_server;
117         if (att_server->state == state) return att_server;
118     }
119     return NULL;
120 }
121 #endif
122 
123 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
124     if (!att_client_packet_handler) return;
125 
126     uint8_t event[7];
127     int pos = 0;
128     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
129     event[pos++] = sizeof(event) - 2;
130     event[pos++] = status;
131     little_endian_store_16(event, pos, client_handle);
132     pos += 2;
133     little_endian_store_16(event, pos, attribute_handle);
134     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
135 }
136 
137 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
138     if (!att_client_packet_handler) return;
139 
140     uint8_t event[6];
141     int pos = 0;
142     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
143     event[pos++] = sizeof(event) - 2;
144     little_endian_store_16(event, pos, con_handle);
145     pos += 2;
146     little_endian_store_16(event, pos, mtu);
147     att_dispatch_server_mtu_exchanged(con_handle, mtu);
148     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
149 }
150 
151 static void att_emit_can_send_now_event(void * context){
152     UNUSED(context);
153     if (!att_client_packet_handler) return;
154 
155     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
156     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
157 }
158 
159 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
160     void * context = btstack_run_loop_get_timer_context(ts);
161     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) context;
162     att_server_t * att_server = att_server_for_handle(con_handle);
163     if (!att_server) return;
164     uint16_t att_handle = att_server->value_indication_handle;
165     att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_server->connection.con_handle, att_handle);
166 }
167 
168 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
169 
170     UNUSED(channel); // ok: there is no channel
171     UNUSED(size);    // ok: handling own l2cap events
172 
173     att_server_t * att_server;
174     hci_con_handle_t con_handle;
175 
176     switch (packet_type) {
177 
178         case HCI_EVENT_PACKET:
179             switch (hci_event_packet_get_type(packet)) {
180 
181                 case HCI_EVENT_LE_META:
182                     switch (packet[2]) {
183                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
184                             con_handle = little_endian_read_16(packet, 4);
185                             att_server = att_server_for_handle(con_handle);
186                             if (!att_server) break;
187                         	// store connection info
188                         	att_server->peer_addr_type = packet[7];
189                             reverse_bd_addr(&packet[8], att_server->peer_address);
190                             att_server->connection.con_handle = con_handle;
191                             // reset connection properties
192                             att_server->state = ATT_SERVER_IDLE;
193                             att_server->connection.mtu = ATT_DEFAULT_MTU;
194                             att_server->connection.max_mtu = l2cap_max_le_mtu();
195                             if (att_server->connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){
196                                 att_server->connection.max_mtu = ATT_REQUEST_BUFFER_SIZE;
197                             }
198                             att_server->connection.encryption_key_size = 0;
199                             att_server->connection.authenticated = 0;
200 		                	att_server->connection.authorized = 0;
201                             // workaround: identity resolving can already be complete, at least store result
202                             att_server->ir_le_device_db_index = sm_le_device_index(con_handle);
203                             att_server->pairing_active = 0;
204                             break;
205 
206                         default:
207                             break;
208                     }
209                     break;
210 
211                 case HCI_EVENT_ENCRYPTION_CHANGE:
212                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
213                 	// check handle
214                     con_handle = little_endian_read_16(packet, 3);
215                     att_server = att_server_for_handle(con_handle);
216                     if (!att_server) break;
217                     att_server->connection.encryption_key_size = gap_encryption_key_size(con_handle);
218                     att_server->connection.authenticated = gap_authenticated(con_handle);
219                     if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE){
220                         // restore CCC values when encrypted
221                         if (hci_event_encryption_change_get_encryption_enabled(packet)){
222                             att_server_persistent_ccc_restore(att_server);
223                         }
224                     }
225                     att_run_for_context(att_server);
226                     break;
227 
228                 case HCI_EVENT_DISCONNECTION_COMPLETE:
229                     // check handle
230                     con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
231                     att_server = att_server_for_handle(con_handle);
232                     if (!att_server) break;
233                     att_clear_transaction_queue(&att_server->connection);
234                     att_server->connection.con_handle = 0;
235                     att_server->value_indication_handle = 0; // reset error state
236                     att_server->pairing_active = 0;
237                     att_server->state = ATT_SERVER_IDLE;
238                     break;
239 
240                 // Identity Resolving
241                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
242                     con_handle = sm_event_identity_resolving_started_get_handle(packet);
243                     att_server = att_server_for_handle(con_handle);
244                     if (!att_server) break;
245                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
246                     att_server->ir_lookup_active = 1;
247                     break;
248                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
249                     con_handle = sm_event_identity_created_get_handle(packet);
250                     att_server = att_server_for_handle(con_handle);
251                     if (!att_server) return;
252                     att_server->ir_lookup_active = 0;
253                     att_server->ir_le_device_db_index = sm_event_identity_resolving_succeeded_get_index(packet);
254                     log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED");
255                     att_run_for_context(att_server);
256                     break;
257                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
258                     con_handle = sm_event_identity_resolving_failed_get_handle(packet);
259                     att_server = att_server_for_handle(con_handle);
260                     if (!att_server) break;
261                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
262                     att_server->ir_lookup_active = 0;
263                     att_server->ir_le_device_db_index = -1;
264                     att_run_for_context(att_server);
265                     break;
266 
267                 // Pairing started - delete stored CCC values
268                 // - assumes pairing indicates either new device or re-pairing, in both cases there should be no stored CCC values
269                 // - assumes that all events have the con handle as the first field
270                 case SM_EVENT_JUST_WORKS_REQUEST:
271                 case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
272                 case SM_EVENT_PASSKEY_INPUT_NUMBER:
273                 case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
274                     con_handle = sm_event_just_works_request_get_handle(packet);
275                     att_server = att_server_for_handle(con_handle);
276                     if (!att_server) break;
277                     att_server->pairing_active = 1;
278                     log_info("SM Pairing started");
279                     if (att_server->ir_le_device_db_index < 0) break;
280                     att_server_persistent_ccc_clear(att_server);
281                     // index not valid anymore
282                     att_server->ir_le_device_db_index = -1;
283                     break;
284 
285                 // Bonding completed
286                 case SM_EVENT_IDENTITY_CREATED:
287                     con_handle = sm_event_identity_created_get_handle(packet);
288                     att_server = att_server_for_handle(con_handle);
289                     if (!att_server) return;
290                     att_server->pairing_active = 0;
291                     att_server->ir_le_device_db_index = sm_event_identity_created_get_index(packet);
292                     att_run_for_context(att_server);
293                     break;
294 
295                 // Pairing complete (with/without bonding=storing of pairing information)
296                 case SM_EVENT_PAIRING_COMPLETE:
297                     con_handle = sm_event_pairing_complete_get_handle(packet);
298                     att_server = att_server_for_handle(con_handle);
299                     if (!att_server) return;
300                     att_server->pairing_active = 0;
301                     att_run_for_context(att_server);
302                     break;
303 
304                 // Authorization
305                 case SM_EVENT_AUTHORIZATION_RESULT: {
306                     con_handle = sm_event_authorization_result_get_handle(packet);
307                     att_server = att_server_for_handle(con_handle);
308                     if (!att_server) break;
309                     att_server->connection.authorized = sm_event_authorization_result_get_authorization_result(packet);
310                     att_dispatch_server_request_can_send_now_event(con_handle);
311                 	break;
312                 }
313                 default:
314                     break;
315             }
316             break;
317         default:
318             break;
319     }
320 }
321 
322 #ifdef ENABLE_LE_SIGNED_WRITE
323 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
324 
325     att_server_t * att_server = att_server_for_state(ATT_SERVER_W4_SIGNED_WRITE_VALIDATION);
326     if (!att_server) return;
327 
328     uint8_t hash_flipped[8];
329     reverse_64(hash, hash_flipped);
330     if (memcmp(hash_flipped, &att_server->request_buffer[att_server->request_size-8], 8)){
331         log_info("ATT Signed Write, invalid signature");
332         att_server->state = ATT_SERVER_IDLE;
333         return;
334     }
335     log_info("ATT Signed Write, valid signature");
336 
337     // update sequence number
338     uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
339     le_device_db_remote_counter_set(att_server->ir_le_device_db_index, counter_packet+1);
340     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
341     att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
342 }
343 #endif
344 
345 // pre: att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
346 // pre: can send now
347 // returns: 1 if packet was sent
348 static int att_server_process_validated_request(att_server_t * att_server){
349 
350     l2cap_reserve_packet_buffer();
351     uint8_t * att_response_buffer = l2cap_get_outgoing_buffer();
352     uint16_t  att_response_size   = att_handle_request(&att_server->connection, att_server->request_buffer, att_server->request_size, att_response_buffer);
353 
354 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
355     if (att_response_size == ATT_READ_RESPONSE_PENDING){
356         // update state
357         att_server->state = ATT_SERVER_READ_RESPONSE_PENDING;
358 
359         // callback with handle ATT_READ_RESPONSE_PENDING
360         att_server_client_read_callback(att_server->connection.con_handle, ATT_READ_RESPONSE_PENDING, 0, NULL, 0);
361 
362         // free reserved buffer
363         l2cap_release_packet_buffer();
364         return 0;
365     }
366 #endif
367 
368     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
369     if ((att_response_size     >= 4)
370     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
371     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
372     && (att_server->connection.authenticated)){
373 
374         switch (gap_authorization_state(att_server->connection.con_handle)){
375             case AUTHORIZATION_UNKNOWN:
376                 l2cap_release_packet_buffer();
377                 sm_request_pairing(att_server->connection.con_handle);
378                 return 0;
379             case AUTHORIZATION_PENDING:
380                 l2cap_release_packet_buffer();
381                 return 0;
382             default:
383                 break;
384         }
385     }
386 
387     att_server->state = ATT_SERVER_IDLE;
388     if (att_response_size == 0) {
389         l2cap_release_packet_buffer();
390         return 0;
391     }
392 
393     l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size);
394 
395     // notify client about MTU exchange result
396     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
397         att_emit_mtu_event(att_server->connection.con_handle, att_server->connection.mtu);
398     }
399     return 1;
400 }
401 
402 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
403 int att_server_read_response_ready(hci_con_handle_t con_handle){
404     att_server_t * att_server = att_server_for_handle(con_handle);
405     if (!att_server)                                             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
406     if (att_server->state != ATT_SERVER_READ_RESPONSE_PENDING)   return ERROR_CODE_COMMAND_DISALLOWED;
407 
408     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
409     att_dispatch_server_request_can_send_now_event(con_handle);
410     return ERROR_CODE_SUCCESS;
411 }
412 #endif
413 
414 static void att_run_for_context(att_server_t * att_server){
415     switch (att_server->state){
416         case ATT_SERVER_REQUEST_RECEIVED:
417 
418             // wait until re-encryption as central is complete
419             if (gap_reconnect_security_setup_active(att_server->connection.con_handle)) break;
420 
421             // wait until pairing is complete
422             if (att_server->pairing_active) break;
423 
424 #ifdef ENABLE_LE_SIGNED_WRITE
425             if (att_server->request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
426                 log_info("ATT Signed Write!");
427                 if (!sm_cmac_ready()) {
428                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
429                     att_server->state = ATT_SERVER_IDLE;
430                     return;
431                 }
432                 if (att_server->request_size < (3 + 12)) {
433                     log_info("ATT Signed Write, request to short. Abort.");
434                     att_server->state = ATT_SERVER_IDLE;
435                     return;
436                 }
437                 if (att_server->ir_lookup_active){
438                     return;
439                 }
440                 if (att_server->ir_le_device_db_index < 0){
441                     log_info("ATT Signed Write, CSRK not available");
442                     att_server->state = ATT_SERVER_IDLE;
443                     return;
444                 }
445 
446                 // check counter
447                 uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
448                 uint32_t counter_db     = le_device_db_remote_counter_get(att_server->ir_le_device_db_index);
449                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
450                 if (counter_packet < counter_db){
451                     log_info("ATT Signed Write, db reports higher counter, abort");
452                     att_server->state = ATT_SERVER_IDLE;
453                     return;
454                 }
455 
456                 // signature is { sequence counter, secure hash }
457                 sm_key_t csrk;
458                 le_device_db_remote_csrk_get(att_server->ir_le_device_db_index, csrk);
459                 att_server->state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
460                 log_info("Orig Signature: ");
461                 log_info_hexdump( &att_server->request_buffer[att_server->request_size-8], 8);
462                 uint16_t attribute_handle = little_endian_read_16(att_server->request_buffer, 1);
463                 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);
464                 return;
465             }
466 #endif
467             // move on
468             att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
469             att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
470             break;
471 
472         default:
473             break;
474     }
475 }
476 
477 static void att_server_handle_can_send_now(void){
478 
479     // NOTE: we get l2cap fixed channel instead of con_handle
480 
481     btstack_linked_list_iterator_t it;
482     hci_connections_get_iterator(&it);
483     while(btstack_linked_list_iterator_has_next(&it)){
484         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
485         att_server_t * att_server = &connection->att_server;
486         if (att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED){
487             int sent = att_server_process_validated_request(att_server);
488             if (sent && !btstack_linked_list_empty(&can_send_now_clients)){
489                 att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
490                 return;
491             }
492         }
493     }
494 
495     while (!btstack_linked_list_empty(&can_send_now_clients)){
496         // handle first client
497         btstack_context_callback_registration_t * client = (btstack_context_callback_registration_t*) can_send_now_clients;
498         hci_con_handle_t con_handle = (uintptr_t) client->context;
499         btstack_linked_list_remove(&can_send_now_clients, (btstack_linked_item_t *) client);
500         client->callback(client->context);
501 
502         // request again if needed
503         if (!att_dispatch_server_can_send_now(con_handle)){
504             if (!btstack_linked_list_empty(&can_send_now_clients)){
505                 att_dispatch_server_request_can_send_now_event(con_handle);
506             }
507             return;
508         }
509     }
510 }
511 
512 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
513 
514     att_server_t * att_server;
515 
516     switch (packet_type){
517 
518         case HCI_EVENT_PACKET:
519             switch (packet[0]){
520                 case L2CAP_EVENT_CAN_SEND_NOW:
521                     att_server_handle_can_send_now();
522                     break;
523                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
524                     // GATT client has negotiated the mtu for this connection
525                     att_server = att_server_for_handle(handle);
526                     if (!att_server) break;
527                     att_server->connection.mtu = little_endian_read_16(packet, 4);
528                     break;
529                 default:
530                     break;
531             }
532             break;
533 
534         case ATT_DATA_PACKET:
535             log_debug("ATT Packet, handle 0x%04x", handle);
536             att_server = att_server_for_handle(handle);
537             if (!att_server) break;
538 
539             // handle value indication confirms
540             if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_server->value_indication_handle){
541                 btstack_run_loop_remove_timer(&att_server->value_indication_timer);
542                 uint16_t att_handle = att_server->value_indication_handle;
543                 att_server->value_indication_handle = 0;
544                 att_handle_value_indication_notify_client(0, att_server->connection.con_handle, att_handle);
545                 return;
546             }
547 
548             // directly process command
549             // note: signed write cannot be handled directly as authentication needs to be verified
550             if (packet[0] == ATT_WRITE_COMMAND){
551                 att_handle_request(&att_server->connection, packet, size, 0);
552                 return;
553             }
554 
555             // check size
556             if (size > sizeof(att_server->request_buffer)) {
557                 log_info("att_packet_handler: dropping att pdu 0x%02x as size %u > att_server->request_buffer %u", packet[0], size, (int) sizeof(att_server->request_buffer));
558                 return;
559             }
560 
561             // last request still in processing?
562             if (att_server->state != ATT_SERVER_IDLE){
563                 log_info("att_packet_handler: skipping att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state);
564                 return;
565             }
566 
567             // store request
568             att_server->state = ATT_SERVER_REQUEST_RECEIVED;
569             att_server->request_size = size;
570             memcpy(att_server->request_buffer, packet, size);
571 
572             att_run_for_context(att_server);
573             break;
574     }
575 }
576 
577 // ---------------------
578 // persistent CCC writes
579 static uint32_t att_server_persistent_ccc_tag_for_index(uint8_t index){
580     return 'B' << 24 | 'T' << 16 | 'C' << 8 | index;
581 }
582 
583 static void att_server_persistent_ccc_write(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t value){
584     // lookup att_server instance
585     att_server_t * att_server = att_server_for_handle(con_handle);
586     if (!att_server) return;
587     int le_device_index = att_server->ir_le_device_db_index;
588     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);
589 
590     // check if bonded
591     if (le_device_index < 0) return;
592 
593     // get btstack_tlv
594     const btstack_tlv_t * tlv_impl = NULL;
595     void * tlv_context;
596     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
597     if (!tlv_impl) return;
598 
599     // update ccc tag
600     int index;
601     uint32_t highest_seq_nr = 0;
602     uint32_t lowest_seq_nr = 0;
603     uint32_t tag_for_lowest_seq_nr = 0;
604     uint32_t tag_for_empty = 0;
605     persistent_ccc_entry_t entry;
606     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
607         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
608         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
609 
610         // empty/invalid tag
611         if (len != sizeof(persistent_ccc_entry_t)){
612             tag_for_empty = tag;
613             continue;
614         }
615         // update highest seq nr
616         if (entry.seq_nr > highest_seq_nr){
617             highest_seq_nr = entry.seq_nr;
618         }
619         // find entry with lowest seq nr
620         if ((tag_for_lowest_seq_nr == 0) || (entry.seq_nr < lowest_seq_nr)){
621             tag_for_lowest_seq_nr = tag;
622             lowest_seq_nr = entry.seq_nr;
623         }
624 
625         if (entry.device_index != le_device_index) continue;
626         if (entry.att_handle   != att_handle)      continue;
627 
628         // found matching entry
629         if (value){
630             // update
631             if (entry.value == value) {
632                 log_info("CCC Index %u: Up-to-date", index);
633                 return;
634             }
635             entry.value = value;
636             entry.seq_nr = highest_seq_nr + 1;
637             log_info("CCC Index %u: Store", index);
638             tlv_impl->store_tag(tlv_context, tag, (const uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
639         } else {
640             // delete
641             log_info("CCC Index %u: Delete", index);
642             tlv_impl->delete_tag(tlv_context, tag);
643         }
644         return;
645     }
646 
647     log_info("tag_for_empy %"PRIx32", tag_for_lowest_seq_nr %"PRIx32, tag_for_empty, tag_for_lowest_seq_nr);
648 
649     if (value == 0){
650         // done
651         return;
652     }
653 
654     uint32_t tag_to_use = 0;
655     if (tag_for_empty){
656         tag_to_use = tag_for_empty;
657     } else if (tag_for_lowest_seq_nr){
658         tag_to_use = tag_for_lowest_seq_nr;
659     } else {
660         // should not happen
661         return;
662     }
663     // store ccc tag
664     entry.seq_nr       = highest_seq_nr + 1;
665     entry.device_index = le_device_index;
666     entry.att_handle   = att_handle;
667     entry.value        = value;
668     tlv_impl->store_tag(tlv_context, tag_to_use, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
669 }
670 
671 static void att_server_persistent_ccc_clear(att_server_t * att_server){
672     if (!att_server) return;
673     int le_device_index = att_server->ir_le_device_db_index;
674     log_info("Clear CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
675     // check if bonded
676     if (le_device_index < 0) return;
677     // get btstack_tlv
678     const btstack_tlv_t * tlv_impl = NULL;
679     void * tlv_context;
680     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
681     if (!tlv_impl) return;
682     // get all ccc tag
683     int index;
684     persistent_ccc_entry_t entry;
685     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
686         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
687         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
688         if (len != sizeof(persistent_ccc_entry_t)) continue;
689         if (entry.device_index != le_device_index) continue;
690         // delete entry
691         log_info("CCC Index %u: Delete", index);
692         tlv_impl->delete_tag(tlv_context, tag);
693     }
694 }
695 
696 static void att_server_persistent_ccc_restore(att_server_t * att_server){
697     if (!att_server) return;
698     int le_device_index = att_server->ir_le_device_db_index;
699     log_info("Restore CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
700     // check if bonded
701     if (le_device_index < 0) return;
702     // get btstack_tlv
703     const btstack_tlv_t * tlv_impl = NULL;
704     void * tlv_context;
705     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
706     if (!tlv_impl) return;
707     // get all ccc tag
708     int index;
709     persistent_ccc_entry_t entry;
710     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
711         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
712         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
713         if (len != sizeof(persistent_ccc_entry_t)) continue;
714         if (entry.device_index != le_device_index) continue;
715         // simulate write callback
716         uint16_t attribute_handle = entry.att_handle;
717         uint8_t  value[2];
718         little_endian_store_16(value, 0, entry.value);
719         att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
720         if (!callback) continue;
721         log_info("CCC Index %u: Set Attribute handle 0x%04x to value 0x%04x", index, attribute_handle, entry.value );
722         (*callback)(att_server->connection.con_handle, attribute_handle, ATT_TRANSACTION_MODE_NONE, 0, value, sizeof(value));
723     }
724 }
725 
726 // persistent CCC writes
727 // ---------------------
728 
729 // gatt service management
730 static att_service_handler_t * att_service_handler_for_handle(uint16_t handle){
731     btstack_linked_list_iterator_t it;
732     btstack_linked_list_iterator_init(&it, &service_handlers);
733     while (btstack_linked_list_iterator_has_next(&it)){
734         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
735         if (handler->start_handle > handle) continue;
736         if (handler->end_handle   < handle) continue;
737         return handler;
738     }
739     return NULL;
740 }
741 static att_read_callback_t att_server_read_callback_for_handle(uint16_t handle){
742     att_service_handler_t * handler = att_service_handler_for_handle(handle);
743     if (handler) return handler->read_callback;
744     return att_server_client_read_callback;
745 }
746 
747 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle){
748     att_service_handler_t * handler = att_service_handler_for_handle(handle);
749     if (handler) return handler->write_callback;
750     return att_server_client_write_callback;
751 }
752 
753 static void att_notify_write_callbacks(hci_con_handle_t con_handle, uint16_t transaction_mode){
754     // notify all callbacks
755     btstack_linked_list_iterator_t it;
756     btstack_linked_list_iterator_init(&it, &service_handlers);
757     while (btstack_linked_list_iterator_has_next(&it)){
758         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
759         if (!handler->write_callback) continue;
760         (*handler->write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
761     }
762     if (!att_server_client_write_callback) return;
763     (*att_server_client_write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
764 }
765 
766 // returns first reported error or 0
767 static uint8_t att_validate_prepared_write(hci_con_handle_t con_handle){
768     btstack_linked_list_iterator_t it;
769     btstack_linked_list_iterator_init(&it, &service_handlers);
770     while (btstack_linked_list_iterator_has_next(&it)){
771         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
772         if (!handler->write_callback) continue;
773         uint8_t error_code = (*handler->write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
774         if (error_code) return error_code;
775     }
776     if (!att_server_client_write_callback) return 0;
777     return (*att_server_client_write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
778 }
779 
780 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){
781     att_read_callback_t callback = att_server_read_callback_for_handle(attribute_handle);
782     if (!callback) return 0;
783     return (*callback)(con_handle, attribute_handle, offset, buffer, buffer_size);
784 }
785 
786 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){
787     switch (transaction_mode){
788         case ATT_TRANSACTION_MODE_VALIDATE:
789             return att_validate_prepared_write(con_handle);
790         case ATT_TRANSACTION_MODE_EXECUTE:
791         case ATT_TRANSACTION_MODE_CANCEL:
792             att_notify_write_callbacks(con_handle, transaction_mode);
793             return 0;
794         default:
795             break;
796     }
797 
798     // track CCC writes
799     if (att_is_persistent_ccc(attribute_handle) && offset == 0 && buffer_size == 2){
800         att_server_persistent_ccc_write(con_handle, attribute_handle, little_endian_read_16(buffer, 0));
801     }
802 
803     att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
804     if (!callback) return 0;
805     return (*callback)(con_handle, attribute_handle, transaction_mode, offset, buffer, buffer_size);
806 }
807 
808 /**
809  * @brief register read/write callbacks for specific handle range
810  * @param att_service_handler_t
811  */
812 void att_server_register_service_handler(att_service_handler_t * handler){
813     if (att_service_handler_for_handle(handler->start_handle) ||
814         att_service_handler_for_handle(handler->end_handle)){
815         log_error("handler for range 0x%04x-0x%04x already registered", handler->start_handle, handler->end_handle);
816         return;
817     }
818     btstack_linked_list_add(&service_handlers, (btstack_linked_item_t*) handler);
819 }
820 
821 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
822 
823     // store callbacks
824     att_server_client_read_callback  = read_callback;
825     att_server_client_write_callback = write_callback;
826 
827     // register for HCI Events
828     hci_event_callback_registration.callback = &att_event_packet_handler;
829     hci_add_event_handler(&hci_event_callback_registration);
830 
831     // register for SM events
832     sm_event_callback_registration.callback = &att_event_packet_handler;
833     sm_add_event_handler(&sm_event_callback_registration);
834 
835     // and L2CAP ATT Server PDUs
836     att_dispatch_register_server(att_packet_handler);
837 
838     att_set_db(db);
839     att_set_read_callback(att_server_read_callback);
840     att_set_write_callback(att_server_write_callback);
841 
842 }
843 
844 void att_server_register_packet_handler(btstack_packet_handler_t handler){
845     att_client_packet_handler = handler;
846 }
847 
848 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
849 	return att_dispatch_server_can_send_now(con_handle);
850 }
851 
852 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
853     log_debug("att_server_request_can_send_now_event 0x%04x", con_handle);
854     att_client_waiting_for_can_send_registration.callback = &att_emit_can_send_now_event;
855     att_server_register_can_send_now_callback(&att_client_waiting_for_can_send_registration, con_handle);
856 }
857 
858 void att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
859     // check if valid con handle
860     if (gap_get_connection_type(con_handle) != GAP_CONNECTION_LE) return;
861     btstack_linked_list_add_tail(&can_send_now_clients, (btstack_linked_item_t*) callback_registration);
862     att_dispatch_server_request_can_send_now_event(con_handle);
863 }
864 
865 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
866     att_server_t * att_server = att_server_for_handle(con_handle);
867     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
868 
869     if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
870 
871     l2cap_reserve_packet_buffer();
872     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
873     uint16_t size = att_prepare_handle_value_notification(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
874 	return l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
875 }
876 
877 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
878     att_server_t * att_server = att_server_for_handle(con_handle);
879     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
880 
881     if (att_server->value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PROGRESS;
882     if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
883 
884     // track indication
885     att_server->value_indication_handle = attribute_handle;
886     btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout);
887     btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
888     btstack_run_loop_add_timer(&att_server->value_indication_timer);
889 
890     l2cap_reserve_packet_buffer();
891     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
892     uint16_t size = att_prepare_handle_value_indication(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
893 	l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
894     return 0;
895 }
896