xref: /btstack/src/ble/att_server.c (revision cb140a1e11895355f5dbf99309e21ec1785da0dd)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "att_server.c"
39 
40 
41 //
42 // ATT Server Globals
43 //
44 
45 #include <stdint.h>
46 #include <string.h>
47 #include <inttypes.h>
48 
49 #include "btstack_config.h"
50 
51 #include "ble/att_dispatch.h"
52 #include "ble/att_db.h"
53 #include "ble/att_server.h"
54 #include "ble/core.h"
55 #include "ble/le_device_db.h"
56 #include "ble/sm.h"
57 #include "bluetooth_psm.h"
58 #include "btstack_debug.h"
59 #include "btstack_event.h"
60 #include "btstack_memory.h"
61 #include "btstack_run_loop.h"
62 #include "gap.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 #include "bluetooth_psm.h"
69 
70 #endif
71 
72 #ifdef ENABLE_TESTING_SUPPORT
73 #include <stdio.h>
74 #endif
75 
76 #ifndef NVN_NUM_GATT_SERVER_CCC
77 #define NVN_NUM_GATT_SERVER_CCC 20
78 #endif
79 
80 #define ATT_SERVICE_FLAGS_DELAYED_RESPONSE (1u<<0u)
81 
82 static void att_run_for_context(att_server_t * att_server, att_connection_t * att_connection);
83 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle);
84 static btstack_packet_handler_t att_server_packet_handler_for_handle(uint16_t handle);
85 static void att_server_handle_can_send_now(void);
86 static void att_server_persistent_ccc_restore(att_server_t * att_server, att_connection_t * att_connection);
87 static void att_server_persistent_ccc_clear(att_server_t * att_server);
88 static void att_server_handle_att_pdu(att_server_t * att_server, att_connection_t * att_connection, uint8_t * packet, uint16_t size);
89 
90 typedef enum {
91     ATT_SERVER_RUN_PHASE_1_REQUESTS = 0,
92     ATT_SERVER_RUN_PHASE_2_INDICATIONS,
93     ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS,
94 } att_server_run_phase_t;
95 
96 //
97 typedef struct {
98     uint32_t seq_nr;
99     uint16_t att_handle;
100     uint8_t  value;
101     uint8_t  device_index;
102 } persistent_ccc_entry_t;
103 
104 // global
105 static btstack_packet_callback_registration_t hci_event_callback_registration;
106 static btstack_packet_callback_registration_t sm_event_callback_registration;
107 static btstack_packet_handler_t               att_client_packet_handler;
108 static btstack_linked_list_t                  service_handlers;
109 static btstack_context_callback_registration_t att_client_waiting_for_can_send_registration;
110 
111 static att_read_callback_t                    att_server_client_read_callback;
112 static att_write_callback_t                   att_server_client_write_callback;
113 
114 // round robin
115 static hci_con_handle_t att_server_last_can_send_now = HCI_CON_HANDLE_INVALID;
116 
117 static uint8_t att_server_flags;
118 
119 #ifdef ENABLE_GATT_OVER_EATT
120 static att_server_eatt_bearer_t * att_server_eatt_bearer_for_con_handle(hci_con_handle_t con_handle);
121 static btstack_linked_list_t att_server_eatt_bearer_pool;
122 static btstack_linked_list_t att_server_eatt_bearer_active;
123 #endif
124 
125 #ifdef ENABLE_LE_SIGNED_WRITE
att_server_connections_for_state(att_server_state_t state,att_server_t ** att_server_out,att_connection_t ** att_connection_out)126 static bool att_server_connections_for_state(att_server_state_t state, att_server_t ** att_server_out, att_connection_t ** att_connection_out){
127     btstack_linked_list_iterator_t it;
128     hci_connections_get_iterator(&it);
129     while(btstack_linked_list_iterator_has_next(&it)){
130         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
131         if (hci_connection->att_server.state == state) {
132             *att_server_out     = &hci_connection->att_server;
133             *att_connection_out = &hci_connection->att_connection;
134             return true;
135         }
136     }
137 
138 #ifdef ENABLE_GATT_OVER_EATT
139     btstack_linked_list_iterator_init(&it, &att_server_eatt_bearer_active);
140     while(btstack_linked_list_iterator_has_next(&it)){
141         att_server_eatt_bearer_t * eatt_bearer = (att_server_eatt_bearer_t *) btstack_linked_list_iterator_next(&it);
142         if (eatt_bearer->att_server.state == state) {
143             *att_server_out     = &eatt_bearer->att_server;
144             *att_connection_out = &eatt_bearer->att_connection;
145             return true;
146         }
147     }
148 #endif
149 
150     return false;
151 }
152 #endif
153 
att_server_request_can_send_now(att_server_t * att_server,att_connection_t * att_connection)154 static void att_server_request_can_send_now(att_server_t * att_server, att_connection_t * att_connection ){
155     switch (att_server->bearer_type){
156         case ATT_BEARER_UNENHANCED_LE:
157 #ifdef ENABLE_GATT_OVER_CLASSIC
158         case ATT_BEARER_UNENHANCED_CLASSIC:
159             /* fall through */
160 #endif
161             att_dispatch_server_request_can_send_now_event(att_connection->con_handle);
162             break;
163 #ifdef ENABLE_GATT_OVER_EATT
164         case ATT_BEARER_ENHANCED_LE:
165             l2cap_request_can_send_now_event(att_server->l2cap_cid);
166             break;
167 #endif
168         default:
169             btstack_unreachable();
170             break;
171     }
172 }
173 
att_server_can_send_packet(att_server_t * att_server,att_connection_t * att_connection)174 static bool att_server_can_send_packet(att_server_t * att_server, att_connection_t * att_connection){
175     switch (att_server->bearer_type) {
176         case ATT_BEARER_UNENHANCED_LE:
177 #ifdef ENABLE_GATT_OVER_CLASSIC
178         case ATT_BEARER_UNENHANCED_CLASSIC:
179             /* fall through */
180 #endif
181             return att_dispatch_server_can_send_now(att_connection->con_handle);
182 #ifdef ENABLE_GATT_OVER_EATT
183         case ATT_BEARER_ENHANCED_LE:
184             return l2cap_can_send_packet_now(att_server->l2cap_cid);
185 #endif
186         default:
187             btstack_unreachable();
188             break;
189     }
190     return false;
191 }
192 
att_handle_value_indication_notify_client(uint8_t status,uint16_t client_handle,uint16_t attribute_handle)193 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
194     btstack_packet_handler_t packet_handler = att_server_packet_handler_for_handle(attribute_handle);
195     if (!packet_handler) return;
196 
197     uint8_t event[7];
198     int pos = 0;
199     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
200     event[pos++] = sizeof(event) - 2u;
201     event[pos++] = status;
202     little_endian_store_16(event, pos, client_handle);
203     pos += 2;
204     little_endian_store_16(event, pos, attribute_handle);
205     (*packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
206 }
207 
att_emit_event_to_all(const uint8_t * event,uint16_t size)208 static void att_emit_event_to_all(const uint8_t * event, uint16_t size){
209     // dispatch to app level handler
210     if (att_client_packet_handler != NULL){
211         (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t*) event, size);
212     }
213 
214     // dispatch to service handlers
215     btstack_linked_list_iterator_t it;
216     btstack_linked_list_iterator_init(&it, &service_handlers);
217     while (btstack_linked_list_iterator_has_next(&it)){
218         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
219         if (!handler->packet_handler) continue;
220         (*handler->packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t*) event, size);
221     }
222 }
223 
att_emit_mtu_event(hci_con_handle_t con_handle,uint16_t mtu)224 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
225     uint8_t event[6];
226     int pos = 0;
227     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
228     event[pos++] = sizeof(event) - 2u;
229     little_endian_store_16(event, pos, con_handle);
230     pos += 2;
231     little_endian_store_16(event, pos, mtu);
232 
233     // also dispatch to GATT Clients
234     att_dispatch_server_mtu_exchanged(con_handle, mtu);
235 
236     // dispatch to app level handler and service handlers
237     att_emit_event_to_all(&event[0], sizeof(event));
238 }
239 
att_emit_can_send_now_event(void * context)240 static void att_emit_can_send_now_event(void * context){
241     UNUSED(context);
242     if (!att_client_packet_handler) return;
243 
244     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
245     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
246 }
247 
att_emit_connected_event(att_server_t * att_server,att_connection_t * att_connection)248 static void att_emit_connected_event(att_server_t * att_server,  att_connection_t * att_connection){
249     uint8_t event[11];
250     int pos = 0;
251     event[pos++] = ATT_EVENT_CONNECTED;
252     event[pos++] = sizeof(event) - 2u;
253     event[pos++] = att_server->peer_addr_type;
254     reverse_bd_addr(att_server->peer_address, &event[pos]);
255     pos += 6;
256     little_endian_store_16(event, pos, att_connection->con_handle);
257     pos += 2;
258 
259     // dispatch to app level handler and service handlers
260     att_emit_event_to_all(&event[0], sizeof(event));
261 }
262 
263 
att_emit_disconnected_event(uint16_t con_handle)264 static void att_emit_disconnected_event(uint16_t con_handle){
265     uint8_t event[4];
266     int pos = 0;
267     event[pos++] = ATT_EVENT_DISCONNECTED;
268     event[pos++] = sizeof(event) - 2u;
269     little_endian_store_16(event, pos, con_handle);
270     pos += 2;
271 
272     // dispatch to app level handler and service handlers
273     att_emit_event_to_all(&event[0], sizeof(event));
274 }
275 
att_handle_value_indication_timeout(btstack_timer_source_t * ts)276 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
277     void * context = btstack_run_loop_get_timer_context(ts);
278     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) context;
279     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
280     if (!hci_connection) return;
281     // @note: after a transaction timeout, no more requests shall be sent over this ATT Bearer
282     // (that's why we don't reset the value_indication_handle)
283     att_server_t * att_server = &hci_connection->att_server;
284     uint16_t att_handle = att_server->value_indication_handle;
285     att_connection_t * att_connection = &hci_connection->att_connection;
286     att_handle_value_indication_notify_client((uint8_t)ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_connection->con_handle, att_handle);
287 }
288 
att_server_event_packet_handler(uint8_t packet_type,uint16_t channel,uint8_t * packet,uint16_t size)289 static void att_server_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
290 
291     UNUSED(channel); // ok: there is no channel
292     UNUSED(size);    // ok: handling own l2cap events
293 
294     att_server_t * att_server;
295     att_connection_t * att_connection;
296     hci_con_handle_t con_handle;
297     hci_connection_t * hci_connection;
298 
299     switch (packet_type) {
300 
301         case HCI_EVENT_PACKET:
302             switch (hci_event_packet_get_type(packet)) {
303                 case HCI_EVENT_META_GAP:
304                     switch (hci_event_gap_meta_get_subevent_code(packet)) {
305                         case GAP_SUBEVENT_LE_CONNECTION_COMPLETE:
306                             con_handle = gap_subevent_le_connection_complete_get_connection_handle(packet);
307                             hci_connection = hci_connection_for_handle(con_handle);
308                             if (!hci_connection) break;
309                             att_server = &hci_connection->att_server;
310                         	// store connection info
311                         	att_server->peer_addr_type = gap_subevent_le_connection_complete_get_peer_address_type(packet);
312                             gap_subevent_le_connection_complete_get_peer_address(packet, att_server->peer_address);
313                             att_connection = &hci_connection->att_connection;
314                             att_connection->con_handle = con_handle;
315                             // reset connection properties
316                             att_server->state = ATT_SERVER_IDLE;
317                             att_server->bearer_type = ATT_BEARER_UNENHANCED_LE;
318                             att_connection->mtu = ATT_DEFAULT_MTU;
319                             att_connection->max_mtu = l2cap_max_le_mtu();
320                             if (att_connection->max_mtu > ATT_REQUEST_BUFFER_SIZE){
321                                 att_connection->max_mtu = ATT_REQUEST_BUFFER_SIZE;
322                             }
323                             att_connection->encryption_key_size = 0u;
324                             att_connection->authenticated = 0u;
325 		                	att_connection->authorized = 0u;
326                             // workaround: identity resolving can already be complete, at least store result
327                             att_server->ir_le_device_db_index = sm_le_device_index(con_handle);
328                             att_server->ir_lookup_active = false;
329                             att_server->pairing_active = false;
330                             // notify all - new
331                             att_emit_connected_event(att_server, att_connection);
332                             break;
333                         default:
334                             break;
335                     }
336                     break;
337 
338                 case HCI_EVENT_LE_META:
339                     switch (hci_event_le_meta_get_subevent_code(packet)) {
340                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
341                             // forward LE Connection Complete event to keep backward compatibility
342                             // deprecated: please register hci handler with hci_add_event_handler or handle ATT_EVENT_CONNECTED
343                             att_emit_event_to_all(packet, size);
344                             break;
345                         default:
346                             break;
347                     }
348                     break;
349 
350                 case HCI_EVENT_ENCRYPTION_CHANGE:
351                 case HCI_EVENT_ENCRYPTION_CHANGE_V2:
352                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
353                 	// check handle
354                     con_handle = little_endian_read_16(packet, 3);
355                     hci_connection = hci_connection_for_handle(con_handle);
356                     if (!hci_connection) break;
357                     if (gap_get_connection_type(con_handle) != GAP_CONNECTION_LE) break;
358                     // update security params
359                     att_server = &hci_connection->att_server;
360                     att_connection = &hci_connection->att_connection;
361                     att_connection->encryption_key_size = gap_encryption_key_size(con_handle);
362                     att_connection->authenticated = gap_authenticated(con_handle) ? 1 : 0;
363                     att_connection->secure_connection = gap_secure_connection(con_handle) ? 1 : 0;
364                     log_info("encrypted key size %u, authenticated %u, secure connection %u",
365                         att_connection->encryption_key_size, att_connection->authenticated, att_connection->secure_connection);
366                     if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE){
367                         // restore CCC values when encrypted for LE Connections
368                         if (hci_event_encryption_change_get_encryption_enabled(packet) != 0u){
369                             att_server_persistent_ccc_restore(att_server, att_connection);
370                         }
371                     }
372                     att_run_for_context(att_server, att_connection);
373                     break;
374 
375                 case HCI_EVENT_DISCONNECTION_COMPLETE:
376                     // check handle
377                     con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
378                     hci_connection = hci_connection_for_handle(con_handle);
379                     if (!hci_connection) break;
380                     att_server = &hci_connection->att_server;
381                     att_connection = &hci_connection->att_connection;
382                     att_clear_transaction_queue(att_connection);
383                     att_connection->con_handle = 0;
384                     att_server->pairing_active = false;
385                     att_server->state = ATT_SERVER_IDLE;
386                     if (att_server->value_indication_handle != 0u){
387                         btstack_run_loop_remove_timer(&att_server->value_indication_timer);
388                         uint16_t att_handle = att_server->value_indication_handle;
389                         att_server->value_indication_handle = 0u; // reset error state
390                         att_handle_value_indication_notify_client((uint8_t)ATT_HANDLE_VALUE_INDICATION_DISCONNECT, att_connection->con_handle, att_handle);
391                     }
392                     // notify all - new
393                     att_emit_disconnected_event(con_handle);
394                     // notify all - old
395                     att_emit_event_to_all(packet, size);
396                     break;
397 
398                 // Identity Resolving
399                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
400                     con_handle = sm_event_identity_resolving_started_get_handle(packet);
401                     hci_connection = hci_connection_for_handle(con_handle);
402                     if (!hci_connection) break;
403                     att_server = &hci_connection->att_server;
404                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
405                     att_server->ir_lookup_active = true;
406                     break;
407                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
408                     con_handle = sm_event_identity_created_get_handle(packet);
409                     hci_connection = hci_connection_for_handle(con_handle);
410                     if (!hci_connection) return;
411                     att_connection = &hci_connection->att_connection;
412                     att_server = &hci_connection->att_server;
413                     att_server->ir_lookup_active = false;
414                     att_server->ir_le_device_db_index = sm_event_identity_resolving_succeeded_get_index(packet);
415                     log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED");
416                     att_run_for_context(att_server, att_connection);
417                     break;
418                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
419                     con_handle = sm_event_identity_resolving_failed_get_handle(packet);
420                     hci_connection = hci_connection_for_handle(con_handle);
421                     if (!hci_connection) break;
422                     att_connection = &hci_connection->att_connection;
423                     att_server = &hci_connection->att_server;
424                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
425                     att_server->ir_lookup_active = false;
426                     att_server->ir_le_device_db_index = -1;
427                     att_run_for_context(att_server, att_connection);
428                     break;
429 
430                 // Pairing started - delete stored CCC values
431                 // - assumes pairing indicates either new device or re-pairing, in both cases there should be no stored CCC values
432                 // - assumes that all events have the con handle as the first field
433                 case SM_EVENT_JUST_WORKS_REQUEST:
434                 case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
435                 case SM_EVENT_PASSKEY_INPUT_NUMBER:
436                 case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
437                     con_handle = sm_event_just_works_request_get_handle(packet);
438                     hci_connection = hci_connection_for_handle(con_handle);
439                     if (!hci_connection) break;
440                     att_server = &hci_connection->att_server;
441                     log_info("SM Pairing started");
442                     att_server->pairing_active = true;
443                     if (att_server->ir_le_device_db_index < 0) break;
444                     att_server_persistent_ccc_clear(att_server);
445                     // index not valid anymore
446                     att_server->ir_le_device_db_index = -1;
447                     break;
448 
449                 // Bonding completed
450                 case SM_EVENT_IDENTITY_CREATED:
451                     con_handle = sm_event_identity_created_get_handle(packet);
452                     hci_connection = hci_connection_for_handle(con_handle);
453                     if (!hci_connection) return;
454                     att_connection = &hci_connection->att_connection;
455                     att_server = &hci_connection->att_server;
456                     att_server->pairing_active = false;
457                     att_server->ir_le_device_db_index = sm_event_identity_created_get_index(packet);
458                     att_run_for_context(att_server, att_connection);
459                     break;
460 
461                 // Pairing complete (with/without bonding=storing of pairing information)
462                 case SM_EVENT_PAIRING_COMPLETE:
463                     con_handle = sm_event_pairing_complete_get_handle(packet);
464                     hci_connection = hci_connection_for_handle(con_handle);
465                     if (!hci_connection) return;
466                     att_connection = &hci_connection->att_connection;
467                     att_server = &hci_connection->att_server;
468                     att_server->pairing_active = false;
469                     att_run_for_context(att_server, att_connection);
470                     break;
471 
472                 // Authorization
473                 case SM_EVENT_AUTHORIZATION_RESULT: {
474                     con_handle = sm_event_authorization_result_get_handle(packet);
475                     hci_connection = hci_connection_for_handle(con_handle);
476                     if (!hci_connection) break;
477                     att_connection = &hci_connection->att_connection;
478                     att_server = &hci_connection->att_server;
479                     att_connection->authorized = sm_event_authorization_result_get_authorization_result(packet);
480                     att_server_request_can_send_now(att_server, att_connection);
481                 	break;
482                 }
483                 default:
484                     break;
485             }
486             break;
487         default:
488             break;
489     }
490 }
491 
492 static uint8_t
att_server_send_prepared(const att_server_t * att_server,const att_connection_t * att_connection,uint8_t * buffer,uint16_t size)493 att_server_send_prepared(const att_server_t *att_server, const att_connection_t *att_connection, uint8_t *buffer,
494                          uint16_t size) {
495     UNUSED(buffer);
496     uint8_t status = ERROR_CODE_SUCCESS;
497     switch (att_server->bearer_type) {
498         case ATT_BEARER_UNENHANCED_LE:
499             status = l2cap_send_prepared_connectionless(att_connection->con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
500             break;
501 #ifdef ENABLE_GATT_OVER_CLASSIC
502         case ATT_BEARER_UNENHANCED_CLASSIC:
503             status = l2cap_send_prepared(att_server->l2cap_cid, size);
504             break;
505 #endif
506 #ifdef ENABLE_GATT_OVER_EATT
507         case ATT_BEARER_ENHANCED_LE:
508             btstack_assert(buffer != NULL);
509             status = l2cap_send(att_server->l2cap_cid, buffer, size);
510             break;
511 #endif
512         default:
513             btstack_unreachable();
514             break;
515     }
516     return status;
517 }
518 
519 #ifdef ENABLE_LE_SIGNED_WRITE
att_signed_write_handle_cmac_result(uint8_t hash[8])520 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
521     att_server_t * att_server = NULL;
522     att_connection_t * att_connection = NULL;
523     bool found = att_server_connections_for_state(ATT_SERVER_W4_SIGNED_WRITE_VALIDATION, &att_server, &att_connection);
524 
525     if (found == false){
526         return;
527     }
528 
529     uint8_t hash_flipped[8];
530     reverse_64(hash, hash_flipped);
531     if (memcmp(hash_flipped, &att_server->request_buffer[att_server->request_size-8], 8) != 0){
532         log_info("ATT Signed Write, invalid signature");
533 #ifdef ENABLE_TESTING_SUPPORT
534         printf("ATT Signed Write, invalid signature\n");
535 #endif
536         att_server->state = ATT_SERVER_IDLE;
537         return;
538     }
539     log_info("ATT Signed Write, valid signature");
540 #ifdef ENABLE_TESTING_SUPPORT
541     printf("ATT Signed Write, valid signature\n");
542 #endif
543 
544     // update sequence number
545     uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
546     le_device_db_remote_counter_set(att_server->ir_le_device_db_index, counter_packet+1);
547     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
548     att_server_request_can_send_now(att_server, att_connection);
549 }
550 #endif
551 
552 #ifdef ENABLE_ATT_DELAYED_RESPONSE
att_server_handle_response_pending(att_server_t * att_server,const att_connection_t * att_connection,const uint8_t * eatt_buffer,uint16_t att_response_size)553 static void att_server_handle_response_pending(att_server_t *att_server, const att_connection_t *att_connection,
554                                                const uint8_t *eatt_buffer,
555                                                uint16_t att_response_size) {
556     // update state
557     att_server->state = ATT_SERVER_RESPONSE_PENDING;
558 
559     // callback with handle ATT_READ_RESPONSE_PENDING for reads
560     if (att_response_size == ATT_READ_RESPONSE_PENDING){
561         // notify services that returned response pending
562         btstack_linked_list_iterator_t it;
563         btstack_linked_list_iterator_init(&it, &service_handlers);
564         while (btstack_linked_list_iterator_has_next(&it)) {
565             att_service_handler_t *handler = (att_service_handler_t *) btstack_linked_list_iterator_next(&it);
566             if ((handler->flags & ATT_SERVICE_FLAGS_DELAYED_RESPONSE) != 0u){
567                 handler->flags &= ~ATT_SERVICE_FLAGS_DELAYED_RESPONSE;
568                 handler->read_callback(att_connection->con_handle, ATT_READ_RESPONSE_PENDING, 0, NULL, 0);
569             }
570         }
571         // notify main read callback if it returned response pending
572         if ((att_server_flags & ATT_SERVICE_FLAGS_DELAYED_RESPONSE) != 0u){
573             // flag was set by read callback
574             btstack_assert(att_server_client_read_callback != NULL);
575             (*att_server_client_read_callback)(att_connection->con_handle, ATT_READ_RESPONSE_PENDING, 0, NULL, 0);
576         }
577     }
578 
579     // free reserved buffer - might trigger next read/write
580     if (eatt_buffer == NULL){
581         l2cap_release_packet_buffer();
582     }
583 }
584 #endif
585 
586 // pre: att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
587 // pre: can send now
588 // uses l2cap outgoing buffer if no eatt_buffer provided
589 // returns: 1 if packet was sent
590 static int
att_server_process_validated_request(att_server_t * att_server,att_connection_t * att_connection,uint8_t * eatt_buffer)591 att_server_process_validated_request(att_server_t *att_server, att_connection_t *att_connection, uint8_t *eatt_buffer) {
592 
593     uint8_t * att_response_buffer;
594     if (eatt_buffer != NULL){
595         att_response_buffer = eatt_buffer;
596     } else {
597         l2cap_reserve_packet_buffer();
598         att_response_buffer = l2cap_get_outgoing_buffer();
599     }
600 
601     uint16_t  att_response_size = 0;
602     // Send Error Response for MTU Request over connection-oriented channel
603     if ((att_server->bearer_type != ATT_BEARER_UNENHANCED_LE) && (att_server->request_buffer[0] == ATT_EXCHANGE_MTU_REQUEST)){
604         att_response_size = 5;
605         att_response_buffer[0] = ATT_ERROR_RESPONSE;
606         att_response_buffer[1] = ATT_EXCHANGE_MTU_REQUEST;
607         att_response_buffer[2] = 0;
608         att_response_buffer[3] = 0;
609         att_response_buffer[4] = ATT_ERROR_REQUEST_NOT_SUPPORTED;
610     } else {
611         att_response_size = att_handle_request(att_connection, att_server->request_buffer, att_server->request_size, att_response_buffer);
612     }
613 
614 #ifdef ENABLE_ATT_DELAYED_RESPONSE
615     if ((att_response_size == ATT_READ_RESPONSE_PENDING) || (att_response_size == ATT_INTERNAL_WRITE_RESPONSE_PENDING)){
616         att_server_handle_response_pending(att_server, att_connection, eatt_buffer, att_response_size);
617         return 0;
618     }
619 #endif
620 
621     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
622     if ((att_response_size     >= 4u)
623     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
624     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
625     && (att_connection->authenticated != 0u)){
626 
627         switch (gap_authorization_state(att_connection->con_handle)){
628             case AUTHORIZATION_UNKNOWN:
629                 if (eatt_buffer == NULL){
630                     l2cap_release_packet_buffer();
631                 }
632                 sm_request_pairing(att_connection->con_handle);
633                 return 0;
634             case AUTHORIZATION_PENDING:
635                 if (eatt_buffer == NULL){
636                     l2cap_release_packet_buffer();
637                 }
638                 return 0;
639             default:
640                 break;
641         }
642     }
643 
644     att_server->state = ATT_SERVER_IDLE;
645     if (att_response_size == 0u) {
646         if (eatt_buffer == NULL){
647             l2cap_release_packet_buffer();
648         }
649         return 0;
650     }
651 
652     (void) att_server_send_prepared(att_server, att_connection, eatt_buffer, att_response_size);
653 
654     // notify client about MTU exchange result
655     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
656         att_emit_mtu_event(att_connection->con_handle, att_connection->mtu);
657     }
658     return 1;
659 }
660 
661 #ifdef ENABLE_ATT_DELAYED_RESPONSE
att_server_response_ready(hci_con_handle_t con_handle)662 uint8_t att_server_response_ready(hci_con_handle_t con_handle){
663     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
664     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
665     att_server_t * att_server = &hci_connection->att_server;
666     att_connection_t * att_connection = &hci_connection->att_connection;
667     if (att_server->state != ATT_SERVER_RESPONSE_PENDING)   return ERROR_CODE_COMMAND_DISALLOWED;
668 
669     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
670     att_server_request_can_send_now(att_server, att_connection);
671     return ERROR_CODE_SUCCESS;
672 }
673 #endif
674 
att_run_for_context(att_server_t * att_server,att_connection_t * att_connection)675 static void att_run_for_context(att_server_t * att_server, att_connection_t * att_connection){
676     switch (att_server->state){
677         case ATT_SERVER_REQUEST_RECEIVED:
678             switch (att_server->bearer_type){
679                 case ATT_BEARER_UNENHANCED_LE:
680                     // wait until re-encryption as central is complete
681                     if (gap_reconnect_security_setup_active(att_connection->con_handle)) {
682                         return;
683                     };
684                     break;
685 #if defined(ENABLE_GATT_OVER_CLASSIC) || defined (ENABLE_GATT_OVER_EATT)
686 #ifdef ENABLE_GATT_OVER_CLASSIC
687                 case ATT_BEARER_UNENHANCED_CLASSIC:
688                     /* fall through */
689 #endif
690 #ifdef ENABLE_GATT_OVER_EATT
691                 case ATT_BEARER_ENHANCED_LE:
692 #endif
693                     // ok
694                     break;
695 #endif
696                 default:
697                     btstack_unreachable();
698                     break;
699             }
700 
701             // wait until pairing is complete
702             if (att_server->pairing_active) break;
703 
704 #ifdef ENABLE_LE_SIGNED_WRITE
705             if (att_server->request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
706                 log_info("ATT Signed Write!");
707                 if (!sm_cmac_ready()) {
708                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
709                     att_server->state = ATT_SERVER_IDLE;
710                     return;
711                 }
712                 if (att_server->request_size < (3 + 12)) {
713                     log_info("ATT Signed Write, request to short. Abort.");
714                     att_server->state = ATT_SERVER_IDLE;
715                     return;
716                 }
717                 if (att_server->ir_lookup_active){
718                     return;
719                 }
720                 if (att_server->ir_le_device_db_index < 0){
721                     log_info("ATT Signed Write, CSRK not available");
722                     att_server->state = ATT_SERVER_IDLE;
723                     return;
724                 }
725 
726                 // check counter
727                 uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
728                 uint32_t counter_db     = le_device_db_remote_counter_get(att_server->ir_le_device_db_index);
729                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
730                 if (counter_packet < counter_db){
731                     log_info("ATT Signed Write, db reports higher counter, abort");
732                     att_server->state = ATT_SERVER_IDLE;
733                     return;
734                 }
735 
736                 // signature is { sequence counter, secure hash }
737                 sm_key_t csrk;
738                 le_device_db_remote_csrk_get(att_server->ir_le_device_db_index, csrk);
739                 att_server->state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
740                 log_info("Orig Signature: ");
741                 log_info_hexdump( &att_server->request_buffer[att_server->request_size-8], 8);
742                 uint16_t attribute_handle = little_endian_read_16(att_server->request_buffer, 1);
743                 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);
744                 return;
745             }
746 #endif
747             // move on
748             att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
749             att_server_request_can_send_now(att_server, att_connection);
750             break;
751 
752         default:
753             break;
754     }
755 }
756 
att_server_data_ready_for_phase(att_server_t * att_server,att_server_run_phase_t phase)757 static bool att_server_data_ready_for_phase(att_server_t * att_server,  att_server_run_phase_t phase){
758     switch (phase){
759         case ATT_SERVER_RUN_PHASE_1_REQUESTS:
760             return att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
761         case ATT_SERVER_RUN_PHASE_2_INDICATIONS:
762              return (!btstack_linked_list_empty(&att_server->indication_requests) && (att_server->value_indication_handle == 0u));
763         case ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS:
764             return (!btstack_linked_list_empty(&att_server->notification_requests));
765         default:
766             btstack_assert(false);
767             return false;
768     }
769 }
770 
att_server_trigger_send_for_phase(att_server_t * att_server,att_connection_t * att_connection,att_server_run_phase_t phase)771 static void att_server_trigger_send_for_phase(att_server_t * att_server, att_connection_t * att_connection, att_server_run_phase_t phase){
772     btstack_context_callback_registration_t * client;
773     switch (phase){
774         case ATT_SERVER_RUN_PHASE_1_REQUESTS:
775             att_server_process_validated_request(att_server, att_connection, NULL);
776             break;
777         case ATT_SERVER_RUN_PHASE_2_INDICATIONS:
778             client = (btstack_context_callback_registration_t*) att_server->indication_requests;
779             btstack_linked_list_remove(&att_server->indication_requests, (btstack_linked_item_t *) client);
780             client->callback(client->context);
781             break;
782        case ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS:
783             client = (btstack_context_callback_registration_t*) att_server->notification_requests;
784             btstack_linked_list_remove(&att_server->notification_requests, (btstack_linked_item_t *) client);
785             client->callback(client->context);
786             break;
787         default:
788             btstack_assert(false);
789             break;
790     }
791 }
792 
att_server_handle_can_send_now(void)793 static void att_server_handle_can_send_now(void){
794 
795     hci_con_handle_t last_send_con_handle = HCI_CON_HANDLE_INVALID;
796     hci_connection_t * request_hci_connection   = NULL;
797     bool can_send_now = true;
798     uint8_t phase_index;
799 
800     for (phase_index = (uint8_t) ATT_SERVER_RUN_PHASE_1_REQUESTS; phase_index <=  (uint8_t) ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS; phase_index++){
801         att_server_run_phase_t phase = (att_server_run_phase_t) phase_index;
802         hci_con_handle_t skip_connections_until = att_server_last_can_send_now;
803         while (true){
804             btstack_linked_list_iterator_t it;
805             hci_connections_get_iterator(&it);
806             while(btstack_linked_list_iterator_has_next(&it)){
807                 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
808                 att_server_t * att_server = &connection->att_server;
809                 att_connection_t * att_connection = &connection->att_connection;
810 
811                 bool data_ready = att_server_data_ready_for_phase(att_server, phase);
812 
813                 // log_debug("phase %u, handle 0x%04x, skip until 0x%04x, data ready %u", phase, att_connection->con_handle, skip_connections_until, data_ready);
814 
815                 // skip until last sender found (which is also skipped)
816                 if (skip_connections_until != HCI_CON_HANDLE_INVALID){
817                     if (data_ready && (request_hci_connection == NULL)){
818                         request_hci_connection = connection;
819                     }
820                     if (skip_connections_until == att_connection->con_handle){
821                         skip_connections_until = HCI_CON_HANDLE_INVALID;
822                     }
823                     continue;
824                 };
825 
826                 if (data_ready){
827                     if (can_send_now){
828                         att_server_trigger_send_for_phase(att_server, att_connection, phase);
829                         last_send_con_handle = att_connection->con_handle;
830                         can_send_now = att_server_can_send_packet(att_server, att_connection);
831                         data_ready = att_server_data_ready_for_phase(att_server, phase);
832                         if (data_ready && (request_hci_connection == NULL)){
833                             request_hci_connection = connection;
834                         }
835                     } else {
836                         request_hci_connection = connection;
837                         break;
838                     }
839                 }
840             }
841 
842             // stop skipping (handles disconnect by last send connection)
843             skip_connections_until = HCI_CON_HANDLE_INVALID;
844 
845             // Exit loop, if we cannot send
846             if (!can_send_now) break;
847 
848             // Exit loop, if we can send but there are also no further request
849             if (request_hci_connection == NULL) break;
850 
851             // Finally, if we still can send and there are requests, just try again
852             request_hci_connection = NULL;
853         }
854         // update last send con handle for round robin
855         if (last_send_con_handle != HCI_CON_HANDLE_INVALID){
856             att_server_last_can_send_now = last_send_con_handle;
857         }
858     }
859 
860     if (request_hci_connection == NULL) return;
861 
862     att_server_t * att_server = &request_hci_connection->att_server;
863     att_connection_t * att_connection = &request_hci_connection->att_connection;
864     att_server_request_can_send_now(att_server, att_connection);
865 }
866 
att_server_handle_att_pdu(att_server_t * att_server,att_connection_t * att_connection,uint8_t * packet,uint16_t size)867 static void att_server_handle_att_pdu(att_server_t * att_server, att_connection_t * att_connection, uint8_t * packet, uint16_t size){
868 
869     uint8_t opcode  = packet[0u];
870     uint8_t method  = opcode & 0x03fu;
871     bool invalid = method > ATT_MULTIPLE_HANDLE_VALUE_NTF;
872     bool command = (opcode & 0x40u) != 0u;
873 
874     // ignore invalid commands
875     if (invalid && command){
876         return;
877     }
878 
879     // handle value indication confirms
880     if ((opcode == ATT_HANDLE_VALUE_CONFIRMATION) && (att_server->value_indication_handle != 0u)){
881         btstack_run_loop_remove_timer(&att_server->value_indication_timer);
882         uint16_t att_handle = att_server->value_indication_handle;
883         att_server->value_indication_handle = 0u;
884         att_handle_value_indication_notify_client(0u, att_connection->con_handle, att_handle);
885         att_server_request_can_send_now(att_server, att_connection);
886         return;
887     }
888 
889     // directly process command
890     // note: signed write cannot be handled directly as authentication needs to be verified
891     if (opcode == ATT_WRITE_COMMAND){
892         att_handle_request(att_connection, packet, size, NULL);
893         return;
894     }
895 
896     // check size
897     if (size > sizeof(att_server->request_buffer)) {
898         log_info("drop att pdu 0x%02x as size %u > att_server->request_buffer %u", packet[0], size, (int) sizeof(att_server->request_buffer));
899         return;
900     }
901 
902 #ifdef ENABLE_LE_SIGNED_WRITE
903     // abort signed write validation if a new request comes in (but finish previous signed write if possible)
904     if (att_server->state == ATT_SERVER_W4_SIGNED_WRITE_VALIDATION){
905         if (packet[0] == ATT_SIGNED_WRITE_COMMAND){
906             log_info("skip new signed write request as previous is in validation");
907             return;
908         } else {
909             log_info("abort signed write validation to process new request");
910             att_server->state = ATT_SERVER_IDLE;
911         }
912     }
913 #endif
914     // last request still in processing?
915     if (att_server->state != ATT_SERVER_IDLE){
916         log_info("skip att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state);
917         return;
918     }
919 
920     // store request
921     att_server->state = ATT_SERVER_REQUEST_RECEIVED;
922     att_server->request_size = size;
923     (void)memcpy(att_server->request_buffer, packet, size);
924 
925     att_run_for_context(att_server, att_connection);
926 }
927 
att_server_dispatch_packet_handler(uint8_t packet_type,uint16_t channel,uint8_t * packet,uint16_t size)928 static void att_server_dispatch_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
929     hci_connection_t * hci_connection;
930     att_connection_t * att_connection;
931     att_server_t     * att_server;
932 #ifdef ENABLE_GATT_OVER_CLASSIC
933     hci_con_handle_t con_handle;
934     bd_addr_t        address;
935     btstack_linked_list_iterator_t it;
936 #endif
937 
938     switch (packet_type){
939         case HCI_EVENT_PACKET:
940             switch (packet[0]){
941 #ifdef ENABLE_GATT_OVER_CLASSIC
942                 case L2CAP_EVENT_CHANNEL_OPENED:
943                     con_handle = l2cap_event_channel_opened_get_handle(packet);
944                     hci_connection = hci_connection_for_handle(con_handle);
945                     if (!hci_connection) break;
946                     att_server = &hci_connection->att_server;
947                     // store connection info
948                     att_server->bearer_type = ATT_BEARER_UNENHANCED_CLASSIC;
949                     att_server->peer_addr_type = BD_ADDR_TYPE_ACL;
950                     l2cap_event_channel_opened_get_address(packet, att_server->peer_address);
951                     att_connection = &hci_connection->att_connection;
952                     att_connection->con_handle = con_handle;
953                     // reset connection properties
954                     att_server->state = ATT_SERVER_IDLE;
955                     att_connection->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
956                     att_connection->max_mtu = l2cap_max_mtu();
957                     if (att_connection->max_mtu > ATT_REQUEST_BUFFER_SIZE){
958                         att_connection->max_mtu = ATT_REQUEST_BUFFER_SIZE;
959                     }
960 
961                     log_info("Connection opened %s, l2cap cid %04x, mtu %u", bd_addr_to_str(address), att_server->l2cap_cid, att_connection->mtu);
962 
963                     // update security params
964                     att_connection->encryption_key_size = gap_encryption_key_size(con_handle);
965                     att_connection->authenticated = gap_authenticated(con_handle);
966                     att_connection->secure_connection = gap_secure_connection(con_handle);
967                     log_info("encrypted key size %u, authenticated %u, secure connection %u",
968                              att_connection->encryption_key_size, att_connection->authenticated, att_connection->secure_connection);
969 
970                     // notify connection opened
971                     att_emit_connected_event(att_server, att_connection);
972 
973                     // restore persisten ccc if encrypted
974                     if ( gap_security_level(con_handle) >= LEVEL_2){
975                         att_server_persistent_ccc_restore(att_server, att_connection);
976                     }
977                     // TODO: what to do about le device db?
978                     att_server->pairing_active = 0;
979                     break;
980 #endif
981                 case L2CAP_EVENT_CAN_SEND_NOW:
982                     att_server_handle_can_send_now();
983                     break;
984                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
985                     // GATT client has negotiated the mtu for this connection
986                     hci_connection = hci_connection_for_handle(channel);
987                     if (!hci_connection) break;
988                     att_connection = &hci_connection->att_connection;
989                     att_connection->mtu = little_endian_read_16(packet, 4);
990                     break;
991                 default:
992                     break;
993             }
994             break;
995 
996         case ATT_DATA_PACKET:
997             log_debug("ATT Packet, handle 0x%04x", channel);
998             hci_connection = hci_connection_for_handle(channel);
999             if (!hci_connection) break;
1000 
1001             att_server = &hci_connection->att_server;
1002             att_connection = &hci_connection->att_connection;
1003             att_server_handle_att_pdu(att_server, att_connection, packet, size);
1004             break;
1005 
1006 #ifdef ENABLE_GATT_OVER_CLASSIC
1007         case L2CAP_DATA_PACKET:
1008             hci_connections_get_iterator(&it);
1009             while(btstack_linked_list_iterator_has_next(&it)){
1010                 hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1011                 att_server = &hci_connection->att_server;
1012                 att_connection = &hci_connection->att_connection;
1013                 if (att_server->l2cap_cid == channel) {
1014                     att_server_handle_att_pdu(att_server, att_connection, packet, size);
1015                     break;
1016                 }
1017             }
1018             break;
1019 #endif
1020 
1021         default:
1022             break;
1023     }
1024 }
1025 
1026 // ---------------------
1027 // persistent CCC writes
att_server_persistent_ccc_tag_for_index(uint8_t index)1028 static uint32_t att_server_persistent_ccc_tag_for_index(uint8_t index){
1029     return (((uint8_t)'B') << 24u) | (((uint8_t)'T') << 16u) | (((uint8_t)'C') << 8u) | index;
1030 }
1031 
att_server_persistent_ccc_write(hci_con_handle_t con_handle,uint16_t att_handle,uint16_t value)1032 static void att_server_persistent_ccc_write(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t value){
1033     // lookup att_server instance
1034     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1035     if (!hci_connection) return;
1036     att_server_t * att_server = &hci_connection->att_server;
1037     int le_device_index = att_server->ir_le_device_db_index;
1038     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);
1039 
1040     // check if bonded
1041     if (le_device_index < 0) return;
1042 
1043     // get btstack_tlv
1044     const btstack_tlv_t * tlv_impl = NULL;
1045     void * tlv_context;
1046     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
1047     if (!tlv_impl) return;
1048 
1049     // update ccc tag
1050     int index;
1051     uint32_t highest_seq_nr = 0;
1052     uint32_t lowest_seq_nr = 0;
1053     uint32_t tag_for_lowest_seq_nr = 0;
1054     uint32_t tag_for_empty = 0;
1055     persistent_ccc_entry_t entry;
1056     for (index=0; index<NVN_NUM_GATT_SERVER_CCC; index++){
1057         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
1058         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1059 
1060         // empty/invalid tag
1061         if (len != (int) sizeof(persistent_ccc_entry_t)){
1062             tag_for_empty = tag;
1063             continue;
1064         }
1065         // update highest seq nr
1066         if (entry.seq_nr > highest_seq_nr){
1067             highest_seq_nr = entry.seq_nr;
1068         }
1069         // find entry with lowest seq nr
1070         if ((tag_for_lowest_seq_nr == 0u) || (entry.seq_nr < lowest_seq_nr)){
1071             tag_for_lowest_seq_nr = tag;
1072             lowest_seq_nr = entry.seq_nr;
1073         }
1074 
1075         if ((int)entry.device_index != le_device_index) continue;
1076         if (     entry.att_handle   != att_handle)      continue;
1077 
1078         // found matching entry
1079         if (value != 0u){
1080             // update
1081             if (entry.value == value) {
1082                 log_info("CCC Index %u: Up-to-date", index);
1083                 return;
1084             }
1085             entry.value = (uint8_t) value;
1086             entry.seq_nr = highest_seq_nr + 1u;
1087             log_info("CCC Index %u: Store", index);
1088             int result = tlv_impl->store_tag(tlv_context, tag, (const uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1089             if (result != 0){
1090                 log_error("Store tag index %u failed", index);
1091             }
1092         } else {
1093             // delete
1094             log_info("CCC Index %u: Delete", index);
1095             tlv_impl->delete_tag(tlv_context, tag);
1096         }
1097         return;
1098     }
1099 
1100     log_info("tag_for_empty %"PRIx32", tag_for_lowest_seq_nr %"PRIx32, tag_for_empty, tag_for_lowest_seq_nr);
1101 
1102     if (value == 0u){
1103         // done
1104         return;
1105     }
1106 
1107     uint32_t tag_to_use = 0u;
1108     if (tag_for_empty != 0u){
1109         tag_to_use = tag_for_empty;
1110     } else if (tag_for_lowest_seq_nr != 0u){
1111         tag_to_use = tag_for_lowest_seq_nr;
1112     } else {
1113         // should not happen
1114         return;
1115     }
1116     // store ccc tag
1117     entry.seq_nr       = highest_seq_nr + 1u;
1118     entry.device_index = le_device_index;
1119     entry.att_handle   = att_handle;
1120     entry.value        = (uint8_t) value;
1121     int result = tlv_impl->store_tag(tlv_context, tag_to_use, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1122     if (result != 0){
1123         log_error("Store tag index %u failed", index);
1124     }
1125 }
1126 
att_server_persistent_ccc_clear(att_server_t * att_server)1127 static void att_server_persistent_ccc_clear(att_server_t * att_server){
1128     int le_device_index = att_server->ir_le_device_db_index;
1129     log_info("Clear CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
1130     // check if bonded
1131     if (le_device_index < 0) return;
1132     // get btstack_tlv
1133     const btstack_tlv_t * tlv_impl = NULL;
1134     void * tlv_context;
1135     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
1136     if (!tlv_impl) return;
1137     // get all ccc tag
1138     int index;
1139     persistent_ccc_entry_t entry;
1140     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
1141         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
1142         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1143         if (len != (int) sizeof(persistent_ccc_entry_t)) continue;
1144         if ((int)entry.device_index != le_device_index) continue;
1145         // delete entry
1146         log_info("CCC Index %u: Delete", index);
1147         tlv_impl->delete_tag(tlv_context, tag);
1148     }
1149 }
1150 
att_server_persistent_ccc_restore(att_server_t * att_server,att_connection_t * att_connection)1151 static void att_server_persistent_ccc_restore(att_server_t * att_server, att_connection_t * att_connection){
1152     int le_device_index = att_server->ir_le_device_db_index;
1153     log_info("Restore CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
1154     // check if bonded
1155     if (le_device_index < 0) return;
1156     // get btstack_tlv
1157     const btstack_tlv_t * tlv_impl = NULL;
1158     void * tlv_context;
1159     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
1160     if (!tlv_impl) return;
1161     // get all ccc tag
1162     int index;
1163     persistent_ccc_entry_t entry;
1164     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
1165         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
1166         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1167         if (len != (int) sizeof(persistent_ccc_entry_t)) continue;
1168         if ((int) entry.device_index != le_device_index) continue;
1169         // simulate write callback
1170         uint16_t attribute_handle = entry.att_handle;
1171         uint8_t  value[2];
1172         little_endian_store_16(value, 0, entry.value);
1173         att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
1174         if (!callback) continue;
1175         log_info("CCC Index %u: Set Attribute handle 0x%04x to value 0x%04x", index, attribute_handle, entry.value );
1176         (*callback)(att_connection->con_handle, attribute_handle, ATT_TRANSACTION_MODE_NONE, 0, value, sizeof(value));
1177     }
1178 }
1179 
1180 // persistent CCC writes
1181 // ---------------------
1182 
1183 // gatt service management
att_service_handler_for_handle(uint16_t handle)1184 static att_service_handler_t * att_service_handler_for_handle(uint16_t handle){
1185     btstack_linked_list_iterator_t it;
1186     btstack_linked_list_iterator_init(&it, &service_handlers);
1187     while (btstack_linked_list_iterator_has_next(&it)){
1188         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1189         if (handler->start_handle > handle) continue;
1190         if (handler->end_handle   < handle) continue;
1191         return handler;
1192     }
1193     return NULL;
1194 }
1195 
att_server_write_callback_for_handle(uint16_t handle)1196 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle){
1197     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1198     if (handler != NULL) return handler->write_callback;
1199     return att_server_client_write_callback;
1200 }
1201 
att_server_packet_handler_for_handle(uint16_t handle)1202 static btstack_packet_handler_t att_server_packet_handler_for_handle(uint16_t handle){
1203     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1204     if (handler != NULL) return handler->packet_handler;
1205     return att_client_packet_handler;
1206 }
1207 
att_notify_write_callbacks(hci_con_handle_t con_handle,uint16_t transaction_mode)1208 static void att_notify_write_callbacks(hci_con_handle_t con_handle, uint16_t transaction_mode){
1209     // notify all callbacks
1210     btstack_linked_list_iterator_t it;
1211     btstack_linked_list_iterator_init(&it, &service_handlers);
1212     while (btstack_linked_list_iterator_has_next(&it)){
1213         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1214         if (!handler->write_callback) continue;
1215         (*handler->write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
1216     }
1217     if (!att_server_client_write_callback) return;
1218     (*att_server_client_write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
1219 }
1220 
1221 // returns first reported error or 0
att_validate_prepared_write(hci_con_handle_t con_handle)1222 static uint8_t att_validate_prepared_write(hci_con_handle_t con_handle){
1223     btstack_linked_list_iterator_t it;
1224     btstack_linked_list_iterator_init(&it, &service_handlers);
1225     while (btstack_linked_list_iterator_has_next(&it)){
1226         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1227         if (!handler->write_callback) continue;
1228         uint8_t error_code = (*handler->write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1229         if (error_code != 0u) return error_code;
1230     }
1231     if (!att_server_client_write_callback) return 0;
1232     return (*att_server_client_write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1233 }
1234 
att_server_read_callback(hci_con_handle_t con_handle,uint16_t attribute_handle,uint16_t offset,uint8_t * buffer,uint16_t buffer_size)1235 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){
1236     att_service_handler_t * service = att_service_handler_for_handle(attribute_handle);
1237     att_read_callback_t read_callback = (service != NULL) ? service->read_callback : att_server_client_read_callback;
1238     uint16_t result = 0;
1239     if (read_callback != NULL){
1240         result = (*read_callback)(con_handle, attribute_handle, offset, buffer, buffer_size);
1241 #ifdef ENABLE_ATT_DELAYED_RESPONSE
1242         if (result == ATT_READ_RESPONSE_PENDING){
1243             if (service == NULL){
1244                 att_server_flags |= ATT_SERVICE_FLAGS_DELAYED_RESPONSE;
1245             } else {
1246                 service->flags   |= ATT_SERVICE_FLAGS_DELAYED_RESPONSE;
1247             }
1248         }
1249 #endif
1250     }
1251     return result;
1252 }
1253 
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)1254 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){
1255     switch (transaction_mode){
1256         case ATT_TRANSACTION_MODE_VALIDATE:
1257             return att_validate_prepared_write(con_handle);
1258         case ATT_TRANSACTION_MODE_EXECUTE:
1259         case ATT_TRANSACTION_MODE_CANCEL:
1260             att_notify_write_callbacks(con_handle, transaction_mode);
1261             return 0;
1262         default:
1263             break;
1264     }
1265 
1266     // track CCC writes
1267     if (att_is_persistent_ccc(attribute_handle) && (offset == 0u) && (buffer_size == 2u)){
1268         att_server_persistent_ccc_write(con_handle, attribute_handle, little_endian_read_16(buffer, 0));
1269     }
1270 
1271     att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
1272     if (!callback) return 0;
1273     return (*callback)(con_handle, attribute_handle, transaction_mode, offset, buffer, buffer_size);
1274 }
1275 
1276 /**
1277  * @brief register read/write callbacks for specific handle range
1278  * @param att_service_handler_t
1279  */
att_server_register_service_handler(att_service_handler_t * handler)1280 void att_server_register_service_handler(att_service_handler_t * handler){
1281     bool att_server_registered = false;
1282     if (att_service_handler_for_handle(handler->start_handle) != NULL){
1283         att_server_registered = true;
1284     }
1285 
1286     if (att_service_handler_for_handle(handler->end_handle) != NULL){
1287         att_server_registered = true;
1288     }
1289 
1290     if (att_server_registered){
1291         log_error("handler for range 0x%04x-0x%04x already registered", handler->start_handle, handler->end_handle);
1292         return;
1293     }
1294 
1295     handler->flags = 0;
1296     btstack_linked_list_add(&service_handlers, (btstack_linked_item_t*) handler);
1297 }
1298 
att_server_init(uint8_t const * db,att_read_callback_t read_callback,att_write_callback_t write_callback)1299 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
1300 
1301     // store callbacks
1302     att_server_client_read_callback  = read_callback;
1303     att_server_client_write_callback = write_callback;
1304 
1305     // register for HCI Events
1306     hci_event_callback_registration.callback = &att_server_event_packet_handler;
1307     hci_add_event_handler(&hci_event_callback_registration);
1308 
1309     // register for SM events
1310     sm_event_callback_registration.callback = &att_server_event_packet_handler;
1311     sm_add_event_handler(&sm_event_callback_registration);
1312 
1313     // and L2CAP ATT Server PDUs
1314     att_dispatch_register_server(att_server_dispatch_packet_handler);
1315 
1316 #ifdef ENABLE_GATT_OVER_CLASSIC
1317     // setup l2cap service
1318     att_dispatch_classic_register_service();
1319 #endif
1320 
1321     att_set_db(db);
1322     att_set_read_callback(att_server_read_callback);
1323     att_set_write_callback(att_server_write_callback);
1324 }
1325 
att_server_register_packet_handler(btstack_packet_handler_t handler)1326 void att_server_register_packet_handler(btstack_packet_handler_t handler){
1327     att_client_packet_handler = handler;
1328 }
1329 
1330 
1331 // to be deprecated
att_server_can_send_packet_now(hci_con_handle_t con_handle)1332 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
1333     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1334     if (!hci_connection) return 0;
1335     att_server_t * att_server = &hci_connection->att_server;
1336     att_connection_t * att_connection = &hci_connection->att_connection;
1337     return att_server_can_send_packet(att_server, att_connection);
1338 }
1339 
att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration,hci_con_handle_t con_handle)1340 uint8_t att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1341     return att_server_request_to_send_notification(callback_registration, con_handle);
1342 }
1343 
att_server_request_can_send_now_event(hci_con_handle_t con_handle)1344 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
1345     att_client_waiting_for_can_send_registration.callback = &att_emit_can_send_now_event;
1346     att_server_request_to_send_notification(&att_client_waiting_for_can_send_registration, con_handle);
1347 }
1348 // end of deprecated
1349 
att_server_request_to_send_notification(btstack_context_callback_registration_t * callback_registration,hci_con_handle_t con_handle)1350 uint8_t att_server_request_to_send_notification(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1351     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1352     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1353     att_server_t * att_server = &hci_connection->att_server;
1354     att_connection_t * att_connection = &hci_connection->att_connection;
1355     bool added = btstack_linked_list_add_tail(&att_server->notification_requests, (btstack_linked_item_t*) callback_registration);
1356     att_server_request_can_send_now(att_server, att_connection);
1357     if (added){
1358         return ERROR_CODE_SUCCESS;
1359     } else {
1360         return ERROR_CODE_COMMAND_DISALLOWED;
1361     }
1362 }
1363 
att_server_request_to_send_indication(btstack_context_callback_registration_t * callback_registration,hci_con_handle_t con_handle)1364 uint8_t att_server_request_to_send_indication(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1365     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1366     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1367     att_server_t * att_server = &hci_connection->att_server;
1368     att_connection_t * att_connection = &hci_connection->att_connection;
1369     bool added = btstack_linked_list_add_tail(&att_server->indication_requests, (btstack_linked_item_t*) callback_registration);
1370     att_server_request_can_send_now(att_server, att_connection);
1371     if (added){
1372         return ERROR_CODE_SUCCESS;
1373     } else {
1374         return ERROR_CODE_COMMAND_DISALLOWED;
1375     }
1376 }
1377 
att_server_prepare_server_message(hci_con_handle_t con_handle,att_server_t ** out_att_server,att_connection_t ** out_att_connection,uint8_t ** out_packet_buffer)1378 static uint8_t att_server_prepare_server_message(hci_con_handle_t con_handle, att_server_t ** out_att_server, att_connection_t ** out_att_connection, uint8_t ** out_packet_buffer){
1379 
1380     att_server_t *     att_server = NULL;
1381     att_connection_t * att_connection = NULL;
1382     uint8_t *          packet_buffer = NULL;
1383 
1384     // prefer enhanced bearer
1385 #ifdef ENABLE_GATT_OVER_EATT
1386     att_server_eatt_bearer_t * eatt_bearer = att_server_eatt_bearer_for_con_handle(con_handle);
1387     if (eatt_bearer != NULL){
1388         att_server     = &eatt_bearer->att_server;
1389         att_connection = &eatt_bearer->att_connection;
1390         packet_buffer  = eatt_bearer->send_buffer;
1391     } else
1392 #endif
1393     {
1394         hci_connection_t *hci_connection = hci_connection_for_handle(con_handle);
1395         if (hci_connection != NULL) {
1396             att_server     = &hci_connection->att_server;
1397             att_connection = &hci_connection->att_connection;
1398         }
1399     }
1400 
1401     if (att_server == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1402     if (!att_server_can_send_packet(att_server, att_connection)) return BTSTACK_ACL_BUFFERS_FULL;
1403 
1404     if (packet_buffer == NULL){
1405         l2cap_reserve_packet_buffer();
1406         packet_buffer = l2cap_get_outgoing_buffer();
1407     }
1408 
1409     *out_att_connection = att_connection;
1410     *out_att_server = att_server;
1411     *out_packet_buffer = packet_buffer;
1412     return ERROR_CODE_SUCCESS;
1413 }
1414 
att_server_notify(hci_con_handle_t con_handle,uint16_t attribute_handle,const uint8_t * value,uint16_t value_len)1415 uint8_t att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, const uint8_t *value, uint16_t value_len){
1416     att_server_t * att_server = NULL;
1417     att_connection_t * att_connection = NULL;
1418     uint8_t * packet_buffer = NULL;
1419 
1420     uint8_t status = att_server_prepare_server_message(con_handle, &att_server, &att_connection, &packet_buffer);
1421     if (status != ERROR_CODE_SUCCESS){
1422         return status;
1423     }
1424 
1425     uint16_t size = att_prepare_handle_value_notification(att_connection, attribute_handle, value, value_len, packet_buffer);
1426 
1427     return att_server_send_prepared(att_server, att_connection, NULL, size);
1428 }
1429 
1430 /**
1431  * @brief notify client about multiple attribute value changes
1432  * @param con_handle
1433  * @param num_attributes
1434  * @param attribute_handles[]
1435  * @param values_data[]
1436  * @param values_len[]
1437  * @return 0 if ok, error otherwise
1438  */
att_server_multiple_notify(hci_con_handle_t con_handle,uint8_t num_attributes,const uint16_t * attribute_handles,const uint8_t ** values_data,const uint16_t * values_len)1439 uint8_t att_server_multiple_notify(hci_con_handle_t con_handle, uint8_t num_attributes,
1440                                    const uint16_t * attribute_handles, const uint8_t ** values_data, const uint16_t * values_len){
1441 
1442     att_server_t * att_server = NULL;
1443     att_connection_t * att_connection = NULL;
1444     uint8_t * packet_buffer = NULL;
1445 
1446     uint8_t status = att_server_prepare_server_message(con_handle, &att_server, &att_connection, &packet_buffer);
1447     if (status != ERROR_CODE_SUCCESS){
1448         return status;
1449     }
1450 
1451     uint16_t size = att_prepare_handle_value_multiple_notification(att_connection, num_attributes, attribute_handles, values_data, values_len, packet_buffer);
1452 
1453     return att_server_send_prepared(att_server, att_connection, packet_buffer, size);
1454 }
1455 
att_server_indicate(hci_con_handle_t con_handle,uint16_t attribute_handle,const uint8_t * value,uint16_t value_len)1456 uint8_t att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, const uint8_t *value, uint16_t value_len){
1457 
1458     att_server_t * att_server = NULL;
1459     att_connection_t * att_connection = NULL;
1460     uint8_t * packet_buffer = NULL;
1461 
1462     uint8_t status = att_server_prepare_server_message(con_handle, &att_server, &att_connection, &packet_buffer);
1463     if (status != ERROR_CODE_SUCCESS){
1464         return status;
1465     }
1466 
1467     if (att_server->value_indication_handle != 0u) {
1468         // free reserved packet buffer
1469         if (att_server->bearer_type == ATT_BEARER_ENHANCED_LE){
1470             l2cap_release_packet_buffer();
1471         }
1472         return ATT_HANDLE_VALUE_INDICATION_IN_PROGRESS;
1473     }
1474 
1475     // track indication
1476     att_server->value_indication_handle = attribute_handle;
1477     btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout);
1478     btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
1479     btstack_run_loop_add_timer(&att_server->value_indication_timer);
1480 
1481     uint16_t size = att_prepare_handle_value_indication(att_connection, attribute_handle, value, value_len, packet_buffer);
1482 
1483     return att_server_send_prepared(att_server, att_connection, NULL, size);
1484 }
1485 
att_server_get_mtu(hci_con_handle_t con_handle)1486 uint16_t att_server_get_mtu(hci_con_handle_t con_handle){
1487     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1488     if (!hci_connection) return 0;
1489     att_connection_t * att_connection = &hci_connection->att_connection;
1490     return att_connection->mtu;
1491 }
1492 
att_server_deinit(void)1493 void att_server_deinit(void){
1494     att_server_client_read_callback  = NULL;
1495     att_server_client_write_callback = NULL;
1496     att_client_packet_handler = NULL;
1497     service_handlers = NULL;
1498     att_server_flags = 0;
1499 }
1500 
1501 #ifdef ENABLE_GATT_OVER_EATT
1502 
1503 #define MAX_NR_EATT_CHANNELS 5
1504 
1505 static uint16_t att_server_eatt_receive_buffer_size;
1506 static uint16_t att_server_eatt_send_buffer_size;
1507 
att_server_eatt_bearer_for_cid(uint16_t cid)1508 static att_server_eatt_bearer_t * att_server_eatt_bearer_for_cid(uint16_t cid){
1509     btstack_linked_list_iterator_t it;
1510     btstack_linked_list_iterator_init(&it, &att_server_eatt_bearer_active);
1511     while(btstack_linked_list_iterator_has_next(&it)){
1512         att_server_eatt_bearer_t * eatt_bearer = (att_server_eatt_bearer_t *) btstack_linked_list_iterator_next(&it);
1513         if (eatt_bearer->att_server.l2cap_cid == cid) {
1514             return eatt_bearer;
1515         }
1516     }
1517     return NULL;
1518 }
1519 
att_server_eatt_bearer_for_con_handle(hci_con_handle_t con_handle)1520 static att_server_eatt_bearer_t * att_server_eatt_bearer_for_con_handle(hci_con_handle_t con_handle){
1521     btstack_linked_list_iterator_t it;
1522     btstack_linked_list_iterator_init(&it, &att_server_eatt_bearer_active);
1523     while(btstack_linked_list_iterator_has_next(&it)){
1524         att_server_eatt_bearer_t * eatt_bearer = (att_server_eatt_bearer_t *) btstack_linked_list_iterator_next(&it);
1525         if (eatt_bearer->att_connection.con_handle == con_handle) {
1526             return eatt_bearer;
1527         }
1528     }
1529     return NULL;
1530 }
1531 
att_server_eatt_handler(uint8_t packet_type,uint16_t channel,uint8_t * packet,uint16_t size)1532 static void att_server_eatt_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1533     uint16_t cid;
1534     uint8_t status;
1535     uint16_t remote_mtu;
1536 
1537     uint8_t i;
1538     uint8_t num_requested_bearers;
1539     uint8_t num_accepted_bearers;
1540     uint16_t initial_credits = L2CAP_LE_AUTOMATIC_CREDITS;
1541     uint8_t * receive_buffers[MAX_NR_EATT_CHANNELS];
1542     uint16_t cids[MAX_NR_EATT_CHANNELS];
1543     att_server_eatt_bearer_t * eatt_bearers[MAX_NR_EATT_CHANNELS];
1544     att_server_eatt_bearer_t * eatt_bearer;
1545     att_server_t * att_server;
1546     att_connection_t * att_connection;
1547     hci_con_handle_t con_handle;
1548     hci_connection_t * hci_connection;
1549 
1550     switch (packet_type) {
1551 
1552         case L2CAP_DATA_PACKET:
1553             eatt_bearer = att_server_eatt_bearer_for_cid(channel);
1554             btstack_assert(eatt_bearer != NULL);
1555             att_server = &eatt_bearer->att_server;
1556             att_connection = &eatt_bearer->att_connection;
1557             att_server_handle_att_pdu(att_server, att_connection, packet, size);
1558             break;
1559 
1560         case HCI_EVENT_PACKET:
1561             switch (packet[0]) {
1562 
1563                 case L2CAP_EVENT_CAN_SEND_NOW:
1564                     cid = l2cap_event_packet_sent_get_local_cid(packet);
1565                     eatt_bearer = att_server_eatt_bearer_for_cid(cid);
1566                     btstack_assert(eatt_bearer != NULL);
1567                     att_server = &eatt_bearer->att_server;
1568                     att_connection = &eatt_bearer->att_connection;
1569                     // only used for EATT request responses
1570                     btstack_assert(att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED);
1571                     att_server_process_validated_request(att_server, att_connection, eatt_bearer->send_buffer);
1572                     break;
1573 
1574                 case L2CAP_EVENT_PACKET_SENT:
1575                     cid = l2cap_event_packet_sent_get_local_cid(packet);
1576                     eatt_bearer = att_server_eatt_bearer_for_cid(cid);
1577                     btstack_assert(eatt_bearer != NULL);
1578                     att_server = &eatt_bearer->att_server;
1579                     att_connection = &eatt_bearer->att_connection;
1580                     att_server_handle_att_pdu(att_server, att_connection, packet, size);
1581                     break;
1582 
1583                 case L2CAP_EVENT_ECBM_INCOMING_CONNECTION:
1584                     cid = l2cap_event_ecbm_incoming_connection_get_local_cid(packet);
1585 
1586                     // reject if outgoing l2cap connection active, L2CAP/TIM/BV-01-C
1587                     con_handle = l2cap_event_ecbm_incoming_connection_get_handle(packet);
1588                     hci_connection = hci_connection_for_handle(con_handle);
1589                     btstack_assert(hci_connection != NULL);
1590                     if (hci_connection->att_server.eatt_outgoing_active) {
1591                         hci_connection->att_server.incoming_connection_request = true;
1592                         l2cap_ecbm_decline_channels(cid, L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE );
1593                         log_info("Decline incoming connection from %s", bd_addr_to_str(hci_connection->address));
1594                     } else {
1595                         num_requested_bearers = l2cap_event_ecbm_incoming_connection_get_num_channels(packet);
1596                         for (i = 0; i < num_requested_bearers; i++){
1597                             eatt_bearers[i] = (att_server_eatt_bearer_t *) btstack_linked_list_pop(&att_server_eatt_bearer_pool);
1598                             if (eatt_bearers[i] == NULL) {
1599                                 break;
1600                             }
1601                             eatt_bearers[i]->att_connection.con_handle = l2cap_event_ecbm_incoming_connection_get_handle(packet);
1602                             eatt_bearers[i]->att_server.bearer_type = ATT_BEARER_ENHANCED_LE;
1603                             receive_buffers[i] = eatt_bearers[i]->receive_buffer;
1604                             btstack_linked_list_add(&att_server_eatt_bearer_active, (btstack_linked_item_t *) eatt_bearers[i]);
1605                         }
1606                         num_accepted_bearers = i;
1607                         status = l2cap_ecbm_accept_channels(cid, num_accepted_bearers, initial_credits, att_server_eatt_receive_buffer_size, receive_buffers, cids);
1608                         btstack_assert(status == ERROR_CODE_SUCCESS);
1609                         log_info("requested %u, accepted %u", num_requested_bearers, num_accepted_bearers);
1610                         for (i=0;i<num_accepted_bearers;i++){
1611                             log_info("eatt l2cap cid: 0x%04x", cids[i]);
1612                             eatt_bearers[i]->att_server.l2cap_cid = cids[i];
1613                         }
1614                     }
1615                     break;
1616 
1617                 case L2CAP_EVENT_ECBM_CHANNEL_OPENED:
1618                     cid         = l2cap_event_ecbm_channel_opened_get_local_cid(packet);
1619                     status      = l2cap_event_ecbm_channel_opened_get_status(packet);
1620                     remote_mtu  = l2cap_event_ecbm_channel_opened_get_remote_mtu(packet);
1621                     eatt_bearer = att_server_eatt_bearer_for_cid(cid);
1622                     btstack_assert(eatt_bearer != NULL);
1623                     eatt_bearer->att_connection.mtu_exchanged = true;
1624                     eatt_bearer->att_connection.mtu = remote_mtu;
1625                     eatt_bearer->att_connection.max_mtu = remote_mtu;
1626                     log_info("L2CAP_EVENT_ECBM_CHANNEL_OPENED - cid 0x%04x mtu %u, status 0x%02x", cid, remote_mtu, status);
1627                     break;
1628 
1629                 case L2CAP_EVENT_ECBM_RECONFIGURED:
1630                     break;
1631 
1632                 case L2CAP_EVENT_CHANNEL_CLOSED:
1633                     eatt_bearer = att_server_eatt_bearer_for_cid(l2cap_event_channel_closed_get_local_cid(packet));
1634                     btstack_assert(eatt_bearer != NULL);
1635 
1636                     // TODO: finalize - abort queued writes
1637 
1638                     btstack_linked_list_remove(&att_server_eatt_bearer_active, (btstack_linked_item_t  *) eatt_bearer);
1639                     btstack_linked_list_add(&att_server_eatt_bearer_pool, (btstack_linked_item_t  *) eatt_bearer);
1640                     break;
1641                 default:
1642                     break;
1643             }
1644             break;
1645         default:
1646             btstack_unreachable();
1647             break;
1648     }
1649 }
1650 
1651 // create eatt bearers
att_server_eatt_init(uint8_t num_eatt_bearers,uint8_t * storage_buffer,uint16_t storage_size)1652 uint8_t att_server_eatt_init(uint8_t num_eatt_bearers, uint8_t * storage_buffer, uint16_t storage_size){
1653     uint16_t size_for_structs = num_eatt_bearers * sizeof(att_server_eatt_bearer_t);
1654     if (storage_size < size_for_structs) {
1655         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
1656     }
1657 
1658     // TODO: The minimum ATT_MTU for an Enhanced ATT bearer is 64 octets.
1659 
1660     memset(storage_buffer, 0, storage_size);
1661     uint16_t buffer_size_per_bearer = ((storage_size - size_for_structs) / num_eatt_bearers);
1662     att_server_eatt_receive_buffer_size = buffer_size_per_bearer / 2;
1663     att_server_eatt_send_buffer_size    = buffer_size_per_bearer / 2;
1664     uint8_t * bearer_buffer = &storage_buffer[size_for_structs];
1665     uint8_t i;
1666     att_server_eatt_bearer_t * eatt_bearer = (att_server_eatt_bearer_t *) storage_buffer;
1667     log_info("%u EATT bearers with receive buffer size %u",
1668              num_eatt_bearers, att_server_eatt_receive_buffer_size);
1669     for (i=0;i<num_eatt_bearers;i++){
1670         eatt_bearer->att_connection.con_handle = HCI_CON_HANDLE_INVALID;
1671         eatt_bearer->receive_buffer = bearer_buffer;
1672         bearer_buffer += att_server_eatt_receive_buffer_size;
1673         eatt_bearer->send_buffer = bearer_buffer;
1674         bearer_buffer += att_server_eatt_send_buffer_size;
1675         btstack_linked_list_add(&att_server_eatt_bearer_pool, (btstack_linked_item_t *) eatt_bearer);
1676         eatt_bearer++;
1677     }
1678     // TODO: define minimum EATT MTU
1679     return l2cap_ecbm_register_service(att_server_eatt_handler, BLUETOOTH_PSM_EATT, 64, LEVEL_2, false);
1680 }
1681 #endif
1682