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