xref: /btstack/src/l2cap.c (revision 6dca2a0cf979e18e72d5000f085d1b12ddb2111d)
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__ "l2cap.c"
39 
40 /*
41  *  l2cap.c
42  *
43  *  Logical Link Control and Adaption Protocl (L2CAP)
44  *
45  *  Created by Matthias Ringwald on 5/16/09.
46  */
47 
48 #include "l2cap.h"
49 #include "hci.h"
50 #include "hci_dump.h"
51 #include "bluetooth_sdp.h"
52 #include "btstack_debug.h"
53 #include "btstack_event.h"
54 #include "btstack_memory.h"
55 
56 #ifdef ENABLE_LE_DATA_CHANNELS
57 #include "ble/sm.h"
58 #endif
59 
60 #include <stdarg.h>
61 #include <string.h>
62 
63 #include <stdio.h>
64 
65 // nr of buffered acl packets in outgoing queue to get max performance
66 #define NR_BUFFERED_ACL_PACKETS 3
67 
68 // used to cache l2cap rejects, echo, and informational requests
69 #define NR_PENDING_SIGNALING_RESPONSES 3
70 
71 // nr of credits provided to remote if credits fall below watermark
72 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
73 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
74 
75 // offsets for L2CAP SIGNALING COMMANDS
76 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
77 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
78 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
79 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
80 
81 // internal table
82 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL 0
83 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL  1
84 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL 2
85 #define L2CAP_FIXED_CHANNEL_TABLE_SIZE (L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL+1)
86 
87 #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
88 #define L2CAP_USES_CHANNELS
89 #endif
90 
91 // prototypes
92 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
93 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
94 static void l2cap_notify_channel_can_send(void);
95 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
96 #ifdef ENABLE_CLASSIC
97 static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
98 static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
99 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
100 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
101 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
102 static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
103 #endif
104 #ifdef ENABLE_LE_DATA_CHANNELS
105 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
106 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
107 static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid);
108 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
109 static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
110 static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
111 #endif
112 
113 typedef struct l2cap_fixed_channel {
114     btstack_packet_handler_t callback;
115     uint8_t waiting_for_can_send_now;
116 } l2cap_fixed_channel_t;
117 
118 #ifdef ENABLE_CLASSIC
119 static btstack_linked_list_t l2cap_channels;
120 static btstack_linked_list_t l2cap_services;
121 static uint8_t require_security_level2_for_outgoing_sdp;
122 #endif
123 
124 #ifdef ENABLE_LE_DATA_CHANNELS
125 static btstack_linked_list_t l2cap_le_channels;
126 static btstack_linked_list_t l2cap_le_services;
127 #endif
128 
129 // used to cache l2cap rejects, echo, and informational requests
130 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
131 static int signaling_responses_pending;
132 
133 static btstack_packet_callback_registration_t hci_event_callback_registration;
134 static l2cap_fixed_channel_t fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_SIZE];
135 
136 #ifdef ENABLE_BLE
137 // only used for connection parameter update events
138 static btstack_packet_handler_t l2cap_event_packet_handler;
139 #endif
140 
141 static uint16_t l2cap_fixed_channel_table_channel_id_for_index(int index){
142     switch (index){
143         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL:
144             return L2CAP_CID_ATTRIBUTE_PROTOCOL;
145         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL:
146             return L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
147         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL:
148             return L2CAP_CID_CONNECTIONLESS_CHANNEL;
149         default:
150             return 0;
151     }
152 }
153 static int l2cap_fixed_channel_table_index_for_channel_id(uint16_t channel_id){
154     switch (channel_id){
155         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
156             return L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL;
157         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
158             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL;
159         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
160             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL;
161         default:
162             return -1;
163         }
164 }
165 
166 static int l2cap_fixed_channel_table_index_is_le(int index){
167     if (index == L2CAP_CID_CONNECTIONLESS_CHANNEL) return 0;
168     return 1;
169 }
170 
171 void l2cap_init(void){
172     signaling_responses_pending = 0;
173 
174 #ifdef ENABLE_CLASSIC
175     l2cap_channels = NULL;
176     l2cap_services = NULL;
177     require_security_level2_for_outgoing_sdp = 0;
178 #endif
179 
180 #ifdef ENABLE_LE_DATA_CHANNELS
181     l2cap_le_services = NULL;
182     l2cap_le_channels = NULL;
183 #endif
184 
185 #ifdef ENABLE_BLE
186     l2cap_event_packet_handler = NULL;
187 #endif
188     memset(fixed_channels, 0, sizeof(fixed_channels));
189 
190     //
191     // register callback with HCI
192     //
193     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
194     hci_add_event_handler(&hci_event_callback_registration);
195 
196     hci_register_acl_packet_handler(&l2cap_acl_handler);
197 
198 #ifdef ENABLE_CLASSIC
199     gap_connectable_control(0); // no services yet
200 #endif
201 }
202 
203 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
204 #ifdef ENABLE_BLE
205     l2cap_event_packet_handler = handler;
206 #else
207     UNUSED(handler);
208 #endif
209 }
210 
211 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
212     UNUSED(con_handle);
213 
214     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
215     if (index < 0) return;
216     fixed_channels[index].waiting_for_can_send_now = 1;
217     l2cap_notify_channel_can_send();
218 }
219 
220 int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
221     UNUSED(channel_id);
222 
223     return hci_can_send_acl_packet_now(con_handle);
224 }
225 
226 uint8_t *l2cap_get_outgoing_buffer(void){
227     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
228 }
229 
230 int l2cap_reserve_packet_buffer(void){
231     return hci_reserve_packet_buffer();
232 }
233 
234 void l2cap_release_packet_buffer(void){
235     hci_release_packet_buffer();
236 }
237 
238 static void l2cap_setup_header(uint8_t * acl_buffer, hci_con_handle_t con_handle, uint8_t packet_boundary, uint16_t remote_cid, uint16_t len){
239     // 0 - Connection handle : PB=pb : BC=00
240     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
241     // 2 - ACL length
242     little_endian_store_16(acl_buffer, 2,  len + 4);
243     // 4 - L2CAP packet length
244     little_endian_store_16(acl_buffer, 4,  len + 0);
245     // 6 - L2CAP channel DEST
246     little_endian_store_16(acl_buffer, 6,  remote_cid);
247 }
248 
249 // assumption - only on LE connections
250 int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
251 
252     if (!hci_is_packet_buffer_reserved()){
253         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
254         return BTSTACK_ACL_BUFFERS_FULL;
255     }
256 
257     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
258         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
259         return BTSTACK_ACL_BUFFERS_FULL;
260     }
261 
262     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
263 
264     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
265     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
266     // send
267     return hci_send_acl_packet_buffer(len+8);
268 }
269 
270 // assumption - only on LE connections
271 int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
272 
273     if (!hci_can_send_acl_packet_now(con_handle)){
274         log_info("l2cap_send cid 0x%02x, cannot send", cid);
275         return BTSTACK_ACL_BUFFERS_FULL;
276     }
277 
278     hci_reserve_packet_buffer();
279     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
280 
281     memcpy(&acl_buffer[8], data, len);
282 
283     return l2cap_send_prepared_connectionless(con_handle, cid, len);
284 }
285 
286 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
287     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
288     uint8_t event[4];
289     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
290     event[1] = sizeof(event) - 2;
291     little_endian_store_16(event, 2, channel);
292     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
293     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
294 }
295 
296 #ifdef L2CAP_USES_CHANNELS
297 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
298     (* (channel->packet_handler))(type, channel->local_cid, data, size);
299 }
300 
301 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
302     uint8_t event[4];
303     event[0] = event_code;
304     event[1] = sizeof(event) - 2;
305     little_endian_store_16(event, 2, channel->local_cid);
306     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
307     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
308 }
309 #endif
310 
311 #ifdef ENABLE_CLASSIC
312 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
313     log_info("L2CAP_EVENT_CHANNEL_OPENED status 0x%x addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u, flush_timeout %u",
314              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
315              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
316     uint8_t event[24];
317     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
318     event[1] = sizeof(event) - 2;
319     event[2] = status;
320     reverse_bd_addr(channel->address, &event[3]);
321     little_endian_store_16(event,  9, channel->con_handle);
322     little_endian_store_16(event, 11, channel->psm);
323     little_endian_store_16(event, 13, channel->local_cid);
324     little_endian_store_16(event, 15, channel->remote_cid);
325     little_endian_store_16(event, 17, channel->local_mtu);
326     little_endian_store_16(event, 19, channel->remote_mtu);
327     little_endian_store_16(event, 21, channel->flush_timeout);
328     event[23] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
329     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
330     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
331 }
332 
333 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
334     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
335     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
336 }
337 
338 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
339     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
340              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
341     uint8_t event[16];
342     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
343     event[1] = sizeof(event) - 2;
344     reverse_bd_addr(channel->address, &event[2]);
345     little_endian_store_16(event,  8, channel->con_handle);
346     little_endian_store_16(event, 10, channel->psm);
347     little_endian_store_16(event, 12, channel->local_cid);
348     little_endian_store_16(event, 14, channel->remote_cid);
349     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
350     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
351 }
352 
353 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
354     btstack_linked_list_iterator_t it;
355     btstack_linked_list_iterator_init(&it, &l2cap_channels);
356     while (btstack_linked_list_iterator_has_next(&it)){
357         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
358         if ( channel->local_cid == local_cid) {
359             return channel;
360         }
361     }
362     return NULL;
363 }
364 
365 ///
366 
367 void l2cap_request_can_send_now_event(uint16_t local_cid){
368     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
369     if (!channel) return;
370     channel->waiting_for_can_send_now = 1;
371     l2cap_notify_channel_can_send();
372 }
373 
374 int  l2cap_can_send_packet_now(uint16_t local_cid){
375     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
376     if (!channel) return 0;
377     return hci_can_send_acl_packet_now(channel->con_handle);
378 }
379 
380 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
381     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
382     if (!channel) return 0;
383     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
384 }
385 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
386     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
387     if (channel) {
388         return channel->remote_mtu;
389     }
390     return 0;
391 }
392 
393 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
394     btstack_linked_list_iterator_t it;
395     btstack_linked_list_iterator_init(&it, &l2cap_channels);
396     while (btstack_linked_list_iterator_has_next(&it)){
397         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
398         if ( &channel->rtx == ts) {
399             return channel;
400         }
401     }
402     return NULL;
403 }
404 
405 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
406     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
407     if (!channel) return;
408 
409     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
410 
411     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
412     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
413     // notify client
414     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
415 
416     // discard channel
417     // no need to stop timer here, it is removed from list during timer callback
418     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
419     btstack_memory_l2cap_channel_free(channel);
420 }
421 
422 static void l2cap_stop_rtx(l2cap_channel_t * channel){
423     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
424     btstack_run_loop_remove_timer(&channel->rtx);
425 }
426 
427 static void l2cap_start_rtx(l2cap_channel_t * channel){
428     l2cap_stop_rtx(channel);
429     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
430     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
431     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
432     btstack_run_loop_add_timer(&channel->rtx);
433 }
434 
435 static void l2cap_start_ertx(l2cap_channel_t * channel){
436     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
437     l2cap_stop_rtx(channel);
438     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
439     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
440     btstack_run_loop_add_timer(&channel->rtx);
441 }
442 
443 void l2cap_require_security_level_2_for_outgoing_sdp(void){
444     require_security_level2_for_outgoing_sdp = 1;
445 }
446 
447 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
448     return (psm == BLUETOOTH_PROTOCOL_SDP) && (!require_security_level2_for_outgoing_sdp);
449 }
450 
451 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
452     if (!hci_can_send_acl_packet_now(handle)){
453         log_info("l2cap_send_signaling_packet, cannot send");
454         return BTSTACK_ACL_BUFFERS_FULL;
455     }
456 
457     // log_info("l2cap_send_signaling_packet type %u", cmd);
458     hci_reserve_packet_buffer();
459     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
460     va_list argptr;
461     va_start(argptr, identifier);
462     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
463     va_end(argptr);
464     // log_info("l2cap_send_signaling_packet con %u!", handle);
465     return hci_send_acl_packet_buffer(len);
466 }
467 
468 // assumption - only on Classic connections
469 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
470 
471     if (!hci_is_packet_buffer_reserved()){
472         log_error("l2cap_send_prepared called without reserving packet first");
473         return BTSTACK_ACL_BUFFERS_FULL;
474     }
475 
476     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
477     if (!channel) {
478         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
479         return -1;   // TODO: define error
480     }
481 
482     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
483         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
484         return BTSTACK_ACL_BUFFERS_FULL;
485     }
486 
487     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
488 
489     // set non-flushable packet boundary flag if supported on Controller
490     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
491     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
492     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len);
493     // send
494     return hci_send_acl_packet_buffer(len+8);
495 }
496 
497 // assumption - only on Classic connections
498 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
499 
500     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
501     if (!channel) {
502         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
503         return -1;   // TODO: define error
504     }
505 
506     if (len > channel->remote_mtu){
507         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
508         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
509     }
510 
511     if (!hci_can_send_acl_packet_now(channel->con_handle)){
512         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
513         return BTSTACK_ACL_BUFFERS_FULL;
514     }
515 
516     hci_reserve_packet_buffer();
517     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
518 
519     memcpy(&acl_buffer[8], data, len);
520 
521     return l2cap_send_prepared(local_cid, len);
522 }
523 
524 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
525     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
526 }
527 
528 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
529     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
530 }
531 
532 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
533     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
534 }
535 #endif
536 
537 
538 #ifdef ENABLE_BLE
539 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
540 
541     if (!hci_can_send_acl_packet_now(handle)){
542         log_info("l2cap_send_le_signaling_packet, cannot send");
543         return BTSTACK_ACL_BUFFERS_FULL;
544     }
545 
546     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
547     hci_reserve_packet_buffer();
548     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
549     va_list argptr;
550     va_start(argptr, identifier);
551     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
552     va_end(argptr);
553     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
554     return hci_send_acl_packet_buffer(len);
555 }
556 #endif
557 
558 uint16_t l2cap_max_mtu(void){
559     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
560 }
561 
562 uint16_t l2cap_max_le_mtu(void){
563     return l2cap_max_mtu();
564 }
565 
566 static uint16_t l2cap_setup_options(l2cap_channel_t * channel, uint8_t * config_options){
567     int send_retransmission_and_flow_control_option = 0;
568     int options_size;
569 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
570     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
571         send_retransmission_and_flow_control_option = 1;
572     }
573 #endif
574     if (send_retransmission_and_flow_control_option){
575 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
576         config_options[0] = 0x04;   // RETRANSMISSION AND FLOW CONTROL OPTION
577         config_options[1] = 9;      // length
578         config_options[2] = (uint8_t) channel->mode;
579         config_options[3] = 1;      // TxWindows size
580         config_options[4] = 1;      // max retransmit
581         little_endian_store_16( config_options, 5, 100); // Retransmission timeout: 100 ms
582         little_endian_store_16( config_options, 7, 300); // Monitor timeout: 300 ms
583         little_endian_store_16( config_options, 9, channel->local_mtu); // Max PDU size // TODO: use real MTU
584         options_size = 11;
585 #endif
586     } else {
587         config_options[0] = 1; // MTU
588         config_options[1] = 2; // len param
589         little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
590         options_size = 4;
591     }
592     return options_size;
593 }
594 
595 // MARK: L2CAP_RUN
596 // process outstanding signaling tasks
597 static void l2cap_run(void){
598 
599     // log_info("l2cap_run: entered");
600 
601     // check pending signaling responses
602     while (signaling_responses_pending){
603 
604         hci_con_handle_t handle = signaling_responses[0].handle;
605 
606         if (!hci_can_send_acl_packet_now(handle)) break;
607 
608         uint8_t  sig_id        = signaling_responses[0].sig_id;
609         uint8_t  response_code = signaling_responses[0].code;
610         uint16_t infoType      = signaling_responses[0].data;  // INFORMATION_REQUEST
611         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
612 #ifdef ENABLE_CLASSIC
613         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
614 #endif
615         UNUSED(infoType);
616 
617         // remove first item before sending (to avoid sending response mutliple times)
618         signaling_responses_pending--;
619         int i;
620         for (i=0; i < signaling_responses_pending; i++){
621             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
622         }
623 
624         switch (response_code){
625 #ifdef ENABLE_CLASSIC
626             case CONNECTION_REQUEST:
627                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
628                 // also disconnect if result is 0x0003 - security blocked
629                 if (result == 0x0003){
630                     hci_disconnect_security_block(handle);
631                 }
632                 break;
633             case ECHO_REQUEST:
634                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
635                 break;
636             case INFORMATION_REQUEST:
637                 switch (infoType){
638                     case 1: { // Connectionless MTU
639                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
640                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
641                         }
642                         break;
643                     case 2: { // Extended Features Supported
644                             // extended features request supported, features: fixed channels, unicast connectionless data reception
645                             uint32_t features = 0x280;
646 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
647                             features |= 0x0008;
648 #endif
649                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
650                         }
651                         break;
652                     case 3: { // Fixed Channels Supported
653                             uint8_t map[8];
654                             memset(map, 0, 8);
655                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
656                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
657                         }
658                         break;
659                     default:
660                         // all other types are not supported
661                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
662                         break;
663                 }
664                 break;
665             case COMMAND_REJECT:
666                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
667                 break;
668 #endif
669 #ifdef ENABLE_BLE
670             case LE_CREDIT_BASED_CONNECTION_REQUEST:
671                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
672                 break;
673             case COMMAND_REJECT_LE:
674                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
675                 break;
676 #endif
677             default:
678                 // should not happen
679                 break;
680         }
681     }
682 
683     btstack_linked_list_iterator_t it;
684     UNUSED(it);
685 
686 #ifdef ENABLE_CLASSIC
687     uint8_t  config_options[10];
688     btstack_linked_list_iterator_init(&it, &l2cap_channels);
689     while (btstack_linked_list_iterator_has_next(&it)){
690 
691         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
692         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
693         switch (channel->state){
694 
695             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
696             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
697                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
698                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
699                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
700                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
701                 }
702                 break;
703 
704             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
705                 if (!hci_can_send_command_packet_now()) break;
706                 // send connection request - set state first
707                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
708                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
709                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
710                 break;
711 
712             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
713                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
714                 channel->state = L2CAP_STATE_INVALID;
715                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
716                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
717                 l2cap_stop_rtx(channel);
718                 btstack_linked_list_iterator_remove(&it);
719                 btstack_memory_l2cap_channel_free(channel);
720                 break;
721 
722             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
723                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
724                 channel->state = L2CAP_STATE_CONFIG;
725                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
726                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
727                 break;
728 
729             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
730                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
731                 // success, start l2cap handshake
732                 channel->local_sig_id = l2cap_next_sig_id();
733                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
734                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
735                 l2cap_start_rtx(channel);
736                 break;
737 
738             case L2CAP_STATE_CONFIG:
739                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
740                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
741                     uint16_t flags = 0;
742                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
743                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
744                         flags = 1;
745                     } else {
746                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
747                     }
748                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
749                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
750                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
751                         uint16_t options_size = l2cap_setup_options(channel, config_options);
752                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, options_size, &config_options);
753                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
754                     } else {
755                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 0, NULL);
756                     }
757                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
758                 }
759                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
760                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
761                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
762                     channel->local_sig_id = l2cap_next_sig_id();
763                     uint16_t options_size = l2cap_setup_options(channel, config_options);
764                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
765                     l2cap_start_rtx(channel);
766                 }
767                 if (l2cap_channel_ready_for_open(channel)){
768                     channel->state = L2CAP_STATE_OPEN;
769                     l2cap_emit_channel_opened(channel, 0);  // success
770                 }
771                 break;
772 
773             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
774                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
775                 channel->state = L2CAP_STATE_INVALID;
776                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
777                 // we don't start an RTX timer for a disconnect - there's no point in closing the channel if the other side doesn't respond :)
778                 l2cap_finialize_channel_close(channel);  // -- remove from list
779                 break;
780 
781             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
782                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
783                 channel->local_sig_id = l2cap_next_sig_id();
784                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
785                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
786                 break;
787             default:
788                 break;
789         }
790     }
791 #endif
792 
793 #ifdef ENABLE_LE_DATA_CHANNELS
794     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
795     while (btstack_linked_list_iterator_has_next(&it)){
796         uint8_t  * acl_buffer;
797         uint8_t  * l2cap_payload;
798         uint16_t pos;
799         uint16_t payload_size;
800         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
801         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
802         switch (channel->state){
803             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
804                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
805                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
806                 // le psm, source cid, mtu, mps, initial credits
807                 channel->local_sig_id = l2cap_next_sig_id();
808                 channel->credits_incoming =  channel->new_credits_incoming;
809                 channel->new_credits_incoming = 0;
810                 l2cap_send_le_signaling_packet( channel->con_handle, LE_CREDIT_BASED_CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid, channel->local_mtu, 23, channel->credits_incoming);
811                 break;
812             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
813                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
814                 // TODO: support larger MPS
815                 channel->state = L2CAP_STATE_OPEN;
816                 channel->credits_incoming =  channel->new_credits_incoming;
817                 channel->new_credits_incoming = 0;
818                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->local_mtu, 23, channel->credits_incoming, 0);
819                 // notify client
820                 l2cap_emit_le_channel_opened(channel, 0);
821                 break;
822             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
823                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
824                 channel->state = L2CAP_STATE_INVALID;
825                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
826                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
827                 l2cap_stop_rtx(channel);
828                 btstack_linked_list_iterator_remove(&it);
829                 btstack_memory_l2cap_channel_free(channel);
830                 break;
831             case L2CAP_STATE_OPEN:
832                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
833 
834                 // send credits
835                 if (channel->new_credits_incoming){
836                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
837                     channel->local_sig_id = l2cap_next_sig_id();
838                     uint16_t new_credits = channel->new_credits_incoming;
839                     channel->new_credits_incoming = 0;
840                     channel->credits_incoming += new_credits;
841                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
842                     break;
843                 }
844 
845                 // send data
846                 if (!channel->send_sdu_buffer) break;
847                 if (!channel->credits_outgoing) break;
848 
849                 // send part of SDU
850                 hci_reserve_packet_buffer();
851                 acl_buffer = hci_get_outgoing_packet_buffer();
852                 l2cap_payload = acl_buffer + 8;
853                 pos = 0;
854                 if (!channel->send_sdu_pos){
855                     // store SDU len
856                     channel->send_sdu_pos += 2;
857                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
858                     pos += 2;
859                 }
860                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
861                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
862                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
863                 pos += payload_size;
864                 channel->send_sdu_pos += payload_size;
865                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
866                 // done
867 
868                 channel->credits_outgoing--;
869 
870                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
871                     channel->send_sdu_buffer = NULL;
872                     // send done event
873                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
874                     // inform about can send now
875                     l2cap_le_notify_channel_can_send(channel);
876                 }
877                 hci_send_acl_packet_buffer(8 + pos);
878                 break;
879             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
880                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
881                 channel->local_sig_id = l2cap_next_sig_id();
882                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
883                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
884                 break;
885             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
886                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
887                 channel->state = L2CAP_STATE_INVALID;
888                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
889                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
890                 break;
891             default:
892                 break;
893         }
894     }
895 #endif
896 
897 #ifdef ENABLE_BLE
898     // send l2cap con paramter update if necessary
899     hci_connections_get_iterator(&it);
900     while(btstack_linked_list_iterator_has_next(&it)){
901         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
902         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
903         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
904         switch (connection->le_con_parameter_update_state){
905             case CON_PARAMETER_UPDATE_SEND_REQUEST:
906                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
907                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
908                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
909                 break;
910             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
911                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
912                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
913                 break;
914             case CON_PARAMETER_UPDATE_DENY:
915                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
916                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
917                 break;
918             default:
919                 break;
920         }
921     }
922 #endif
923 
924     // log_info("l2cap_run: exit");
925 }
926 
927 #ifdef ENABLE_CLASSIC
928 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
929     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
930         log_info("l2cap_handle_connection_complete expected state");
931         // success, start l2cap handshake
932         channel->con_handle = con_handle;
933         // check remote SSP feature first
934         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
935     }
936 }
937 
938 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
939     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
940 
941     // we have been waiting for remote supported features, if both support SSP,
942     log_info("l2cap received remote supported features, sec_level_0_allowed for psm %u = %u", channel->psm, l2cap_security_level_0_allowed_for_PSM(channel->psm));
943     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
944         // request security level 2
945         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
946         gap_request_security_level(channel->con_handle, LEVEL_2);
947         return;
948     }
949     // fine, go ahead
950     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
951 }
952 #endif
953 
954 #ifdef L2CAP_USES_CHANNELS
955 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, bd_addr_t address, bd_addr_type_t address_type,
956     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
957 
958     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
959     if (!channel) {
960         return NULL;
961     }
962 
963      // Init memory (make valgrind happy)
964     memset(channel, 0, sizeof(l2cap_channel_t));
965 
966     // fill in
967     channel->packet_handler = packet_handler;
968     bd_addr_copy(channel->address, address);
969     channel->address_type = address_type;
970     channel->psm = psm;
971     channel->local_mtu  = local_mtu;
972     channel->remote_mtu = L2CAP_MINIMAL_MTU;
973     channel->required_security_level = security_level;
974 
975     //
976     channel->local_cid = l2cap_next_local_cid();
977     channel->con_handle = 0;
978 
979     // set initial state
980     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
981     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
982     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
983     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
984     return channel;
985 }
986 #endif
987 
988 #ifdef ENABLE_CLASSIC
989 
990 /**
991  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
992  * @param packet_handler
993  * @param address
994  * @param psm
995  * @param mtu
996  * @param local_cid
997  */
998 
999 uint8_t l2cap_create_channel(btstack_packet_handler_t channel_packet_handler, bd_addr_t address, uint16_t psm, uint16_t mtu, uint16_t * out_local_cid){
1000     // limit MTU to the size of our outtgoing HCI buffer
1001     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1002 
1003     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u -> local mtu %u", bd_addr_to_str(address), psm, mtu, local_mtu);
1004 
1005     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1006     if (!channel) {
1007         return BTSTACK_MEMORY_ALLOC_FAILED;
1008     }
1009 
1010     // add to connections list
1011     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1012 
1013     // store local_cid
1014     if (out_local_cid){
1015        *out_local_cid = channel->local_cid;
1016     }
1017 
1018     // check if hci connection is already usable
1019     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
1020     if (conn){
1021         log_info("l2cap_create_channel, hci connection already exists");
1022         l2cap_handle_connection_complete(conn->con_handle, channel);
1023         // check if remote supported fearures are already received
1024         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1025             l2cap_handle_remote_supported_features_received(channel);
1026         }
1027     }
1028 
1029     l2cap_run();
1030 
1031     return 0;
1032 }
1033 
1034 void
1035 l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1036     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1037     // find channel for local_cid
1038     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1039     if (channel) {
1040         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1041     }
1042     // process
1043     l2cap_run();
1044 }
1045 
1046 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1047     btstack_linked_list_iterator_t it;
1048     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1049     while (btstack_linked_list_iterator_has_next(&it)){
1050         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1051         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1052         // channel for this address found
1053         switch (channel->state){
1054             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1055             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1056                 // failure, forward error code
1057                 l2cap_emit_channel_opened(channel, status);
1058                 // discard channel
1059                 l2cap_stop_rtx(channel);
1060                 btstack_linked_list_iterator_remove(&it);
1061                 btstack_memory_l2cap_channel_free(channel);
1062                 break;
1063             default:
1064                 break;
1065         }
1066     }
1067 }
1068 
1069 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1070     btstack_linked_list_iterator_t it;
1071     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1072     while (btstack_linked_list_iterator_has_next(&it)){
1073         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1074         if ( ! bd_addr_cmp( channel->address, address) ){
1075             l2cap_handle_connection_complete(handle, channel);
1076         }
1077     }
1078     // process
1079     l2cap_run();
1080 }
1081 #endif
1082 
1083 static void l2cap_notify_channel_can_send(void){
1084 
1085 #ifdef ENABLE_CLASSIC
1086     btstack_linked_list_iterator_t it;
1087     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1088     while (btstack_linked_list_iterator_has_next(&it)){
1089         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1090         if (!channel->waiting_for_can_send_now) continue;
1091         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1092         channel->waiting_for_can_send_now = 0;
1093         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
1094     }
1095 #endif
1096 
1097     int i;
1098     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1099         if (!fixed_channels[i].callback) continue;
1100         if (!fixed_channels[i].waiting_for_can_send_now) continue;
1101         int can_send = 0;
1102         if (l2cap_fixed_channel_table_index_is_le(i)){
1103 #ifdef ENABLE_BLE
1104             can_send = hci_can_send_acl_le_packet_now();
1105 #endif
1106         } else {
1107 #ifdef ENABLE_CLASSIC
1108             can_send = hci_can_send_acl_classic_packet_now();
1109 #endif
1110         }
1111         if (!can_send) continue;
1112         fixed_channels[i].waiting_for_can_send_now = 0;
1113         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
1114     }
1115 }
1116 
1117 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1118 
1119     UNUSED(packet_type);
1120     UNUSED(cid);
1121     UNUSED(size);
1122 
1123     bd_addr_t address;
1124     hci_con_handle_t handle;
1125     int hci_con_used;
1126     btstack_linked_list_iterator_t it;
1127 
1128     // avoid unused warnings
1129     UNUSED(address);
1130     UNUSED(hci_con_used);
1131     UNUSED(it);
1132     UNUSED(handle);
1133 
1134     switch(hci_event_packet_get_type(packet)){
1135 
1136         // Notify channel packet handler if they can send now
1137         case HCI_EVENT_TRANSPORT_PACKET_SENT:
1138         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
1139             l2cap_run();    // try sending signaling packets first
1140             l2cap_notify_channel_can_send();
1141             break;
1142 
1143         case HCI_EVENT_COMMAND_STATUS:
1144             l2cap_run();    // try sending signaling packets first
1145             break;
1146 
1147 #ifdef ENABLE_CLASSIC
1148         // handle connection complete events
1149         case HCI_EVENT_CONNECTION_COMPLETE:
1150             reverse_bd_addr(&packet[5], address);
1151             if (packet[2] == 0){
1152                 handle = little_endian_read_16(packet, 3);
1153                 l2cap_handle_connection_success_for_addr(address, handle);
1154             } else {
1155                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1156             }
1157             break;
1158 
1159         // handle successful create connection cancel command
1160         case HCI_EVENT_COMMAND_COMPLETE:
1161             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1162                 if (packet[5] == 0){
1163                     reverse_bd_addr(&packet[6], address);
1164                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1165                     l2cap_handle_connection_failed_for_addr(address, 0x16);
1166                 }
1167             }
1168             l2cap_run();    // try sending signaling packets first
1169             break;
1170 #endif
1171 
1172         // handle disconnection complete events
1173         case HCI_EVENT_DISCONNECTION_COMPLETE:
1174             // send l2cap disconnect events for all channels on this handle and free them
1175 #ifdef ENABLE_CLASSIC
1176             handle = little_endian_read_16(packet, 3);
1177             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1178             while (btstack_linked_list_iterator_has_next(&it)){
1179                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1180                 if (channel->con_handle != handle) continue;
1181                 l2cap_emit_channel_closed(channel);
1182                 l2cap_stop_rtx(channel);
1183                 btstack_linked_list_iterator_remove(&it);
1184                 btstack_memory_l2cap_channel_free(channel);
1185             }
1186 #endif
1187 #ifdef ENABLE_LE_DATA_CHANNELS
1188             handle = little_endian_read_16(packet, 3);
1189             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1190             while (btstack_linked_list_iterator_has_next(&it)){
1191                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1192                 if (channel->con_handle != handle) continue;
1193                 l2cap_emit_channel_closed(channel);
1194                 btstack_linked_list_iterator_remove(&it);
1195                 btstack_memory_l2cap_channel_free(channel);
1196             }
1197 #endif
1198             break;
1199 
1200         // HCI Connection Timeouts
1201 #ifdef ENABLE_CLASSIC
1202         case L2CAP_EVENT_TIMEOUT_CHECK:
1203             handle = little_endian_read_16(packet, 2);
1204             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
1205             if (hci_authentication_active_for_handle(handle)) break;
1206             hci_con_used = 0;
1207             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1208             while (btstack_linked_list_iterator_has_next(&it)){
1209                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1210                 if (channel->con_handle != handle) continue;
1211                 hci_con_used = 1;
1212                 break;
1213             }
1214             if (hci_con_used) break;
1215             if (!hci_can_send_command_packet_now()) break;
1216             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1217             break;
1218 
1219         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1220             handle = little_endian_read_16(packet, 3);
1221             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1222             while (btstack_linked_list_iterator_has_next(&it)){
1223                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1224                 if (channel->con_handle != handle) continue;
1225                 l2cap_handle_remote_supported_features_received(channel);
1226                 break;
1227             }
1228             break;
1229 
1230         case GAP_EVENT_SECURITY_LEVEL:
1231             handle = little_endian_read_16(packet, 2);
1232             log_info("l2cap - security level update");
1233             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1234             while (btstack_linked_list_iterator_has_next(&it)){
1235                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1236                 if (channel->con_handle != handle) continue;
1237 
1238                 log_info("l2cap - state %u", channel->state);
1239 
1240                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
1241                 gap_security_level_t required_level = channel->required_security_level;
1242 
1243                 switch (channel->state){
1244                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1245                         if (actual_level >= required_level){
1246                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
1247                             l2cap_emit_incoming_connection(channel);
1248                         } else {
1249                             channel->reason = 0x0003; // security block
1250                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1251                         }
1252                         break;
1253 
1254                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
1255                         if (actual_level >= required_level){
1256                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
1257                         } else {
1258                             // disconnnect, authentication not good enough
1259                             hci_disconnect_security_block(handle);
1260                         }
1261                         break;
1262 
1263                     default:
1264                         break;
1265                 }
1266             }
1267             break;
1268 #endif
1269 
1270         default:
1271             break;
1272     }
1273 
1274     l2cap_run();
1275 }
1276 
1277 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
1278     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
1279     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
1280         signaling_responses[signaling_responses_pending].handle = handle;
1281         signaling_responses[signaling_responses_pending].code = code;
1282         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1283         signaling_responses[signaling_responses_pending].cid = cid;
1284         signaling_responses[signaling_responses_pending].data = data;
1285         signaling_responses_pending++;
1286         l2cap_run();
1287     }
1288 }
1289 
1290 #ifdef ENABLE_CLASSIC
1291 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
1292     channel->remote_sig_id = identifier;
1293     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1294     l2cap_run();
1295 }
1296 
1297 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1298 
1299     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1300     l2cap_service_t *service = l2cap_get_service(psm);
1301     if (!service) {
1302         // 0x0002 PSM not supported
1303         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1304         return;
1305     }
1306 
1307     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1308     if (!hci_connection) {
1309         //
1310         log_error("no hci_connection for handle %u", handle);
1311         return;
1312     }
1313 
1314     // alloc structure
1315     // log_info("l2cap_handle_connection_request register channel");
1316     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1317     psm, service->mtu, service->required_security_level);
1318     if (!channel){
1319         // 0x0004 No resources available
1320         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
1321         return;
1322     }
1323 
1324     channel->con_handle = handle;
1325     channel->remote_cid = source_cid;
1326     channel->remote_sig_id = sig_id;
1327 
1328     // limit local mtu to max acl packet length - l2cap header
1329     if (channel->local_mtu > l2cap_max_mtu()) {
1330         channel->local_mtu = l2cap_max_mtu();
1331     }
1332 
1333     // set initial state
1334     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1335     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
1336 
1337     // add to connections list
1338     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1339 
1340     // assert security requirements
1341     gap_request_security_level(handle, channel->required_security_level);
1342 }
1343 
1344 void l2cap_accept_connection(uint16_t local_cid){
1345     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1346     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1347     if (!channel) {
1348         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1349         return;
1350     }
1351 
1352 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1353     // configure L2CAP Basic mode
1354     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
1355 #endif
1356 
1357     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1358 
1359     // process
1360     l2cap_run();
1361 }
1362 
1363 
1364 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1365 void l2cap_accept_ertm_connection(uint16_t local_cid){
1366     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
1367     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1368     if (!channel) {
1369         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1370         return;
1371     }
1372 
1373     // configure L2CAP ERTM
1374     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
1375 
1376     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1377 
1378     // process
1379     l2cap_run();
1380 }
1381 #endif
1382 
1383 
1384 void l2cap_decline_connection(uint16_t local_cid){
1385     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1386     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1387     if (!channel) {
1388         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1389         return;
1390     }
1391     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1392     channel->reason = 0x04; // no resources available
1393     l2cap_run();
1394 }
1395 
1396 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1397 
1398     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1399 
1400     uint16_t flags = little_endian_read_16(command, 6);
1401     if (flags & 1) {
1402         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1403     }
1404 
1405     // accept the other's configuration options
1406     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1407     uint16_t pos     = 8;
1408     while (pos < end_pos){
1409         uint8_t option_hint = command[pos] >> 7;
1410         uint8_t option_type = command[pos] & 0x7f;
1411         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
1412         pos++;
1413         uint8_t length = command[pos++];
1414         // MTU { type(8): 1, len(8):2, MTU(16) }
1415         if (option_type == 1 && length == 2){
1416             channel->remote_mtu = little_endian_read_16(command, pos);
1417             if (channel->remote_mtu > l2cap_max_mtu()){
1418                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
1419                 channel->remote_mtu = l2cap_max_mtu();
1420             }
1421             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1422         }
1423         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
1424         if (option_type == 2 && length == 2){
1425             channel->flush_timeout = little_endian_read_16(command, pos);
1426         }
1427 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1428         // Retransmission and Flow Control Option
1429         if (option_type == 4 && length == 9){
1430             // TODO store and evaluate configuration
1431             // TODO Use different enum name
1432             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1433         }
1434 #endif
1435         // check for unknown options
1436         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1437             log_info("l2cap cid %u, unknown options", channel->local_cid);
1438             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
1439         }
1440         pos += length;
1441     }
1442 }
1443 
1444 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
1445     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
1446     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
1447     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1448     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1449     if (channel->state == L2CAP_STATE_OPEN) return 0;
1450     return 1;
1451 }
1452 
1453 
1454 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
1455 
1456     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1457     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1458     uint16_t result = 0;
1459 
1460     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1461 
1462     // handle DISCONNECT REQUESTS seperately
1463     if (code == DISCONNECTION_REQUEST){
1464         switch (channel->state){
1465             case L2CAP_STATE_CONFIG:
1466             case L2CAP_STATE_OPEN:
1467             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1468             case L2CAP_STATE_WAIT_DISCONNECT:
1469                 l2cap_handle_disconnect_request(channel, identifier);
1470                 break;
1471 
1472             default:
1473                 // ignore in other states
1474                 break;
1475         }
1476         return;
1477     }
1478 
1479     // @STATEMACHINE(l2cap)
1480     switch (channel->state) {
1481 
1482         case L2CAP_STATE_WAIT_CONNECT_RSP:
1483             switch (code){
1484                 case CONNECTION_RESPONSE:
1485                     l2cap_stop_rtx(channel);
1486                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1487                     switch (result) {
1488                         case 0:
1489                             // successful connection
1490                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1491                             channel->state = L2CAP_STATE_CONFIG;
1492                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1493                             break;
1494                         case 1:
1495                             // connection pending. get some coffee, but start the ERTX
1496                             l2cap_start_ertx(channel);
1497                             break;
1498                         default:
1499                             // channel closed
1500                             channel->state = L2CAP_STATE_CLOSED;
1501                             // map l2cap connection response result to BTstack status enumeration
1502                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1503 
1504                             // drop link key if security block
1505                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
1506                                 gap_drop_link_key_for_bd_addr(channel->address);
1507                             }
1508 
1509                             // discard channel
1510                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1511                             btstack_memory_l2cap_channel_free(channel);
1512                             break;
1513                     }
1514                     break;
1515 
1516                 default:
1517                     //@TODO: implement other signaling packets
1518                     break;
1519             }
1520             break;
1521 
1522         case L2CAP_STATE_CONFIG:
1523             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1524             switch (code) {
1525                 case CONFIGURE_REQUEST:
1526                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1527                     l2cap_signaling_handle_configure_request(channel, command);
1528                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
1529                         // only done if continuation not set
1530                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
1531                     }
1532                     break;
1533                 case CONFIGURE_RESPONSE:
1534                     l2cap_stop_rtx(channel);
1535                     switch (result){
1536                         case 0: // success
1537                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
1538                             break;
1539                         case 4: // pending
1540                             l2cap_start_ertx(channel);
1541                             break;
1542                         default:
1543                             // retry on negative result
1544                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1545                             break;
1546                     }
1547                     break;
1548                 default:
1549                     break;
1550             }
1551             if (l2cap_channel_ready_for_open(channel)){
1552                 // for open:
1553                 channel->state = L2CAP_STATE_OPEN;
1554                 l2cap_emit_channel_opened(channel, 0);
1555             }
1556             break;
1557 
1558         case L2CAP_STATE_WAIT_DISCONNECT:
1559             switch (code) {
1560                 case DISCONNECTION_RESPONSE:
1561                     l2cap_finialize_channel_close(channel);
1562                     break;
1563                 default:
1564                     //@TODO: implement other signaling packets
1565                     break;
1566             }
1567             break;
1568 
1569         case L2CAP_STATE_CLOSED:
1570             // @TODO handle incoming requests
1571             break;
1572 
1573         case L2CAP_STATE_OPEN:
1574             //@TODO: implement other signaling packets, e.g. re-configure
1575             break;
1576         default:
1577             break;
1578     }
1579     // log_info("new state %u", channel->state);
1580 }
1581 
1582 
1583 static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
1584 
1585     // get code, signalind identifier and command len
1586     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1587     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1588 
1589     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
1590     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
1591         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
1592         return;
1593     }
1594 
1595     // general commands without an assigned channel
1596     switch(code) {
1597 
1598         case CONNECTION_REQUEST: {
1599             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1600             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
1601             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
1602             return;
1603         }
1604 
1605         case ECHO_REQUEST:
1606             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
1607             return;
1608 
1609         case INFORMATION_REQUEST: {
1610             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1611             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
1612             return;
1613         }
1614 
1615         default:
1616             break;
1617     }
1618 
1619 
1620     // Get potential destination CID
1621     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1622 
1623     // Find channel for this sig_id and connection handle
1624     btstack_linked_list_iterator_t it;
1625     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1626     while (btstack_linked_list_iterator_has_next(&it)){
1627         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1628         if (channel->con_handle != handle) continue;
1629         if (code & 1) {
1630             // match odd commands (responses) by previous signaling identifier
1631             if (channel->local_sig_id == sig_id) {
1632                 l2cap_signaling_handler_channel(channel, command);
1633                 break;
1634             }
1635         } else {
1636             // match even commands (requests) by local channel id
1637             if (channel->local_cid == dest_cid) {
1638                 l2cap_signaling_handler_channel(channel, command);
1639                 break;
1640             }
1641         }
1642     }
1643 }
1644 #endif
1645 
1646 #ifdef ENABLE_BLE
1647 
1648 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
1649     uint8_t event[6];
1650     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
1651     event[1] = 4;
1652     little_endian_store_16(event, 2, con_handle);
1653     little_endian_store_16(event, 4, result);
1654     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1655     if (!l2cap_event_packet_handler) return;
1656     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
1657 }
1658 
1659 // @returns valid
1660 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
1661     hci_connection_t * connection;
1662     uint16_t result;
1663     uint8_t  event[10];
1664 
1665 #ifdef ENABLE_LE_DATA_CHANNELS
1666     btstack_linked_list_iterator_t it;
1667     l2cap_channel_t * channel;
1668     uint16_t local_cid;
1669     uint16_t le_psm;
1670     uint16_t new_credits;
1671     uint16_t credits_before;
1672     l2cap_service_t * service;
1673     uint16_t source_cid;
1674 #endif
1675 
1676     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1677     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
1678 
1679     switch (code){
1680 
1681         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
1682             result = little_endian_read_16(command, 4);
1683             l2cap_emit_connection_parameter_update_response(handle, result);
1684             break;
1685 
1686         case CONNECTION_PARAMETER_UPDATE_REQUEST:
1687             connection = hci_connection_for_handle(handle);
1688             if (connection){
1689                 if (connection->role != HCI_ROLE_MASTER){
1690                     // reject command without notifying upper layer when not in master role
1691                     return 0;
1692                 }
1693                 int update_parameter = 1;
1694                 le_connection_parameter_range_t existing_range;
1695                 gap_get_connection_parameter_range(&existing_range);
1696                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
1697                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
1698                 uint16_t le_conn_latency = little_endian_read_16(command,12);
1699                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
1700 
1701                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
1702                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
1703 
1704                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
1705                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
1706 
1707                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
1708                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
1709 
1710                 if (update_parameter){
1711                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
1712                     connection->le_conn_interval_min = le_conn_interval_min;
1713                     connection->le_conn_interval_max = le_conn_interval_max;
1714                     connection->le_conn_latency = le_conn_latency;
1715                     connection->le_supervision_timeout = le_supervision_timeout;
1716                 } else {
1717                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
1718                 }
1719                 connection->le_con_param_update_identifier = sig_id;
1720             }
1721 
1722             if (!l2cap_event_packet_handler) break;
1723 
1724             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
1725             event[1] = 8;
1726             memcpy(&event[2], &command[4], 8);
1727             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1728             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
1729             break;
1730 
1731 #ifdef ENABLE_LE_DATA_CHANNELS
1732 
1733         case COMMAND_REJECT:
1734             // Find channel for this sig_id and connection handle
1735             channel = NULL;
1736             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1737             while (btstack_linked_list_iterator_has_next(&it)){
1738                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1739                 if (a_channel->con_handle   != handle) continue;
1740                 if (a_channel->local_sig_id != sig_id) continue;
1741                 channel = a_channel;
1742                 break;
1743             }
1744             if (!channel) break;
1745 
1746             // if received while waiting for le connection response, assume legacy device
1747             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
1748                 channel->state = L2CAP_STATE_CLOSED;
1749                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
1750                 l2cap_emit_le_channel_opened(channel, 0x0002);
1751 
1752                 // discard channel
1753                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1754                 btstack_memory_l2cap_channel_free(channel);
1755                 break;
1756             }
1757             break;
1758 
1759         case LE_CREDIT_BASED_CONNECTION_REQUEST:
1760 
1761             // get hci connection, bail if not found (must not happen)
1762             connection = hci_connection_for_handle(handle);
1763             if (!connection) return 0;
1764 
1765             // check if service registered
1766             le_psm  = little_endian_read_16(command, 4);
1767             service = l2cap_le_get_service(le_psm);
1768             source_cid = little_endian_read_16(command, 6);
1769 
1770             if (service){
1771                 if (source_cid < 0x40){
1772                     // 0x0009 Connection refused - Invalid Source CID
1773                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
1774                     return 1;
1775                 }
1776 
1777                 // go through list of channels for this ACL connection and check if we get a match
1778                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1779                 while (btstack_linked_list_iterator_has_next(&it)){
1780                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1781                     if (a_channel->con_handle != handle) continue;
1782                     if (a_channel->remote_cid != source_cid) continue;
1783                     // 0x000a Connection refused - Source CID already allocated
1784                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
1785                     return 1;
1786                 }
1787 
1788                 // security: check encryption
1789                 if (service->required_security_level >= LEVEL_2){
1790                     if (sm_encryption_key_size(handle) == 0){
1791                         // 0x0008 Connection refused - insufficient encryption
1792                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
1793                         return 1;
1794                     }
1795                     // anything less than 16 byte key size is insufficient
1796                     if (sm_encryption_key_size(handle) < 16){
1797                         // 0x0007 Connection refused – insufficient encryption key size
1798                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
1799                         return 1;
1800                     }
1801                 }
1802 
1803                 // security: check authencation
1804                 if (service->required_security_level >= LEVEL_3){
1805                     if (!sm_authenticated(handle)){
1806                         // 0x0005 Connection refused – insufficient authentication
1807                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
1808                         return 1;
1809                     }
1810                 }
1811 
1812                 // security: check authorization
1813                 if (service->required_security_level >= LEVEL_4){
1814                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
1815                         // 0x0006 Connection refused – insufficient authorization
1816                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
1817                         return 1;
1818                     }
1819                 }
1820 
1821                 // allocate channel
1822                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
1823                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
1824                 if (!channel){
1825                     // 0x0004 Connection refused – no resources available
1826                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
1827                     return 1;
1828                 }
1829 
1830                 channel->con_handle = handle;
1831                 channel->remote_cid = source_cid;
1832                 channel->remote_sig_id = sig_id;
1833                 channel->remote_mtu = little_endian_read_16(command, 8);
1834                 channel->remote_mps = little_endian_read_16(command, 10);
1835                 channel->credits_outgoing = little_endian_read_16(command, 12);
1836 
1837                 // set initial state
1838                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
1839                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
1840 
1841                 // add to connections list
1842                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1843 
1844                 // post connection request event
1845                 l2cap_emit_le_incoming_connection(channel);
1846 
1847             } else {
1848                 // Connection refused – LE_PSM not supported
1849                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1850             }
1851             break;
1852 
1853         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
1854             // Find channel for this sig_id and connection handle
1855             channel = NULL;
1856             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1857             while (btstack_linked_list_iterator_has_next(&it)){
1858                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1859                 if (a_channel->con_handle   != handle) continue;
1860                 if (a_channel->local_sig_id != sig_id) continue;
1861                 channel = a_channel;
1862                 break;
1863             }
1864             if (!channel) break;
1865 
1866             // cid + 0
1867             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
1868             if (result){
1869                 channel->state = L2CAP_STATE_CLOSED;
1870                 // map l2cap connection response result to BTstack status enumeration
1871                 l2cap_emit_le_channel_opened(channel, result);
1872 
1873                 // discard channel
1874                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1875                 btstack_memory_l2cap_channel_free(channel);
1876                 break;
1877             }
1878 
1879             // success
1880             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1881             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
1882             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
1883             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
1884             channel->state = L2CAP_STATE_OPEN;
1885             l2cap_emit_le_channel_opened(channel, result);
1886             break;
1887 
1888         case LE_FLOW_CONTROL_CREDIT:
1889             // find channel
1890             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1891             channel = l2cap_le_get_channel_for_local_cid(local_cid);
1892             if (!channel) {
1893                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
1894                 break;
1895             }
1896             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
1897             credits_before = channel->credits_outgoing;
1898             channel->credits_outgoing += new_credits;
1899             // check for credit overrun
1900             if (credits_before > channel->credits_outgoing){
1901                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
1902                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1903                 break;
1904             }
1905             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
1906             break;
1907 
1908         case DISCONNECTION_REQUEST:
1909             // find channel
1910             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1911             channel = l2cap_le_get_channel_for_local_cid(local_cid);
1912             if (!channel) {
1913                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
1914                 break;
1915             }
1916             channel->remote_sig_id = sig_id;
1917             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1918             break;
1919 
1920 #endif
1921 
1922         case DISCONNECTION_RESPONSE:
1923             break;
1924 
1925         default:
1926             // command unknown -> reject command
1927             return 0;
1928     }
1929     return 1;
1930 }
1931 #endif
1932 
1933 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
1934     UNUSED(packet_type);
1935     UNUSED(channel);
1936 
1937     l2cap_channel_t * l2cap_channel;
1938     UNUSED(l2cap_channel);
1939 
1940     // Get Channel ID
1941     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
1942     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
1943 
1944     switch (channel_id) {
1945 
1946 #ifdef ENABLE_CLASSIC
1947         case L2CAP_CID_SIGNALING: {
1948             uint16_t command_offset = 8;
1949             while (command_offset < size) {
1950                 // handle signaling commands
1951                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
1952 
1953                 // increment command_offset
1954                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1955             }
1956             break;
1957         }
1958 #endif
1959 
1960 #ifdef ENABLE_BLE
1961         case L2CAP_CID_SIGNALING_LE: {
1962             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
1963             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
1964             if (!valid){
1965                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
1966             }
1967             break;
1968         }
1969 #endif
1970 
1971         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1972             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
1973                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1974             }
1975             break;
1976 
1977         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1978             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
1979                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1980             }
1981             break;
1982 
1983         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1984             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
1985                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1986             }
1987             break;
1988 
1989         default:
1990 #ifdef ENABLE_CLASSIC
1991             // Find channel for this channel_id and connection handle
1992             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
1993             if (l2cap_channel) {
1994                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1995             }
1996 #endif
1997 #ifdef ENABLE_LE_DATA_CHANNELS
1998             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
1999             if (l2cap_channel) {
2000                 // credit counting
2001                 if (l2cap_channel->credits_incoming == 0){
2002                     log_error("LE Data Channel packet received but no incoming credits");
2003                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2004                     break;
2005                 }
2006                 l2cap_channel->credits_incoming--;
2007 
2008                 // automatic credits
2009                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
2010                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
2011                 }
2012 
2013                 // first fragment
2014                 uint16_t pos = 0;
2015                 if (!l2cap_channel->receive_sdu_len){
2016                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2017                     l2cap_channel->receive_sdu_pos = 0;
2018                     pos  += 2;
2019                     size -= 2;
2020                 }
2021                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
2022                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
2023                 // done?
2024                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
2025                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
2026                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
2027                     l2cap_channel->receive_sdu_len = 0;
2028                 }
2029             } else {
2030                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
2031             }
2032 #endif
2033             break;
2034     }
2035 
2036     l2cap_run();
2037 }
2038 
2039 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
2040 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
2041     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
2042     if (index < 0) return;
2043     fixed_channels[index].callback = the_packet_handler;
2044 }
2045 
2046 #ifdef ENABLE_CLASSIC
2047 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
2048 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
2049     channel->state = L2CAP_STATE_CLOSED;
2050     l2cap_emit_channel_closed(channel);
2051     // discard channel
2052     l2cap_stop_rtx(channel);
2053     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2054     btstack_memory_l2cap_channel_free(channel);
2055 }
2056 
2057 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
2058     btstack_linked_list_iterator_t it;
2059     btstack_linked_list_iterator_init(&it, services);
2060     while (btstack_linked_list_iterator_has_next(&it)){
2061         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
2062         if ( service->psm == psm){
2063             return service;
2064         };
2065     }
2066     return NULL;
2067 }
2068 
2069 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
2070     return l2cap_get_service_internal(&l2cap_services, psm);
2071 }
2072 
2073 
2074 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
2075 
2076     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
2077 
2078     // check for alread registered psm
2079     l2cap_service_t *service = l2cap_get_service(psm);
2080     if (service) {
2081         log_error("l2cap_register_service: PSM %u already registered", psm);
2082         return L2CAP_SERVICE_ALREADY_REGISTERED;
2083     }
2084 
2085     // alloc structure
2086     service = btstack_memory_l2cap_service_get();
2087     if (!service) {
2088         log_error("l2cap_register_service: no memory for l2cap_service_t");
2089         return BTSTACK_MEMORY_ALLOC_FAILED;
2090     }
2091 
2092     // fill in
2093     service->psm = psm;
2094     service->mtu = mtu;
2095     service->packet_handler = service_packet_handler;
2096     service->required_security_level = security_level;
2097 
2098     // add to services list
2099     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2100 
2101     // enable page scan
2102     gap_connectable_control(1);
2103 
2104     return 0;
2105 }
2106 
2107 uint8_t l2cap_unregister_service(uint16_t psm){
2108 
2109     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2110 
2111     l2cap_service_t *service = l2cap_get_service(psm);
2112     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2113     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2114     btstack_memory_l2cap_service_free(service);
2115 
2116     // disable page scan when no services registered
2117     if (btstack_linked_list_empty(&l2cap_services)) {
2118         gap_connectable_control(0);
2119     }
2120     return 0;
2121 }
2122 #endif
2123 
2124 
2125 #ifdef ENABLE_LE_DATA_CHANNELS
2126 
2127 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
2128     if (!channel->waiting_for_can_send_now) return;
2129     if (channel->send_sdu_buffer) return;
2130     channel->waiting_for_can_send_now = 0;
2131     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
2132     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
2133 }
2134 
2135 // 1BH2222
2136 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
2137     log_info("L2CAP_EVENT_LE_INCOMING_CONNECTION addr_type %u, addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x, remote_mtu %u",
2138              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
2139     uint8_t event[19];
2140     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
2141     event[1] = sizeof(event) - 2;
2142     event[2] = channel->address_type;
2143     reverse_bd_addr(channel->address, &event[3]);
2144     little_endian_store_16(event,  9, channel->con_handle);
2145     little_endian_store_16(event, 11, channel->psm);
2146     little_endian_store_16(event, 13, channel->local_cid);
2147     little_endian_store_16(event, 15, channel->remote_cid);
2148     little_endian_store_16(event, 17, channel->remote_mtu);
2149     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2150     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2151 }
2152 // 11BH22222
2153 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
2154     log_info("L2CAP_EVENT_LE_CHANNEL_OPENED status 0x%x addr_type %u addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u",
2155              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
2156              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2157     uint8_t event[23];
2158     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
2159     event[1] = sizeof(event) - 2;
2160     event[2] = status;
2161     event[3] = channel->address_type;
2162     reverse_bd_addr(channel->address, &event[4]);
2163     little_endian_store_16(event, 10, channel->con_handle);
2164     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2165     little_endian_store_16(event, 13, channel->psm);
2166     little_endian_store_16(event, 15, channel->local_cid);
2167     little_endian_store_16(event, 17, channel->remote_cid);
2168     little_endian_store_16(event, 19, channel->local_mtu);
2169     little_endian_store_16(event, 21, channel->remote_mtu);
2170     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2171     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2172 }
2173 
2174 static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
2175     btstack_linked_list_iterator_t it;
2176     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2177     while (btstack_linked_list_iterator_has_next(&it)){
2178         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2179         if ( channel->local_cid == local_cid) {
2180             return channel;
2181         }
2182     }
2183     return NULL;
2184 }
2185 
2186 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
2187 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
2188     channel->state = L2CAP_STATE_CLOSED;
2189     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
2190     // discard channel
2191     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2192     btstack_memory_l2cap_channel_free(channel);
2193 }
2194 
2195 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
2196     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
2197 }
2198 
2199 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
2200 
2201     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
2202 
2203     // check for alread registered psm
2204     l2cap_service_t *service = l2cap_le_get_service(psm);
2205     if (service) {
2206         return L2CAP_SERVICE_ALREADY_REGISTERED;
2207     }
2208 
2209     // alloc structure
2210     service = btstack_memory_l2cap_service_get();
2211     if (!service) {
2212         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2213         return BTSTACK_MEMORY_ALLOC_FAILED;
2214     }
2215 
2216     // fill in
2217     service->psm = psm;
2218     service->mtu = 0;
2219     service->packet_handler = packet_handler;
2220     service->required_security_level = security_level;
2221 
2222     // add to services list
2223     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
2224 
2225     // done
2226     return 0;
2227 }
2228 
2229 uint8_t l2cap_le_unregister_service(uint16_t psm) {
2230     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
2231     l2cap_service_t *service = l2cap_le_get_service(psm);
2232     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2233 
2234     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
2235     btstack_memory_l2cap_service_free(service);
2236     return 0;
2237 }
2238 
2239 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
2240     // get channel
2241     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2242     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2243 
2244     // validate state
2245     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2246         return ERROR_CODE_COMMAND_DISALLOWED;
2247     }
2248 
2249     // set state accept connection
2250     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
2251     channel->receive_sdu_buffer = receive_sdu_buffer;
2252     channel->local_mtu = mtu;
2253     channel->new_credits_incoming = initial_credits;
2254     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
2255 
2256     // test
2257     // channel->new_credits_incoming = 1;
2258 
2259     // go
2260     l2cap_run();
2261     return 0;
2262 }
2263 
2264 /**
2265  * @brief Deny incoming LE Data Channel connection due to resource constraints
2266  * @param local_cid             L2CAP LE Data Channel Identifier
2267  */
2268 
2269 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
2270     // get channel
2271     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2272     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2273 
2274     // validate state
2275     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2276         return ERROR_CODE_COMMAND_DISALLOWED;
2277     }
2278 
2279     // set state decline connection
2280     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
2281     channel->reason = 0x04; // no resources available
2282     l2cap_run();
2283     return 0;
2284 }
2285 
2286 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
2287     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
2288     uint16_t * out_local_cid) {
2289 
2290     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
2291 
2292 
2293     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2294     if (!connection) {
2295         log_error("no hci_connection for handle 0x%04x", con_handle);
2296         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2297     }
2298 
2299     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
2300     if (!channel) {
2301         return BTSTACK_MEMORY_ALLOC_FAILED;
2302     }
2303     log_info("l2cap_le_create_channel %p", channel);
2304 
2305     // store local_cid
2306     if (out_local_cid){
2307        *out_local_cid = channel->local_cid;
2308     }
2309 
2310     // provide buffer
2311     channel->con_handle = con_handle;
2312     channel->receive_sdu_buffer = receive_sdu_buffer;
2313     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
2314     channel->new_credits_incoming = initial_credits;
2315     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
2316 
2317     // add to connections list
2318     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2319 
2320     // go
2321     l2cap_run();
2322     return 0;
2323 }
2324 
2325 /**
2326  * @brief Provide credtis for LE Data Channel
2327  * @param local_cid             L2CAP LE Data Channel Identifier
2328  * @param credits               Number additional credits for peer
2329  */
2330 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
2331 
2332     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2333     if (!channel) {
2334         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2335         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2336     }
2337 
2338     // check state
2339     if (channel->state != L2CAP_STATE_OPEN){
2340         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
2341     }
2342 
2343     // assert incoming credits + credits <= 0xffff
2344     uint32_t total_credits = channel->credits_incoming;
2345     total_credits += channel->new_credits_incoming;
2346     total_credits += credits;
2347     if (total_credits > 0xffff){
2348         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
2349             channel->new_credits_incoming, credits);
2350     }
2351 
2352     // set credits_granted
2353     channel->new_credits_incoming += credits;
2354 
2355     // go
2356     l2cap_run();
2357     return 0;
2358 }
2359 
2360 /**
2361  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
2362  * @param local_cid             L2CAP LE Data Channel Identifier
2363  */
2364 int l2cap_le_can_send_now(uint16_t local_cid){
2365     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2366     if (!channel) {
2367         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2368         return 0;
2369     }
2370 
2371     // check state
2372     if (channel->state != L2CAP_STATE_OPEN) return 0;
2373 
2374     // check queue
2375     if (channel->send_sdu_buffer) return 0;
2376 
2377     // fine, go ahead
2378     return 1;
2379 }
2380 
2381 /**
2382  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
2383  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
2384  *       so packet handler should be ready to handle it
2385  * @param local_cid             L2CAP LE Data Channel Identifier
2386  */
2387 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
2388     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2389     if (!channel) {
2390         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
2391         return 0;
2392     }
2393     channel->waiting_for_can_send_now = 1;
2394     l2cap_le_notify_channel_can_send(channel);
2395     return 0;
2396 }
2397 
2398 /**
2399  * @brief Send data via LE Data Channel
2400  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
2401  * @param local_cid             L2CAP LE Data Channel Identifier
2402  * @param data                  data to send
2403  * @param size                  data size
2404  */
2405 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
2406 
2407     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2408     if (!channel) {
2409         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2410         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2411     }
2412 
2413     if (len > channel->remote_mtu){
2414         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
2415         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
2416     }
2417 
2418     if (channel->send_sdu_buffer){
2419         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
2420         return BTSTACK_ACL_BUFFERS_FULL;
2421     }
2422 
2423     channel->send_sdu_buffer = data;
2424     channel->send_sdu_len    = len;
2425     channel->send_sdu_pos    = 0;
2426 
2427     l2cap_run();
2428     return 0;
2429 }
2430 
2431 /**
2432  * @brief Disconnect from LE Data Channel
2433  * @param local_cid             L2CAP LE Data Channel Identifier
2434  */
2435 uint8_t l2cap_le_disconnect(uint16_t local_cid)
2436 {
2437     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2438     if (!channel) {
2439         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2440         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2441     }
2442 
2443     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2444     l2cap_run();
2445     return 0;
2446 }
2447 
2448 #endif
2449