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