xref: /btstack/src/ble/att_server.c (revision de804f9e40fa10b2ead91db28fa5571afa6ec08a)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "att_server.c"
39 
40 
41 //
42 // ATT Server Globals
43 //
44 
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <inttypes.h>
50 
51 #include "btstack_config.h"
52 
53 #include "att_dispatch.h"
54 #include "ble/att_db.h"
55 #include "ble/att_server.h"
56 #include "ble/core.h"
57 #include "ble/le_device_db.h"
58 #include "ble/sm.h"
59 #include "btstack_debug.h"
60 #include "btstack_event.h"
61 #include "btstack_memory.h"
62 #include "btstack_run_loop.h"
63 #include "gap.h"
64 #include "hci.h"
65 #include "hci_dump.h"
66 #include "l2cap.h"
67 
68 static void att_run_for_context(att_server_t * att_server);
69 
70 // global
71 static btstack_packet_callback_registration_t hci_event_callback_registration;
72 static btstack_packet_callback_registration_t sm_event_callback_registration;
73 static btstack_packet_handler_t               att_client_packet_handler = NULL;
74 static btstack_linked_list_t                  can_send_now_clients;
75 static uint8_t                                att_client_waiting_for_can_send;
76 
77 static att_server_t * att_server_for_handle(hci_con_handle_t con_handle){
78     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
79     if (!hci_connection) return NULL;
80     return &hci_connection->att_server;
81 }
82 
83 #ifdef ENABLE_LE_SIGNED_WRITE
84 static att_server_t * att_server_for_state(att_server_state_t state){
85     btstack_linked_list_iterator_t it;
86     hci_connections_get_iterator(&it);
87     while(btstack_linked_list_iterator_has_next(&it)){
88         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
89         att_server_t * att_server = &connection->att_server;
90         if (att_server->state == state) return att_server;
91     }
92     return NULL;
93 }
94 #endif
95 
96 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
97     if (!att_client_packet_handler) return;
98 
99     uint8_t event[7];
100     int pos = 0;
101     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
102     event[pos++] = sizeof(event) - 2;
103     event[pos++] = status;
104     little_endian_store_16(event, pos, client_handle);
105     pos += 2;
106     little_endian_store_16(event, pos, attribute_handle);
107     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
108 }
109 
110 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
111     if (!att_client_packet_handler) return;
112 
113     uint8_t event[6];
114     int pos = 0;
115     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
116     event[pos++] = sizeof(event) - 2;
117     little_endian_store_16(event, pos, con_handle);
118     pos += 2;
119     little_endian_store_16(event, pos, mtu);
120     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
121 }
122 
123 static void att_emit_can_send_now_event(void){
124     if (!att_client_packet_handler) return;
125 
126     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
127     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
128 }
129 
130 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
131     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
132     att_server_t * att_server = att_server_for_handle(con_handle);
133     if (!att_server) return;
134     uint16_t att_handle = att_server->value_indication_handle;
135     att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_server->connection.con_handle, att_handle);
136 }
137 
138 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
139 
140     UNUSED(channel);
141     UNUSED(size);
142 
143     att_server_t * att_server;
144     hci_con_handle_t con_handle;
145 
146     switch (packet_type) {
147 
148         case HCI_EVENT_PACKET:
149             switch (hci_event_packet_get_type(packet)) {
150 
151                 case HCI_EVENT_LE_META:
152                     switch (packet[2]) {
153                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
154                             con_handle = little_endian_read_16(packet, 4);
155                             att_server = att_server_for_handle(con_handle);
156                             if (!att_server) break;
157                         	// store connection info
158                         	att_server->peer_addr_type = packet[7];
159                             reverse_bd_addr(&packet[8], att_server->peer_address);
160                             att_server->connection.con_handle = con_handle;
161                             // reset connection properties
162                             att_server->state = ATT_SERVER_IDLE;
163                             att_server->connection.mtu = ATT_DEFAULT_MTU;
164                             att_server->connection.max_mtu = l2cap_max_le_mtu();
165                             if (att_server->connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){
166                                 att_server->connection.max_mtu = ATT_REQUEST_BUFFER_SIZE;
167                             }
168                             att_server->connection.encryption_key_size = 0;
169                             att_server->connection.authenticated = 0;
170 		                	att_server->connection.authorized = 0;
171                             att_server->ir_le_device_db_index = -1;
172                             break;
173 
174                         default:
175                             break;
176                     }
177                     break;
178 
179                 case HCI_EVENT_ENCRYPTION_CHANGE:
180                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
181                 	// check handle
182                     con_handle = little_endian_read_16(packet, 3);
183                     att_server = att_server_for_handle(con_handle);
184                     if (!att_server) break;
185                 	att_server->connection.encryption_key_size = sm_encryption_key_size(con_handle);
186                 	att_server->connection.authenticated = sm_authenticated(con_handle);
187                 	break;
188 
189                 case HCI_EVENT_DISCONNECTION_COMPLETE:
190                     // check handle
191                     con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
192                     att_server = att_server_for_handle(con_handle);
193                     if (!att_server) break;
194                     att_clear_transaction_queue(&att_server->connection);
195                     att_server->connection.con_handle = 0;
196                     att_server->value_indication_handle = 0; // reset error state
197                     att_server->state = ATT_SERVER_IDLE;
198                     break;
199 
200                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
201                     con_handle = sm_event_identity_resolving_started_get_handle(packet);
202                     att_server = att_server_for_handle(con_handle);
203                     if (!att_server) break;
204                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
205                     att_server->ir_lookup_active = 1;
206                     break;
207                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
208                     con_handle = sm_event_identity_resolving_succeeded_get_handle(packet);
209                     att_server = att_server_for_handle(con_handle);
210                     if (!att_server) break;
211                     att_server->ir_lookup_active = 0;
212                     att_server->ir_le_device_db_index = sm_event_identity_resolving_succeeded_get_index_internal(packet);
213                     log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED id %u", att_server->ir_le_device_db_index);
214                     att_run_for_context(att_server);
215                     break;
216                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
217                     con_handle = sm_event_identity_resolving_failed_get_handle(packet);
218                     att_server = att_server_for_handle(con_handle);
219                     if (!att_server) break;
220                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
221                     att_server->ir_lookup_active = 0;
222                     att_server->ir_le_device_db_index = -1;
223                     att_run_for_context(att_server);
224                     break;
225                 case SM_EVENT_AUTHORIZATION_RESULT: {
226                     con_handle = sm_event_authorization_result_get_handle(packet);
227                     att_server = att_server_for_handle(con_handle);
228                     if (!att_server) break;
229                     att_server->connection.authorized = sm_event_authorization_result_get_authorization_result(packet);
230                     att_dispatch_server_request_can_send_now_event(con_handle);
231                 	break;
232                 }
233                 default:
234                     break;
235             }
236             break;
237         default:
238             break;
239     }
240 }
241 
242 #ifdef ENABLE_LE_SIGNED_WRITE
243 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
244 
245     att_server_t * att_server = att_server_for_state(ATT_SERVER_W4_SIGNED_WRITE_VALIDATION);
246     if (!att_server) return;
247 
248     uint8_t hash_flipped[8];
249     reverse_64(hash, hash_flipped);
250     if (memcmp(hash_flipped, &att_server->request_buffer[att_server->request_size-8], 8)){
251         log_info("ATT Signed Write, invalid signature");
252         att_server->state = ATT_SERVER_IDLE;
253         return;
254     }
255     log_info("ATT Signed Write, valid signature");
256 
257     // update sequence number
258     uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
259     le_device_db_remote_counter_set(att_server->ir_le_device_db_index, counter_packet+1);
260     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
261     att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
262 }
263 #endif
264 
265 // pre: att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
266 // pre: can send now
267 // returns: 1 if packet was sent
268 static int att_server_process_validated_request(att_server_t * att_server){
269 
270     l2cap_reserve_packet_buffer();
271     uint8_t * att_response_buffer = l2cap_get_outgoing_buffer();
272     uint16_t  att_response_size   = att_handle_request(&att_server->connection, att_server->request_buffer, att_server->request_size, att_response_buffer);
273 
274     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
275     if ((att_response_size     >= 4)
276     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
277     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
278     && (att_server->connection.authenticated)){
279 
280         switch (sm_authorization_state(att_server->connection.con_handle)){
281             case AUTHORIZATION_UNKNOWN:
282                 l2cap_release_packet_buffer();
283                 sm_request_pairing(att_server->connection.con_handle);
284                 return 0;
285             case AUTHORIZATION_PENDING:
286                 l2cap_release_packet_buffer();
287                 return 0;
288             default:
289                 break;
290         }
291     }
292 
293     att_server->state = ATT_SERVER_IDLE;
294     if (att_response_size == 0) {
295         l2cap_release_packet_buffer();
296         return 0;
297     }
298 
299     l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size);
300 
301     // notify client about MTU exchange result
302     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
303         att_emit_mtu_event(att_server->connection.con_handle, att_server->connection.mtu);
304     }
305     return 1;
306 }
307 
308 static void att_run_for_context(att_server_t * att_server){
309     switch (att_server->state){
310         case ATT_SERVER_REQUEST_RECEIVED:
311 #ifdef ENABLE_LE_SIGNED_WRITE
312             if (att_server->request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
313                 log_info("ATT Signed Write!");
314                 if (!sm_cmac_ready()) {
315                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
316                     att_server->state = ATT_SERVER_IDLE;
317                     return;
318                 }
319                 if (att_server->request_size < (3 + 12)) {
320                     log_info("ATT Signed Write, request to short. Abort.");
321                     att_server->state = ATT_SERVER_IDLE;
322                     return;
323                 }
324                 if (att_server->ir_lookup_active){
325                     return;
326                 }
327                 if (att_server->ir_le_device_db_index < 0){
328                     log_info("ATT Signed Write, CSRK not available");
329                     att_server->state = ATT_SERVER_IDLE;
330                     return;
331                 }
332 
333                 // check counter
334                 uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
335                 uint32_t counter_db     = le_device_db_remote_counter_get(att_server->ir_le_device_db_index);
336                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
337                 if (counter_packet < counter_db){
338                     log_info("ATT Signed Write, db reports higher counter, abort");
339                     att_server->state = ATT_SERVER_IDLE;
340                     return;
341                 }
342 
343                 // signature is { sequence counter, secure hash }
344                 sm_key_t csrk;
345                 le_device_db_remote_csrk_get(att_server->ir_le_device_db_index, csrk);
346                 att_server->state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
347                 log_info("Orig Signature: ");
348                 log_info_hexdump( &att_server->request_buffer[att_server->request_size-8], 8);
349                 uint16_t attribute_handle = little_endian_read_16(att_server->request_buffer, 1);
350                 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);
351                 return;
352             }
353 #endif
354             // move on
355             att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
356             att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
357             break;
358 
359         default:
360             break;
361     }
362 }
363 
364 static void att_server_handle_can_send_now(void){
365 
366     // NOTE: we get l2cap fixed channel instead of con_handle
367 
368     btstack_linked_list_iterator_t it;
369     hci_connections_get_iterator(&it);
370     while(btstack_linked_list_iterator_has_next(&it)){
371         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
372         att_server_t * att_server = &connection->att_server;
373         if (att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED){
374             int sent = att_server_process_validated_request(att_server);
375             if (sent && (att_client_waiting_for_can_send || !btstack_linked_list_empty(&can_send_now_clients))){
376                 att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
377                 return;
378             }
379         }
380     }
381 
382     while (!btstack_linked_list_empty(&can_send_now_clients)){
383         // handle first client
384         btstack_context_callback_registration_t * client = (btstack_context_callback_registration_t*) can_send_now_clients;
385         hci_con_handle_t con_handle = (uintptr_t) client->context;
386         btstack_linked_list_remove(&can_send_now_clients, (btstack_linked_item_t *) client);
387         client->callback(client->context);
388 
389         // request again if needed
390         if (!att_dispatch_server_can_send_now(con_handle)){
391             if (!btstack_linked_list_empty(&can_send_now_clients) || att_client_waiting_for_can_send){
392                 att_dispatch_server_request_can_send_now_event(con_handle);
393             }
394             return;
395         }
396     }
397 
398     if (att_client_waiting_for_can_send){
399         att_client_waiting_for_can_send = 0;
400         att_emit_can_send_now_event();
401     }
402 }
403 
404 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
405 
406     att_server_t * att_server;
407 
408     switch (packet_type){
409 
410         case HCI_EVENT_PACKET:
411             if (packet[0] != L2CAP_EVENT_CAN_SEND_NOW) break;
412             att_server_handle_can_send_now();
413             break;
414 
415         case ATT_DATA_PACKET:
416             log_info("ATT Packet, handle 0x%04x", handle);
417             att_server = att_server_for_handle(handle);
418             if (!att_server) break;
419 
420             // handle value indication confirms
421             if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_server->value_indication_handle){
422                 btstack_run_loop_remove_timer(&att_server->value_indication_timer);
423                 uint16_t att_handle = att_server->value_indication_handle;
424                 att_server->value_indication_handle = 0;
425                 att_handle_value_indication_notify_client(0, att_server->connection.con_handle, att_handle);
426                 return;
427             }
428 
429             // directly process command
430             // note: signed write cannot be handled directly as authentication needs to be verified
431             if (packet[0] == ATT_WRITE_COMMAND){
432                 att_handle_request(&att_server->connection, packet, size, 0);
433                 return;
434             }
435 
436             // check size
437             if (size > sizeof(att_server->request_buffer)) {
438                 log_info("att_packet_handler: dropping att pdu 0x%02x as size %u > att_server->request_buffer %u", packet[0], size, (int) sizeof(att_server->request_buffer));
439                 return;
440             }
441 
442             // last request still in processing?
443             if (att_server->state != ATT_SERVER_IDLE){
444                 log_info("att_packet_handler: skipping att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state);
445                 return;
446             }
447 
448             // store request
449             att_server->state = ATT_SERVER_REQUEST_RECEIVED;
450             att_server->request_size = size;
451             memcpy(att_server->request_buffer, packet, size);
452 
453             att_run_for_context(att_server);
454             break;
455     }
456 }
457 
458 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
459 
460     // register for HCI Events
461     hci_event_callback_registration.callback = &att_event_packet_handler;
462     hci_add_event_handler(&hci_event_callback_registration);
463 
464     // register for SM events
465     sm_event_callback_registration.callback = &att_event_packet_handler;
466     sm_add_event_handler(&sm_event_callback_registration);
467 
468     // and L2CAP ATT Server PDUs
469     att_dispatch_register_server(att_packet_handler);
470 
471     att_set_db(db);
472     att_set_read_callback(read_callback);
473     att_set_write_callback(write_callback);
474 
475 }
476 
477 void att_server_register_packet_handler(btstack_packet_handler_t handler){
478     att_client_packet_handler = handler;
479 }
480 
481 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
482 	return att_dispatch_server_can_send_now(con_handle);
483 }
484 
485 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
486     log_debug("att_server_request_can_send_now_event 0x%04x", con_handle);
487     att_client_waiting_for_can_send = 1;
488     att_dispatch_server_request_can_send_now_event(con_handle);
489 }
490 
491 void att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
492     // check if can send already
493     if (att_dispatch_server_can_send_now(con_handle)){
494         callback_registration->callback(callback_registration->context);
495         return;
496     }
497     callback_registration->context = (void*)(uintptr_t) con_handle;
498     btstack_linked_list_add_tail(&can_send_now_clients, (btstack_linked_item_t*) callback_registration);
499     att_dispatch_server_request_can_send_now_event(con_handle);
500 }
501 
502 
503 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
504     att_server_t * att_server = att_server_for_handle(con_handle);
505     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
506 
507     if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
508 
509     l2cap_reserve_packet_buffer();
510     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
511     uint16_t size = att_prepare_handle_value_notification(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
512 	return l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
513 }
514 
515 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
516     att_server_t * att_server = att_server_for_handle(con_handle);
517     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
518 
519     if (att_server->value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PROGRESS;
520     if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
521 
522     // track indication
523     att_server->value_indication_handle = attribute_handle;
524     btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout);
525     btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
526     btstack_run_loop_add_timer(&att_server->value_indication_timer);
527 
528     l2cap_reserve_packet_buffer();
529     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
530     uint16_t size = att_prepare_handle_value_indication(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
531 	l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
532     return 0;
533 }
534