1 /* 2 * Copyright (C) 2009-2012 by Matthias Ringwald 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 MATTHIAS RINGWALD 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 [email protected] 34 * 35 */ 36 37 /* 38 * l2cap.c 39 * 40 * Logical Link Control and Adaption Protocl (L2CAP) 41 * 42 * Created by Matthias Ringwald on 5/16/09. 43 */ 44 45 #include "l2cap.h" 46 #include "hci.h" 47 #include "hci_dump.h" 48 #include "debug.h" 49 #include "btstack_memory.h" 50 51 #include <stdarg.h> 52 #include <string.h> 53 54 #include <stdio.h> 55 56 // nr of buffered acl packets in outgoing queue to get max performance 57 #define NR_BUFFERED_ACL_PACKETS 3 58 59 // used to cache l2cap rejects, echo, and informational requests 60 #define NR_PENDING_SIGNALING_RESPONSES 3 61 62 // offsets for L2CAP SIGNALING COMMANDS 63 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET 0 64 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET 1 65 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2 66 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET 4 67 68 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 69 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size); 70 71 // used to cache l2cap rejects, echo, and informational requests 72 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES]; 73 static int signaling_responses_pending; 74 75 static linked_list_t l2cap_channels = NULL; 76 static linked_list_t l2cap_services = NULL; 77 static void (*packet_handler) (void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) = null_packet_handler; 78 static int new_credits_blocked = 0; 79 80 static btstack_packet_handler_t attribute_protocol_packet_handler = NULL; 81 static btstack_packet_handler_t security_protocol_packet_handler = NULL; 82 83 // prototypes 84 static void l2cap_finialize_channel_close(l2cap_channel_t *channel); 85 static l2cap_service_t * l2cap_get_service(uint16_t psm); 86 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status); 87 static void l2cap_emit_channel_closed(l2cap_channel_t *channel); 88 static void l2cap_emit_connection_request(l2cap_channel_t *channel); 89 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel); 90 91 92 void l2cap_init(){ 93 new_credits_blocked = 0; 94 signaling_responses_pending = 0; 95 96 l2cap_channels = NULL; 97 l2cap_services = NULL; 98 99 packet_handler = null_packet_handler; 100 101 // 102 // register callback with HCI 103 // 104 hci_register_packet_handler(&l2cap_packet_handler); 105 hci_connectable_control(0); // no services yet 106 } 107 108 109 /** Register L2CAP packet handlers */ 110 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 111 } 112 void l2cap_register_packet_handler(void (*handler)(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){ 113 packet_handler = handler; 114 } 115 116 // notify client/protocol handler 117 void l2cap_dispatch(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){ 118 if (channel->packet_handler) { 119 (* (channel->packet_handler))(type, channel->local_cid, data, size); 120 } else { 121 (*packet_handler)(channel->connection, type, channel->local_cid, data, size); 122 } 123 } 124 125 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) { 126 uint8_t event[21]; 127 event[0] = L2CAP_EVENT_CHANNEL_OPENED; 128 event[1] = sizeof(event) - 2; 129 event[2] = status; 130 bt_flip_addr(&event[3], channel->address); 131 bt_store_16(event, 9, channel->handle); 132 bt_store_16(event, 11, channel->psm); 133 bt_store_16(event, 13, channel->local_cid); 134 bt_store_16(event, 15, channel->remote_cid); 135 bt_store_16(event, 17, channel->local_mtu); 136 bt_store_16(event, 19, channel->remote_mtu); 137 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 138 l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event)); 139 } 140 141 void l2cap_emit_channel_closed(l2cap_channel_t *channel) { 142 uint8_t event[4]; 143 event[0] = L2CAP_EVENT_CHANNEL_CLOSED; 144 event[1] = sizeof(event) - 2; 145 bt_store_16(event, 2, channel->local_cid); 146 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 147 l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event)); 148 } 149 150 void l2cap_emit_connection_request(l2cap_channel_t *channel) { 151 uint8_t event[16]; 152 event[0] = L2CAP_EVENT_INCOMING_CONNECTION; 153 event[1] = sizeof(event) - 2; 154 bt_flip_addr(&event[2], channel->address); 155 bt_store_16(event, 8, channel->handle); 156 bt_store_16(event, 10, channel->psm); 157 bt_store_16(event, 12, channel->local_cid); 158 bt_store_16(event, 14, channel->remote_cid); 159 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 160 l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event)); 161 } 162 163 static void l2cap_emit_service_registered(void *connection, uint8_t status, uint16_t psm){ 164 uint8_t event[5]; 165 event[0] = L2CAP_EVENT_SERVICE_REGISTERED; 166 event[1] = sizeof(event) - 2; 167 event[2] = status; 168 bt_store_16(event, 3, psm); 169 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 170 (*packet_handler)(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 171 } 172 173 void l2cap_emit_credits(l2cap_channel_t *channel, uint8_t credits) { 174 // track credits 175 channel->packets_granted += credits; 176 // log_info("l2cap_emit_credits for cid %u, credits given: %u (+%u)\n", channel->local_cid, channel->packets_granted, credits); 177 178 uint8_t event[5]; 179 event[0] = L2CAP_EVENT_CREDITS; 180 event[1] = sizeof(event) - 2; 181 bt_store_16(event, 2, channel->local_cid); 182 event[4] = credits; 183 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 184 l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event)); 185 } 186 187 void l2cap_block_new_credits(uint8_t blocked){ 188 new_credits_blocked = blocked; 189 } 190 191 void l2cap_hand_out_credits(void){ 192 193 if (new_credits_blocked) return; // we're told not to. used by daemon 194 195 linked_item_t *it; 196 for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){ 197 if (!hci_number_free_acl_slots()) return; 198 l2cap_channel_t * channel = (l2cap_channel_t *) it; 199 if (channel->state != L2CAP_STATE_OPEN) continue; 200 if (hci_number_outgoing_packets(channel->handle) < NR_BUFFERED_ACL_PACKETS && channel->packets_granted == 0) { 201 l2cap_emit_credits(channel, 1); 202 } 203 } 204 } 205 206 l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){ 207 linked_item_t *it; 208 for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){ 209 l2cap_channel_t * channel = (l2cap_channel_t *) it; 210 if ( channel->local_cid == local_cid) { 211 return channel; 212 } 213 } 214 return NULL; 215 } 216 217 int l2cap_can_send_packet_now(uint16_t local_cid){ 218 l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid); 219 if (!channel) return 0; 220 if (!channel->packets_granted) return 0; 221 return hci_can_send_packet_now(HCI_ACL_DATA_PACKET); 222 } 223 224 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){ 225 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 226 if (channel) { 227 return channel->remote_mtu; 228 } 229 return 0; 230 } 231 232 int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){ 233 234 if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)){ 235 log_info("l2cap_send_signaling_packet, cannot send\n"); 236 return BTSTACK_ACL_BUFFERS_FULL; 237 } 238 239 // log_info("l2cap_send_signaling_packet type %u\n", cmd); 240 uint8_t *acl_buffer = hci_get_outgoing_acl_packet_buffer(); 241 va_list argptr; 242 va_start(argptr, identifier); 243 uint16_t len = l2cap_create_signaling_internal(acl_buffer, handle, cmd, identifier, argptr); 244 va_end(argptr); 245 // log_info("l2cap_send_signaling_packet con %u!\n", handle); 246 return hci_send_acl_packet(acl_buffer, len); 247 } 248 249 uint8_t *l2cap_get_outgoing_buffer(void){ 250 return hci_get_outgoing_acl_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes 251 } 252 253 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){ 254 255 if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)){ 256 log_info("l2cap_send_internal cid %u, cannot send\n", local_cid); 257 return BTSTACK_ACL_BUFFERS_FULL; 258 } 259 260 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 261 if (!channel) { 262 log_error("l2cap_send_internal no channel for cid %u\n", local_cid); 263 return -1; // TODO: define error 264 } 265 266 if (channel->packets_granted == 0){ 267 log_error("l2cap_send_internal cid %u, no credits!\n", local_cid); 268 return -1; // TODO: define error 269 } 270 271 --channel->packets_granted; 272 273 log_debug("l2cap_send_internal cid %u, handle %u, 1 credit used, credits left %u;\n", 274 local_cid, channel->handle, channel->packets_granted); 275 276 uint8_t *acl_buffer = hci_get_outgoing_acl_packet_buffer(); 277 278 // 0 - Connection handle : PB=10 : BC=00 279 bt_store_16(acl_buffer, 0, channel->handle | (2 << 12) | (0 << 14)); 280 // 2 - ACL length 281 bt_store_16(acl_buffer, 2, len + 4); 282 // 4 - L2CAP packet length 283 bt_store_16(acl_buffer, 4, len + 0); 284 // 6 - L2CAP channel DEST 285 bt_store_16(acl_buffer, 6, channel->remote_cid); 286 // send 287 int err = hci_send_acl_packet(acl_buffer, len+8); 288 289 l2cap_hand_out_credits(); 290 291 return err; 292 } 293 294 int l2cap_send_prepared_connectionless(uint16_t handle, uint16_t cid, uint16_t len){ 295 296 if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)){ 297 log_info("l2cap_send_prepared_to_handle cid %u, cannot send\n", cid); 298 return BTSTACK_ACL_BUFFERS_FULL; 299 } 300 301 log_debug("l2cap_send_prepared_to_handle cid %u, handle %u\n", cid, handle); 302 303 uint8_t *acl_buffer = hci_get_outgoing_acl_packet_buffer(); 304 305 // 0 - Connection handle : PB=10 : BC=00 306 bt_store_16(acl_buffer, 0, handle | (2 << 12) | (0 << 14)); 307 // 2 - ACL length 308 bt_store_16(acl_buffer, 2, len + 4); 309 // 4 - L2CAP packet length 310 bt_store_16(acl_buffer, 4, len + 0); 311 // 6 - L2CAP channel DEST 312 bt_store_16(acl_buffer, 6, cid); 313 // send 314 int err = hci_send_acl_packet(acl_buffer, len+8); 315 316 l2cap_hand_out_credits(); 317 318 return err; 319 } 320 321 int l2cap_send_internal(uint16_t local_cid, uint8_t *data, uint16_t len){ 322 323 if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)){ 324 log_info("l2cap_send_internal cid %u, cannot send\n", local_cid); 325 return BTSTACK_ACL_BUFFERS_FULL; 326 } 327 328 uint8_t *acl_buffer = hci_get_outgoing_acl_packet_buffer(); 329 330 memcpy(&acl_buffer[8], data, len); 331 332 return l2cap_send_prepared(local_cid, len); 333 } 334 335 int l2cap_send_connectionless(uint16_t handle, uint16_t cid, uint8_t *data, uint16_t len){ 336 337 if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)){ 338 log_info("l2cap_send_internal cid %u, cannot send\n", cid); 339 return BTSTACK_ACL_BUFFERS_FULL; 340 } 341 342 uint8_t *acl_buffer = hci_get_outgoing_acl_packet_buffer(); 343 344 memcpy(&acl_buffer[8], data, len); 345 346 return l2cap_send_prepared_connectionless(handle, cid, len); 347 } 348 349 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){ 350 channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag); 351 } 352 353 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){ 354 channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag); 355 } 356 357 358 359 // MARK: L2CAP_RUN 360 // process outstanding signaling tasks 361 void l2cap_run(void){ 362 363 // check pending signaling responses 364 while (signaling_responses_pending){ 365 366 if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)) break; 367 368 hci_con_handle_t handle = signaling_responses[0].handle; 369 uint8_t sig_id = signaling_responses[0].sig_id; 370 uint16_t infoType = signaling_responses[0].data; // INFORMATION_REQUEST 371 uint16_t result = signaling_responses[0].data; // CONNECTION_REQUEST 372 373 switch (signaling_responses[0].code){ 374 case CONNECTION_REQUEST: 375 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, result, 0); 376 break; 377 case ECHO_REQUEST: 378 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL); 379 break; 380 case INFORMATION_REQUEST: 381 if (infoType == 2) { 382 uint32_t features = 0; 383 // extended features request supported, however no features present 384 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, 4, &features); 385 } else { 386 // all other types are not supported 387 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL); 388 } 389 break; 390 default: 391 // should not happen 392 break; 393 } 394 395 // remove first item 396 signaling_responses_pending--; 397 int i; 398 for (i=0; i < signaling_responses_pending; i++){ 399 memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t)); 400 } 401 } 402 403 uint8_t config_options[4]; 404 linked_item_t *it; 405 linked_item_t *next; 406 for (it = (linked_item_t *) l2cap_channels; it ; it = next){ 407 next = it->next; // cache next item as current item might get freed 408 409 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) break; 410 if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)) break; 411 412 l2cap_channel_t * channel = (l2cap_channel_t *) it; 413 414 // log_info("l2cap_run: state %u, var 0x%02x\n", channel->state, channel->state_var); 415 416 417 switch (channel->state){ 418 419 case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION: 420 // send connection request - set state first 421 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE; 422 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch 423 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1); 424 break; 425 426 case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE: 427 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, channel->reason, 0); 428 // discard channel - l2cap_finialize_channel_close without sending l2cap close event 429 linked_list_remove(&l2cap_channels, (linked_item_t *) channel); // -- remove from list 430 btstack_memory_l2cap_channel_free(channel); 431 break; 432 433 case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT: 434 channel->state = L2CAP_STATE_CONFIG; 435 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 436 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0); 437 break; 438 439 case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST: 440 // success, start l2cap handshake 441 channel->local_sig_id = l2cap_next_sig_id(); 442 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP; 443 l2cap_send_signaling_packet( channel->handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid); 444 break; 445 446 case L2CAP_STATE_CONFIG: 447 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){ 448 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP); 449 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP); 450 l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, 0, 0, 0, NULL); 451 } 452 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){ 453 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 454 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ); 455 channel->local_sig_id = l2cap_next_sig_id(); 456 config_options[0] = 1; // MTU 457 config_options[1] = 2; // len param 458 bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu); 459 l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options); 460 } 461 if (l2cap_channel_ready_for_open(channel)){ 462 channel->state = L2CAP_STATE_OPEN; 463 l2cap_emit_channel_opened(channel, 0); // success 464 l2cap_emit_credits(channel, 1); 465 } 466 break; 467 468 case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE: 469 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid); 470 l2cap_finialize_channel_close(channel); // -- remove from list 471 break; 472 473 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 474 channel->local_sig_id = l2cap_next_sig_id(); 475 channel->state = L2CAP_STATE_WAIT_DISCONNECT; 476 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid); 477 break; 478 default: 479 break; 480 } 481 } 482 } 483 484 uint16_t l2cap_max_mtu(void){ 485 return hci_max_acl_data_packet_length() - L2CAP_HEADER_SIZE; 486 } 487 488 // open outgoing L2CAP channel 489 void l2cap_create_channel_internal(void * connection, btstack_packet_handler_t packet_handler, 490 bd_addr_t address, uint16_t psm, uint16_t mtu){ 491 492 // alloc structure 493 l2cap_channel_t * chan = (l2cap_channel_t*) btstack_memory_l2cap_channel_get(); 494 if (!chan) { 495 // emit error event 496 l2cap_channel_t dummy_channel; 497 BD_ADDR_COPY(dummy_channel.address, address); 498 dummy_channel.psm = psm; 499 l2cap_emit_channel_opened(&dummy_channel, BTSTACK_MEMORY_ALLOC_FAILED); 500 return; 501 } 502 // limit local mtu to max acl packet length 503 if (mtu > l2cap_max_mtu()) { 504 mtu = l2cap_max_mtu(); 505 } 506 507 // fill in 508 BD_ADDR_COPY(chan->address, address); 509 chan->psm = psm; 510 chan->handle = 0; 511 chan->connection = connection; 512 chan->packet_handler = packet_handler; 513 chan->remote_mtu = L2CAP_MINIMAL_MTU; 514 chan->local_mtu = mtu; 515 chan->packets_granted = 0; 516 517 // set initial state 518 chan->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION; 519 chan->state_var = L2CAP_CHANNEL_STATE_VAR_NONE; 520 chan->remote_sig_id = L2CAP_SIG_ID_INVALID; 521 chan->local_sig_id = L2CAP_SIG_ID_INVALID; 522 523 // add to connections list 524 linked_list_add(&l2cap_channels, (linked_item_t *) chan); 525 526 l2cap_run(); 527 } 528 529 void l2cap_disconnect_internal(uint16_t local_cid, uint8_t reason){ 530 // find channel for local_cid 531 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 532 if (channel) { 533 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 534 } 535 // process 536 l2cap_run(); 537 } 538 539 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){ 540 linked_item_t *it = (linked_item_t *) &l2cap_channels; 541 while (it->next){ 542 l2cap_channel_t * channel = (l2cap_channel_t *) it->next; 543 if ( ! BD_ADDR_CMP( channel->address, address) ){ 544 if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) { 545 // failure, forward error code 546 l2cap_emit_channel_opened(channel, status); 547 // discard channel 548 it->next = it->next->next; 549 btstack_memory_l2cap_channel_free(channel); 550 } 551 } else { 552 it = it->next; 553 } 554 } 555 } 556 557 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){ 558 linked_item_t *it; 559 for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){ 560 l2cap_channel_t * channel = (l2cap_channel_t *) it; 561 if ( ! BD_ADDR_CMP( channel->address, address) ){ 562 if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) { 563 // success, start l2cap handshake 564 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST; 565 channel->handle = handle; 566 channel->local_cid = l2cap_next_local_cid(); 567 } 568 } 569 } 570 // process 571 l2cap_run(); 572 } 573 574 void l2cap_event_handler( uint8_t *packet, uint16_t size ){ 575 576 bd_addr_t address; 577 hci_con_handle_t handle; 578 l2cap_channel_t * channel; 579 linked_item_t *it; 580 int hci_con_used; 581 582 switch(packet[0]){ 583 584 // handle connection complete events 585 case HCI_EVENT_CONNECTION_COMPLETE: 586 bt_flip_addr(address, &packet[5]); 587 if (packet[2] == 0){ 588 handle = READ_BT_16(packet, 3); 589 l2cap_handle_connection_success_for_addr(address, handle); 590 } else { 591 l2cap_handle_connection_failed_for_addr(address, packet[2]); 592 } 593 break; 594 595 // handle successful create connection cancel command 596 case HCI_EVENT_COMMAND_COMPLETE: 597 if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) { 598 if (packet[5] == 0){ 599 bt_flip_addr(address, &packet[6]); 600 // CONNECTION TERMINATED BY LOCAL HOST (0X16) 601 l2cap_handle_connection_failed_for_addr(address, 0x16); 602 } 603 } 604 l2cap_run(); // try sending signaling packets first 605 break; 606 607 case HCI_EVENT_COMMAND_STATUS: 608 l2cap_run(); // try sending signaling packets first 609 break; 610 611 // handle disconnection complete events 612 case HCI_EVENT_DISCONNECTION_COMPLETE: 613 // send l2cap disconnect events for all channels on this handle 614 handle = READ_BT_16(packet, 3); 615 it = (linked_item_t *) &l2cap_channels; 616 while (it->next){ 617 l2cap_channel_t * channel = (l2cap_channel_t *) it->next; 618 if ( channel->handle == handle ){ 619 // update prev item before free'ing next element - don't call l2cap_finalize_channel_close 620 it->next = it->next->next; 621 l2cap_emit_channel_closed(channel); 622 btstack_memory_l2cap_channel_free(channel); 623 } else { 624 it = it->next; 625 } 626 } 627 break; 628 629 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: 630 l2cap_run(); // try sending signaling packets first 631 l2cap_hand_out_credits(); 632 break; 633 634 // HCI Connection Timeouts 635 case L2CAP_EVENT_TIMEOUT_CHECK: 636 handle = READ_BT_16(packet, 2); 637 if (hci_authentication_active_for_handle(handle)) break; 638 hci_con_used = 0; 639 for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){ 640 channel = (l2cap_channel_t *) it; 641 if (channel->handle == handle) { 642 hci_con_used = 1; 643 } 644 } 645 if (hci_con_used) break; 646 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) break; 647 hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection 648 break; 649 650 case DAEMON_EVENT_HCI_PACKET_SENT: 651 for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){ 652 channel = (l2cap_channel_t *) it; 653 if (channel->packet_handler) { 654 (* (channel->packet_handler))(HCI_EVENT_PACKET, channel->local_cid, packet, size); 655 } 656 } 657 if (attribute_protocol_packet_handler) { 658 (*attribute_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size); 659 } 660 if (security_protocol_packet_handler) { 661 (*security_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size); 662 } 663 break; 664 665 default: 666 break; 667 } 668 669 // pass on 670 (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, packet, size); 671 } 672 673 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){ 674 channel->remote_sig_id = identifier; 675 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE; 676 l2cap_run(); 677 } 678 679 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){ 680 if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) { 681 signaling_responses[signaling_responses_pending].handle = handle; 682 signaling_responses[signaling_responses_pending].code = code; 683 signaling_responses[signaling_responses_pending].sig_id = sig_id; 684 signaling_responses[signaling_responses_pending].data = data; 685 signaling_responses_pending++; 686 l2cap_run(); 687 } 688 } 689 690 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){ 691 692 // log_info("l2cap_handle_connection_request for handle %u, psm %u cid %u\n", handle, psm, source_cid); 693 l2cap_service_t *service = l2cap_get_service(psm); 694 if (!service) { 695 // 0x0002 PSM not supported 696 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002); 697 return; 698 } 699 700 hci_connection_t * hci_connection = connection_for_handle( handle ); 701 if (!hci_connection) { 702 // 703 log_error("no hci_connection for handle %u\n", handle); 704 return; 705 } 706 // alloc structure 707 // log_info("l2cap_handle_connection_request register channel\n"); 708 l2cap_channel_t * channel = (l2cap_channel_t*) btstack_memory_l2cap_channel_get(); 709 if (!channel){ 710 // 0x0004 No resources available 711 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004); 712 return; 713 } 714 715 // fill in 716 BD_ADDR_COPY(channel->address, hci_connection->address); 717 channel->psm = psm; 718 channel->handle = handle; 719 channel->connection = service->connection; 720 channel->packet_handler = service->packet_handler; 721 channel->local_cid = l2cap_next_local_cid(); 722 channel->remote_cid = source_cid; 723 channel->local_mtu = service->mtu; 724 channel->remote_mtu = L2CAP_DEFAULT_MTU; 725 channel->packets_granted = 0; 726 channel->remote_sig_id = sig_id; 727 728 // limit local mtu to max acl packet length 729 if (channel->local_mtu > l2cap_max_mtu()) { 730 channel->local_mtu = l2cap_max_mtu(); 731 } 732 733 // set initial state 734 channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT; 735 channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE; 736 737 // add to connections list 738 linked_list_add(&l2cap_channels, (linked_item_t *) channel); 739 740 // emit incoming connection request 741 l2cap_emit_connection_request(channel); 742 } 743 744 void l2cap_accept_connection_internal(uint16_t local_cid){ 745 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 746 if (!channel) { 747 log_error("l2cap_accept_connection_internal called but local_cid 0x%x not found", local_cid); 748 return; 749 } 750 751 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT; 752 753 // process 754 l2cap_run(); 755 } 756 757 void l2cap_decline_connection_internal(uint16_t local_cid, uint8_t reason){ 758 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid); 759 if (!channel) { 760 log_error( "l2cap_decline_connection_internal called but local_cid 0x%x not found", local_cid); 761 return; 762 } 763 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE; 764 channel->reason = reason; 765 l2cap_run(); 766 } 767 768 void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){ 769 770 channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 771 772 // accept the other's configuration options 773 uint16_t end_pos = 4 + READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 774 uint16_t pos = 8; 775 while (pos < end_pos){ 776 uint8_t type = command[pos++]; 777 uint8_t length = command[pos++]; 778 // MTU { type(8): 1, len(8):2, MTU(16) } 779 if ((type & 0x7f) == 1 && length == 2){ 780 channel->remote_mtu = READ_BT_16(command, pos); 781 // log_info("l2cap cid %u, remote mtu %u\n", channel->local_cid, channel->remote_mtu); 782 } 783 pos += length; 784 } 785 } 786 787 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){ 788 // log_info("l2cap_channel_ready_for_open 0x%02x\n", channel->state_var); 789 if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0; 790 if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0; 791 return 1; 792 } 793 794 795 void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){ 796 797 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 798 uint8_t identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 799 uint16_t result = 0; 800 801 log_info("L2CAP signaling handler code %u, state %u\n", code, channel->state); 802 803 // handle DISCONNECT REQUESTS seperately 804 if (code == DISCONNECTION_REQUEST){ 805 switch (channel->state){ 806 case L2CAP_STATE_CONFIG: 807 case L2CAP_STATE_OPEN: 808 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 809 case L2CAP_STATE_WAIT_DISCONNECT: 810 l2cap_handle_disconnect_request(channel, identifier); 811 break; 812 813 default: 814 // ignore in other states 815 break; 816 } 817 return; 818 } 819 820 // @STATEMACHINE(l2cap) 821 switch (channel->state) { 822 823 case L2CAP_STATE_WAIT_CONNECT_RSP: 824 switch (code){ 825 case CONNECTION_RESPONSE: 826 result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 827 switch (result) { 828 case 0: 829 // successful connection 830 channel->remote_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 831 channel->state = L2CAP_STATE_CONFIG; 832 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 833 break; 834 case 1: 835 // connection pending. get some coffee 836 break; 837 default: 838 // channel closed 839 channel->state = L2CAP_STATE_CLOSED; 840 841 // map l2cap connection response result to BTstack status enumeration 842 l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result); 843 844 // drop link key if security block 845 if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){ 846 hci_drop_link_key_for_bd_addr(&channel->address); 847 } 848 849 // discard channel 850 linked_list_remove(&l2cap_channels, (linked_item_t *) channel); 851 btstack_memory_l2cap_channel_free(channel); 852 break; 853 } 854 break; 855 856 default: 857 //@TODO: implement other signaling packets 858 break; 859 } 860 break; 861 862 case L2CAP_STATE_CONFIG: 863 switch (code) { 864 case CONFIGURE_REQUEST: 865 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ); 866 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP); 867 l2cap_signaling_handle_configure_request(channel, command); 868 break; 869 case CONFIGURE_RESPONSE: 870 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP); 871 break; 872 default: 873 break; 874 } 875 if (l2cap_channel_ready_for_open(channel)){ 876 // for open: 877 channel->state = L2CAP_STATE_OPEN; 878 l2cap_emit_channel_opened(channel, 0); 879 l2cap_emit_credits(channel, 1); 880 } 881 break; 882 883 case L2CAP_STATE_WAIT_DISCONNECT: 884 switch (code) { 885 case DISCONNECTION_RESPONSE: 886 l2cap_finialize_channel_close(channel); 887 break; 888 default: 889 //@TODO: implement other signaling packets 890 break; 891 } 892 break; 893 894 case L2CAP_STATE_CLOSED: 895 // @TODO handle incoming requests 896 break; 897 898 case L2CAP_STATE_OPEN: 899 //@TODO: implement other signaling packets, e.g. re-configure 900 break; 901 default: 902 break; 903 } 904 // log_info("new state %u\n", channel->state); 905 } 906 907 908 void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){ 909 910 // get code, signalind identifier and command len 911 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 912 uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 913 914 // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST 915 if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){ 916 return; 917 } 918 919 // general commands without an assigned channel 920 switch(code) { 921 922 case CONNECTION_REQUEST: { 923 uint16_t psm = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 924 uint16_t source_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2); 925 l2cap_handle_connection_request(handle, sig_id, psm, source_cid); 926 return; 927 } 928 929 case ECHO_REQUEST: 930 l2cap_register_signaling_response(handle, code, sig_id, 0); 931 return; 932 933 case INFORMATION_REQUEST: { 934 uint16_t infoType = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 935 l2cap_register_signaling_response(handle, code, sig_id, infoType); 936 return; 937 } 938 939 default: 940 break; 941 } 942 943 944 // Get potential destination CID 945 uint16_t dest_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 946 947 // Find channel for this sig_id and connection handle 948 linked_item_t *it; 949 for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){ 950 l2cap_channel_t * channel = (l2cap_channel_t *) it; 951 if (channel->handle == handle) { 952 if (code & 1) { 953 // match odd commands (responses) by previous signaling identifier 954 if (channel->local_sig_id == sig_id) { 955 l2cap_signaling_handler_channel(channel, command); 956 break; 957 } 958 } else { 959 // match even commands (requests) by local channel id 960 if (channel->local_cid == dest_cid) { 961 l2cap_signaling_handler_channel(channel, command); 962 break; 963 } 964 } 965 } 966 } 967 } 968 969 void l2cap_acl_handler( uint8_t *packet, uint16_t size ){ 970 971 // Get Channel ID 972 uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet); 973 hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet); 974 975 switch (channel_id) { 976 977 case L2CAP_CID_SIGNALING: { 978 979 uint16_t command_offset = 8; 980 while (command_offset < size) { 981 982 // handle signaling commands 983 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]); 984 985 // increment command_offset 986 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + READ_BT_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 987 } 988 break; 989 } 990 991 case L2CAP_CID_ATTRIBUTE_PROTOCOL: 992 if (attribute_protocol_packet_handler) { 993 (*attribute_protocol_packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 994 } 995 break; 996 997 case L2CAP_CID_SECURITY_MANAGER_PROTOCOL: 998 if (security_protocol_packet_handler) { 999 (*security_protocol_packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1000 } 1001 break; 1002 1003 default: { 1004 // Find channel for this channel_id and connection handle 1005 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(channel_id); 1006 if (channel) { 1007 l2cap_dispatch(channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1008 } 1009 break; 1010 } 1011 } 1012 1013 l2cap_run(); 1014 } 1015 1016 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 1017 switch (packet_type) { 1018 case HCI_EVENT_PACKET: 1019 l2cap_event_handler(packet, size); 1020 break; 1021 case HCI_ACL_DATA_PACKET: 1022 l2cap_acl_handler(packet, size); 1023 break; 1024 default: 1025 break; 1026 } 1027 } 1028 1029 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE 1030 void l2cap_finialize_channel_close(l2cap_channel_t *channel){ 1031 channel->state = L2CAP_STATE_CLOSED; 1032 l2cap_emit_channel_closed(channel); 1033 // discard channel 1034 linked_list_remove(&l2cap_channels, (linked_item_t *) channel); 1035 btstack_memory_l2cap_channel_free(channel); 1036 } 1037 1038 l2cap_service_t * l2cap_get_service(uint16_t psm){ 1039 linked_item_t *it; 1040 1041 // close open channels 1042 for (it = (linked_item_t *) l2cap_services; it ; it = it->next){ 1043 l2cap_service_t * service = ((l2cap_service_t *) it); 1044 if ( service->psm == psm){ 1045 return service; 1046 }; 1047 } 1048 return NULL; 1049 } 1050 1051 void l2cap_register_service_internal(void *connection, btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t mtu){ 1052 // check for alread registered psm 1053 // TODO: emit error event 1054 l2cap_service_t *service = l2cap_get_service(psm); 1055 if (service) { 1056 log_error("l2cap_register_service_internal: PSM %u already registered\n", psm); 1057 l2cap_emit_service_registered(connection, L2CAP_SERVICE_ALREADY_REGISTERED, psm); 1058 return; 1059 } 1060 1061 // alloc structure 1062 // TODO: emit error event 1063 service = (l2cap_service_t *) btstack_memory_l2cap_service_get(); 1064 if (!service) { 1065 log_error("l2cap_register_service_internal: no memory for l2cap_service_t\n"); 1066 l2cap_emit_service_registered(connection, BTSTACK_MEMORY_ALLOC_FAILED, psm); 1067 return; 1068 } 1069 1070 // fill in 1071 service->psm = psm; 1072 service->mtu = mtu; 1073 service->connection = connection; 1074 service->packet_handler = packet_handler; 1075 1076 // add to services list 1077 linked_list_add(&l2cap_services, (linked_item_t *) service); 1078 1079 // enable page scan 1080 hci_connectable_control(1); 1081 1082 // done 1083 l2cap_emit_service_registered(connection, 0, psm); 1084 } 1085 1086 void l2cap_unregister_service_internal(void *connection, uint16_t psm){ 1087 l2cap_service_t *service = l2cap_get_service(psm); 1088 if (!service) return; 1089 linked_list_remove(&l2cap_services, (linked_item_t *) service); 1090 btstack_memory_l2cap_service_free(service); 1091 1092 // disable page scan when no services registered 1093 if (!linked_list_empty(&l2cap_services)) return; 1094 hci_connectable_control(0); 1095 } 1096 1097 // 1098 void l2cap_close_connection(void *connection){ 1099 linked_item_t *it; 1100 1101 // close open channels - note to myself: no channel is freed, so no new for fancy iterator tricks 1102 l2cap_channel_t * channel; 1103 for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){ 1104 channel = (l2cap_channel_t *) it; 1105 if (channel->connection == connection) { 1106 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 1107 } 1108 } 1109 1110 // unregister services 1111 it = (linked_item_t *) &l2cap_services; 1112 while (it->next) { 1113 l2cap_service_t * service = (l2cap_service_t *) it->next; 1114 if (service->connection == connection){ 1115 it->next = it->next->next; 1116 btstack_memory_l2cap_service_free(service); 1117 } else { 1118 it = it->next; 1119 } 1120 } 1121 1122 // process 1123 l2cap_run(); 1124 } 1125 1126 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol 1127 void l2cap_register_fixed_channel(btstack_packet_handler_t packet_handler, uint16_t channel_id) { 1128 switch(channel_id){ 1129 case L2CAP_CID_ATTRIBUTE_PROTOCOL: 1130 attribute_protocol_packet_handler = packet_handler; 1131 break; 1132 case L2CAP_CID_SECURITY_MANAGER_PROTOCOL: 1133 security_protocol_packet_handler = packet_handler; 1134 break; 1135 } 1136 } 1137 1138