xref: /btstack/src/l2cap.c (revision a6bfadd349591fe6d767d8088dd474788fc01d06)
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 // MARK: L2CAP_RUN
567 // process outstanding signaling tasks
568 static void l2cap_run(void){
569 
570     // log_info("l2cap_run: entered");
571 
572     // check pending signaling responses
573     while (signaling_responses_pending){
574 
575         hci_con_handle_t handle = signaling_responses[0].handle;
576 
577         if (!hci_can_send_acl_packet_now(handle)) break;
578 
579         uint8_t  sig_id        = signaling_responses[0].sig_id;
580         uint8_t  response_code = signaling_responses[0].code;
581         uint16_t infoType      = signaling_responses[0].data;  // INFORMATION_REQUEST
582         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
583 #ifdef ENABLE_CLASSIC
584         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
585 #endif
586         UNUSED(infoType);
587 
588         // remove first item before sending (to avoid sending response mutliple times)
589         signaling_responses_pending--;
590         int i;
591         for (i=0; i < signaling_responses_pending; i++){
592             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
593         }
594 
595         switch (response_code){
596 #ifdef ENABLE_CLASSIC
597             case CONNECTION_REQUEST:
598                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
599                 // also disconnect if result is 0x0003 - security blocked
600                 if (result == 0x0003){
601                     hci_disconnect_security_block(handle);
602                 }
603                 break;
604             case ECHO_REQUEST:
605                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
606                 break;
607             case INFORMATION_REQUEST:
608                 switch (infoType){
609                     case 1: { // Connectionless MTU
610                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
611                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
612                         }
613                         break;
614                     case 2: { // Extended Features Supported
615                             // extended features request supported, features: fixed channels, unicast connectionless data reception
616                             uint32_t features = 0x280;
617 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
618                             features |= 0x0008;
619 #endif
620                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
621                         }
622                         break;
623                     case 3: { // Fixed Channels Supported
624                             uint8_t map[8];
625                             memset(map, 0, 8);
626                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
627                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
628                         }
629                         break;
630                     default:
631                         // all other types are not supported
632                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
633                         break;
634                 }
635                 break;
636             case COMMAND_REJECT:
637                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
638                 break;
639 #endif
640 #ifdef ENABLE_BLE
641             case LE_CREDIT_BASED_CONNECTION_REQUEST:
642                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
643                 break;
644             case COMMAND_REJECT_LE:
645                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
646                 break;
647 #endif
648             default:
649                 // should not happen
650                 break;
651         }
652     }
653 
654     btstack_linked_list_iterator_t it;
655     UNUSED(it);
656 
657 #ifdef ENABLE_CLASSIC
658     uint8_t  config_options[4];
659     btstack_linked_list_iterator_init(&it, &l2cap_channels);
660     while (btstack_linked_list_iterator_has_next(&it)){
661 
662         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
663         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
664         switch (channel->state){
665 
666             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
667             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
668                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
669                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
670                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
671                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
672                 }
673                 break;
674 
675             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
676                 if (!hci_can_send_command_packet_now()) break;
677                 // send connection request - set state first
678                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
679                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
680                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
681                 break;
682 
683             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
684                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
685                 channel->state = L2CAP_STATE_INVALID;
686                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
687                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
688                 l2cap_stop_rtx(channel);
689                 btstack_linked_list_iterator_remove(&it);
690                 btstack_memory_l2cap_channel_free(channel);
691                 break;
692 
693             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
694                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
695                 channel->state = L2CAP_STATE_CONFIG;
696                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
697                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
698                 break;
699 
700             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
701                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
702                 // success, start l2cap handshake
703                 channel->local_sig_id = l2cap_next_sig_id();
704                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
705                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
706                 l2cap_start_rtx(channel);
707                 break;
708 
709             case L2CAP_STATE_CONFIG:
710                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
711                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
712                     uint16_t flags = 0;
713                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
714                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
715                         flags = 1;
716                     } else {
717                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
718                     }
719                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
720                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
721                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
722                         config_options[0] = 1; // MTU
723                         config_options[1] = 2; // len param
724                         little_endian_store_16( (uint8_t*)&config_options, 2, channel->remote_mtu);
725                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 4, &config_options);
726                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
727                     } else {
728                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 0, NULL);
729                     }
730                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
731                 }
732                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
733                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
734                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
735                     channel->local_sig_id = l2cap_next_sig_id();
736                     config_options[0] = 1; // MTU
737                     config_options[1] = 2; // len param
738                     little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
739                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options);
740                     l2cap_start_rtx(channel);
741                 }
742                 if (l2cap_channel_ready_for_open(channel)){
743                     channel->state = L2CAP_STATE_OPEN;
744                     l2cap_emit_channel_opened(channel, 0);  // success
745                 }
746                 break;
747 
748             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
749                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
750                 channel->state = L2CAP_STATE_INVALID;
751                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
752                 // 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 :)
753                 l2cap_finialize_channel_close(channel);  // -- remove from list
754                 break;
755 
756             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
757                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
758                 channel->local_sig_id = l2cap_next_sig_id();
759                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
760                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
761                 break;
762             default:
763                 break;
764         }
765     }
766 #endif
767 
768 #ifdef ENABLE_LE_DATA_CHANNELS
769     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
770     while (btstack_linked_list_iterator_has_next(&it)){
771         uint8_t  * acl_buffer;
772         uint8_t  * l2cap_payload;
773         uint16_t pos;
774         uint16_t payload_size;
775         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
776         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
777         switch (channel->state){
778             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
779                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
780                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
781                 // le psm, source cid, mtu, mps, initial credits
782                 channel->local_sig_id = l2cap_next_sig_id();
783                 channel->credits_incoming =  channel->new_credits_incoming;
784                 channel->new_credits_incoming = 0;
785                 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);
786                 break;
787             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
788                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
789                 // TODO: support larger MPS
790                 channel->state = L2CAP_STATE_OPEN;
791                 channel->credits_incoming =  channel->new_credits_incoming;
792                 channel->new_credits_incoming = 0;
793                 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);
794                 // notify client
795                 l2cap_emit_le_channel_opened(channel, 0);
796                 break;
797             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
798                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
799                 channel->state = L2CAP_STATE_INVALID;
800                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
801                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
802                 l2cap_stop_rtx(channel);
803                 btstack_linked_list_iterator_remove(&it);
804                 btstack_memory_l2cap_channel_free(channel);
805                 break;
806             case L2CAP_STATE_OPEN:
807                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
808 
809                 // send credits
810                 if (channel->new_credits_incoming){
811                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
812                     channel->local_sig_id = l2cap_next_sig_id();
813                     uint16_t new_credits = channel->new_credits_incoming;
814                     channel->new_credits_incoming = 0;
815                     channel->credits_incoming += new_credits;
816                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
817                     break;
818                 }
819 
820                 // send data
821                 if (!channel->send_sdu_buffer) break;
822                 if (!channel->credits_outgoing) break;
823 
824                 // send part of SDU
825                 hci_reserve_packet_buffer();
826                 acl_buffer = hci_get_outgoing_packet_buffer();
827                 l2cap_payload = acl_buffer + 8;
828                 pos = 0;
829                 if (!channel->send_sdu_pos){
830                     // store SDU len
831                     channel->send_sdu_pos += 2;
832                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
833                     pos += 2;
834                 }
835                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
836                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
837                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
838                 pos += payload_size;
839                 channel->send_sdu_pos += payload_size;
840                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
841                 // done
842 
843                 channel->credits_outgoing--;
844 
845                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
846                     channel->send_sdu_buffer = NULL;
847                     // send done event
848                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
849                     // inform about can send now
850                     l2cap_le_notify_channel_can_send(channel);
851                 }
852                 hci_send_acl_packet_buffer(8 + pos);
853                 break;
854             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
855                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
856                 channel->local_sig_id = l2cap_next_sig_id();
857                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
858                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
859                 break;
860             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
861                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
862                 channel->state = L2CAP_STATE_INVALID;
863                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
864                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
865                 break;
866             default:
867                 break;
868         }
869     }
870 #endif
871 
872 #ifdef ENABLE_BLE
873     // send l2cap con paramter update if necessary
874     hci_connections_get_iterator(&it);
875     while(btstack_linked_list_iterator_has_next(&it)){
876         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
877         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
878         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
879         switch (connection->le_con_parameter_update_state){
880             case CON_PARAMETER_UPDATE_SEND_REQUEST:
881                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
882                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
883                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
884                 break;
885             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
886                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
887                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
888                 break;
889             case CON_PARAMETER_UPDATE_DENY:
890                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
891                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
892                 break;
893             default:
894                 break;
895         }
896     }
897 #endif
898 
899     // log_info("l2cap_run: exit");
900 }
901 
902 #ifdef ENABLE_CLASSIC
903 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
904     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
905         log_info("l2cap_handle_connection_complete expected state");
906         // success, start l2cap handshake
907         channel->con_handle = con_handle;
908         // check remote SSP feature first
909         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
910     }
911 }
912 
913 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
914     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
915 
916     // we have been waiting for remote supported features, if both support SSP,
917     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));
918     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
919         // request security level 2
920         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
921         gap_request_security_level(channel->con_handle, LEVEL_2);
922         return;
923     }
924     // fine, go ahead
925     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
926 }
927 #endif
928 
929 #ifdef L2CAP_USES_CHANNELS
930 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, bd_addr_t address, bd_addr_type_t address_type,
931     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
932 
933     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
934     if (!channel) {
935         return NULL;
936     }
937 
938      // Init memory (make valgrind happy)
939     memset(channel, 0, sizeof(l2cap_channel_t));
940 
941     // fill in
942     channel->packet_handler = packet_handler;
943     bd_addr_copy(channel->address, address);
944     channel->address_type = address_type;
945     channel->psm = psm;
946     channel->local_mtu  = local_mtu;
947     channel->remote_mtu = L2CAP_MINIMAL_MTU;
948     channel->required_security_level = security_level;
949 
950     //
951     channel->local_cid = l2cap_next_local_cid();
952     channel->con_handle = 0;
953 
954     // set initial state
955     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
956     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
957     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
958     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
959     return channel;
960 }
961 #endif
962 
963 #ifdef ENABLE_CLASSIC
964 
965 /**
966  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
967  * @param packet_handler
968  * @param address
969  * @param psm
970  * @param mtu
971  * @param local_cid
972  */
973 
974 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){
975     // limit MTU to the size of our outtgoing HCI buffer
976     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
977 
978     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u -> local mtu %u", bd_addr_to_str(address), psm, mtu, local_mtu);
979 
980     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
981     if (!channel) {
982         return BTSTACK_MEMORY_ALLOC_FAILED;
983     }
984 
985     // add to connections list
986     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
987 
988     // store local_cid
989     if (out_local_cid){
990        *out_local_cid = channel->local_cid;
991     }
992 
993     // check if hci connection is already usable
994     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
995     if (conn){
996         log_info("l2cap_create_channel, hci connection already exists");
997         l2cap_handle_connection_complete(conn->con_handle, channel);
998         // check if remote supported fearures are already received
999         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1000             l2cap_handle_remote_supported_features_received(channel);
1001         }
1002     }
1003 
1004     l2cap_run();
1005 
1006     return 0;
1007 }
1008 
1009 void
1010 l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1011     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1012     // find channel for local_cid
1013     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1014     if (channel) {
1015         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1016     }
1017     // process
1018     l2cap_run();
1019 }
1020 
1021 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1022     btstack_linked_list_iterator_t it;
1023     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1024     while (btstack_linked_list_iterator_has_next(&it)){
1025         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1026         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1027         // channel for this address found
1028         switch (channel->state){
1029             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1030             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1031                 // failure, forward error code
1032                 l2cap_emit_channel_opened(channel, status);
1033                 // discard channel
1034                 l2cap_stop_rtx(channel);
1035                 btstack_linked_list_iterator_remove(&it);
1036                 btstack_memory_l2cap_channel_free(channel);
1037                 break;
1038             default:
1039                 break;
1040         }
1041     }
1042 }
1043 
1044 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1045     btstack_linked_list_iterator_t it;
1046     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1047     while (btstack_linked_list_iterator_has_next(&it)){
1048         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1049         if ( ! bd_addr_cmp( channel->address, address) ){
1050             l2cap_handle_connection_complete(handle, channel);
1051         }
1052     }
1053     // process
1054     l2cap_run();
1055 }
1056 #endif
1057 
1058 static void l2cap_notify_channel_can_send(void){
1059 
1060 #ifdef ENABLE_CLASSIC
1061     btstack_linked_list_iterator_t it;
1062     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1063     while (btstack_linked_list_iterator_has_next(&it)){
1064         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1065         if (!channel->waiting_for_can_send_now) continue;
1066         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1067         channel->waiting_for_can_send_now = 0;
1068         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
1069     }
1070 #endif
1071 
1072     int i;
1073     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1074         if (!fixed_channels[i].callback) continue;
1075         if (!fixed_channels[i].waiting_for_can_send_now) continue;
1076         int can_send = 0;
1077         if (l2cap_fixed_channel_table_index_is_le(i)){
1078 #ifdef ENABLE_BLE
1079             can_send = hci_can_send_acl_le_packet_now();
1080 #endif
1081         } else {
1082 #ifdef ENABLE_CLASSIC
1083             can_send = hci_can_send_acl_classic_packet_now();
1084 #endif
1085         }
1086         if (!can_send) continue;
1087         fixed_channels[i].waiting_for_can_send_now = 0;
1088         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
1089     }
1090 }
1091 
1092 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1093 
1094     UNUSED(packet_type);
1095     UNUSED(cid);
1096     UNUSED(size);
1097 
1098     bd_addr_t address;
1099     hci_con_handle_t handle;
1100     int hci_con_used;
1101     btstack_linked_list_iterator_t it;
1102 
1103     // avoid unused warnings
1104     UNUSED(address);
1105     UNUSED(hci_con_used);
1106     UNUSED(it);
1107     UNUSED(handle);
1108 
1109     switch(hci_event_packet_get_type(packet)){
1110 
1111         // Notify channel packet handler if they can send now
1112         case HCI_EVENT_TRANSPORT_PACKET_SENT:
1113         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
1114             l2cap_run();    // try sending signaling packets first
1115             l2cap_notify_channel_can_send();
1116             break;
1117 
1118         case HCI_EVENT_COMMAND_STATUS:
1119             l2cap_run();    // try sending signaling packets first
1120             break;
1121 
1122 #ifdef ENABLE_CLASSIC
1123         // handle connection complete events
1124         case HCI_EVENT_CONNECTION_COMPLETE:
1125             reverse_bd_addr(&packet[5], address);
1126             if (packet[2] == 0){
1127                 handle = little_endian_read_16(packet, 3);
1128                 l2cap_handle_connection_success_for_addr(address, handle);
1129             } else {
1130                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1131             }
1132             break;
1133 
1134         // handle successful create connection cancel command
1135         case HCI_EVENT_COMMAND_COMPLETE:
1136             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1137                 if (packet[5] == 0){
1138                     reverse_bd_addr(&packet[6], address);
1139                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1140                     l2cap_handle_connection_failed_for_addr(address, 0x16);
1141                 }
1142             }
1143             l2cap_run();    // try sending signaling packets first
1144             break;
1145 #endif
1146 
1147         // handle disconnection complete events
1148         case HCI_EVENT_DISCONNECTION_COMPLETE:
1149             // send l2cap disconnect events for all channels on this handle and free them
1150 #ifdef ENABLE_CLASSIC
1151             handle = little_endian_read_16(packet, 3);
1152             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1153             while (btstack_linked_list_iterator_has_next(&it)){
1154                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1155                 if (channel->con_handle != handle) continue;
1156                 l2cap_emit_channel_closed(channel);
1157                 l2cap_stop_rtx(channel);
1158                 btstack_linked_list_iterator_remove(&it);
1159                 btstack_memory_l2cap_channel_free(channel);
1160             }
1161 #endif
1162 #ifdef ENABLE_LE_DATA_CHANNELS
1163             handle = little_endian_read_16(packet, 3);
1164             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1165             while (btstack_linked_list_iterator_has_next(&it)){
1166                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1167                 if (channel->con_handle != handle) continue;
1168                 l2cap_emit_channel_closed(channel);
1169                 btstack_linked_list_iterator_remove(&it);
1170                 btstack_memory_l2cap_channel_free(channel);
1171             }
1172 #endif
1173             break;
1174 
1175         // HCI Connection Timeouts
1176 #ifdef ENABLE_CLASSIC
1177         case L2CAP_EVENT_TIMEOUT_CHECK:
1178             handle = little_endian_read_16(packet, 2);
1179             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
1180             if (hci_authentication_active_for_handle(handle)) break;
1181             hci_con_used = 0;
1182             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1183             while (btstack_linked_list_iterator_has_next(&it)){
1184                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1185                 if (channel->con_handle != handle) continue;
1186                 hci_con_used = 1;
1187                 break;
1188             }
1189             if (hci_con_used) break;
1190             if (!hci_can_send_command_packet_now()) break;
1191             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1192             break;
1193 
1194         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1195             handle = little_endian_read_16(packet, 3);
1196             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1197             while (btstack_linked_list_iterator_has_next(&it)){
1198                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1199                 if (channel->con_handle != handle) continue;
1200                 l2cap_handle_remote_supported_features_received(channel);
1201                 break;
1202             }
1203             break;
1204 
1205         case GAP_EVENT_SECURITY_LEVEL:
1206             handle = little_endian_read_16(packet, 2);
1207             log_info("l2cap - security level update");
1208             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1209             while (btstack_linked_list_iterator_has_next(&it)){
1210                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1211                 if (channel->con_handle != handle) continue;
1212 
1213                 log_info("l2cap - state %u", channel->state);
1214 
1215                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
1216                 gap_security_level_t required_level = channel->required_security_level;
1217 
1218                 switch (channel->state){
1219                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1220                         if (actual_level >= required_level){
1221                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
1222                             l2cap_emit_incoming_connection(channel);
1223                         } else {
1224                             channel->reason = 0x0003; // security block
1225                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1226                         }
1227                         break;
1228 
1229                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
1230                         if (actual_level >= required_level){
1231                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
1232                         } else {
1233                             // disconnnect, authentication not good enough
1234                             hci_disconnect_security_block(handle);
1235                         }
1236                         break;
1237 
1238                     default:
1239                         break;
1240                 }
1241             }
1242             break;
1243 #endif
1244 
1245         default:
1246             break;
1247     }
1248 
1249     l2cap_run();
1250 }
1251 
1252 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
1253     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
1254     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
1255         signaling_responses[signaling_responses_pending].handle = handle;
1256         signaling_responses[signaling_responses_pending].code = code;
1257         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1258         signaling_responses[signaling_responses_pending].cid = cid;
1259         signaling_responses[signaling_responses_pending].data = data;
1260         signaling_responses_pending++;
1261         l2cap_run();
1262     }
1263 }
1264 
1265 #ifdef ENABLE_CLASSIC
1266 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
1267     channel->remote_sig_id = identifier;
1268     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1269     l2cap_run();
1270 }
1271 
1272 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1273 
1274     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1275     l2cap_service_t *service = l2cap_get_service(psm);
1276     if (!service) {
1277         // 0x0002 PSM not supported
1278         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1279         return;
1280     }
1281 
1282     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1283     if (!hci_connection) {
1284         //
1285         log_error("no hci_connection for handle %u", handle);
1286         return;
1287     }
1288 
1289     // alloc structure
1290     // log_info("l2cap_handle_connection_request register channel");
1291     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1292     psm, service->mtu, service->required_security_level);
1293     if (!channel){
1294         // 0x0004 No resources available
1295         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
1296         return;
1297     }
1298 
1299     channel->con_handle = handle;
1300     channel->remote_cid = source_cid;
1301     channel->remote_sig_id = sig_id;
1302 
1303     // limit local mtu to max acl packet length - l2cap header
1304     if (channel->local_mtu > l2cap_max_mtu()) {
1305         channel->local_mtu = l2cap_max_mtu();
1306     }
1307 
1308     // set initial state
1309     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1310     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
1311 
1312     // add to connections list
1313     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1314 
1315     // assert security requirements
1316     gap_request_security_level(handle, channel->required_security_level);
1317 }
1318 
1319 void l2cap_accept_connection(uint16_t local_cid){
1320     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1321     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1322     if (!channel) {
1323         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1324         return;
1325     }
1326 
1327     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1328 
1329     // process
1330     l2cap_run();
1331 }
1332 
1333 void l2cap_decline_connection(uint16_t local_cid){
1334     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1335     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1336     if (!channel) {
1337         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1338         return;
1339     }
1340     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1341     channel->reason = 0x04; // no resources available
1342     l2cap_run();
1343 }
1344 
1345 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1346 
1347     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1348 
1349     uint16_t flags = little_endian_read_16(command, 6);
1350     if (flags & 1) {
1351         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1352     }
1353 
1354     // accept the other's configuration options
1355     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1356     uint16_t pos     = 8;
1357     while (pos < end_pos){
1358         uint8_t option_hint = command[pos] >> 7;
1359         uint8_t option_type = command[pos] & 0x7f;
1360         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
1361         pos++;
1362         uint8_t length = command[pos++];
1363         // MTU { type(8): 1, len(8):2, MTU(16) }
1364         if (option_type == 1 && length == 2){
1365             channel->remote_mtu = little_endian_read_16(command, pos);
1366             if (channel->remote_mtu > l2cap_max_mtu()){
1367                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
1368                 channel->remote_mtu = l2cap_max_mtu();
1369             }
1370             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1371         }
1372         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
1373         if (option_type == 2 && length == 2){
1374             channel->flush_timeout = little_endian_read_16(command, pos);
1375         }
1376         // check for unknown options
1377         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1378             log_info("l2cap cid %u, unknown options", channel->local_cid);
1379             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
1380         }
1381         pos += length;
1382     }
1383 }
1384 
1385 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
1386     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
1387     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
1388     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1389     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1390     if (channel->state == L2CAP_STATE_OPEN) return 0;
1391     return 1;
1392 }
1393 
1394 
1395 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
1396 
1397     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1398     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1399     uint16_t result = 0;
1400 
1401     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1402 
1403     // handle DISCONNECT REQUESTS seperately
1404     if (code == DISCONNECTION_REQUEST){
1405         switch (channel->state){
1406             case L2CAP_STATE_CONFIG:
1407             case L2CAP_STATE_OPEN:
1408             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1409             case L2CAP_STATE_WAIT_DISCONNECT:
1410                 l2cap_handle_disconnect_request(channel, identifier);
1411                 break;
1412 
1413             default:
1414                 // ignore in other states
1415                 break;
1416         }
1417         return;
1418     }
1419 
1420     // @STATEMACHINE(l2cap)
1421     switch (channel->state) {
1422 
1423         case L2CAP_STATE_WAIT_CONNECT_RSP:
1424             switch (code){
1425                 case CONNECTION_RESPONSE:
1426                     l2cap_stop_rtx(channel);
1427                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1428                     switch (result) {
1429                         case 0:
1430                             // successful connection
1431                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1432                             channel->state = L2CAP_STATE_CONFIG;
1433                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1434                             break;
1435                         case 1:
1436                             // connection pending. get some coffee, but start the ERTX
1437                             l2cap_start_ertx(channel);
1438                             break;
1439                         default:
1440                             // channel closed
1441                             channel->state = L2CAP_STATE_CLOSED;
1442                             // map l2cap connection response result to BTstack status enumeration
1443                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1444 
1445                             // drop link key if security block
1446                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
1447                                 gap_drop_link_key_for_bd_addr(channel->address);
1448                             }
1449 
1450                             // discard channel
1451                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1452                             btstack_memory_l2cap_channel_free(channel);
1453                             break;
1454                     }
1455                     break;
1456 
1457                 default:
1458                     //@TODO: implement other signaling packets
1459                     break;
1460             }
1461             break;
1462 
1463         case L2CAP_STATE_CONFIG:
1464             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1465             switch (code) {
1466                 case CONFIGURE_REQUEST:
1467                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1468                     l2cap_signaling_handle_configure_request(channel, command);
1469                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
1470                         // only done if continuation not set
1471                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
1472                     }
1473                     break;
1474                 case CONFIGURE_RESPONSE:
1475                     l2cap_stop_rtx(channel);
1476                     switch (result){
1477                         case 0: // success
1478                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
1479                             break;
1480                         case 4: // pending
1481                             l2cap_start_ertx(channel);
1482                             break;
1483                         default:
1484                             // retry on negative result
1485                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1486                             break;
1487                     }
1488                     break;
1489                 default:
1490                     break;
1491             }
1492             if (l2cap_channel_ready_for_open(channel)){
1493                 // for open:
1494                 channel->state = L2CAP_STATE_OPEN;
1495                 l2cap_emit_channel_opened(channel, 0);
1496             }
1497             break;
1498 
1499         case L2CAP_STATE_WAIT_DISCONNECT:
1500             switch (code) {
1501                 case DISCONNECTION_RESPONSE:
1502                     l2cap_finialize_channel_close(channel);
1503                     break;
1504                 default:
1505                     //@TODO: implement other signaling packets
1506                     break;
1507             }
1508             break;
1509 
1510         case L2CAP_STATE_CLOSED:
1511             // @TODO handle incoming requests
1512             break;
1513 
1514         case L2CAP_STATE_OPEN:
1515             //@TODO: implement other signaling packets, e.g. re-configure
1516             break;
1517         default:
1518             break;
1519     }
1520     // log_info("new state %u", channel->state);
1521 }
1522 
1523 
1524 static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
1525 
1526     // get code, signalind identifier and command len
1527     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1528     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1529 
1530     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
1531     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
1532         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
1533         return;
1534     }
1535 
1536     // general commands without an assigned channel
1537     switch(code) {
1538 
1539         case CONNECTION_REQUEST: {
1540             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1541             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
1542             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
1543             return;
1544         }
1545 
1546         case ECHO_REQUEST:
1547             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
1548             return;
1549 
1550         case INFORMATION_REQUEST: {
1551             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1552             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
1553             return;
1554         }
1555 
1556         default:
1557             break;
1558     }
1559 
1560 
1561     // Get potential destination CID
1562     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1563 
1564     // Find channel for this sig_id and connection handle
1565     btstack_linked_list_iterator_t it;
1566     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1567     while (btstack_linked_list_iterator_has_next(&it)){
1568         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1569         if (channel->con_handle != handle) continue;
1570         if (code & 1) {
1571             // match odd commands (responses) by previous signaling identifier
1572             if (channel->local_sig_id == sig_id) {
1573                 l2cap_signaling_handler_channel(channel, command);
1574                 break;
1575             }
1576         } else {
1577             // match even commands (requests) by local channel id
1578             if (channel->local_cid == dest_cid) {
1579                 l2cap_signaling_handler_channel(channel, command);
1580                 break;
1581             }
1582         }
1583     }
1584 }
1585 #endif
1586 
1587 #ifdef ENABLE_BLE
1588 
1589 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
1590     uint8_t event[6];
1591     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
1592     event[1] = 4;
1593     little_endian_store_16(event, 2, con_handle);
1594     little_endian_store_16(event, 4, result);
1595     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1596     if (!l2cap_event_packet_handler) return;
1597     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
1598 }
1599 
1600 // @returns valid
1601 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
1602     hci_connection_t * connection;
1603     uint16_t result;
1604     uint8_t  event[10];
1605 
1606 #ifdef ENABLE_LE_DATA_CHANNELS
1607     btstack_linked_list_iterator_t it;
1608     l2cap_channel_t * channel;
1609     uint16_t local_cid;
1610     uint16_t le_psm;
1611     uint16_t new_credits;
1612     uint16_t credits_before;
1613     l2cap_service_t * service;
1614     uint16_t source_cid;
1615 #endif
1616 
1617     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1618     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
1619 
1620     switch (code){
1621 
1622         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
1623             result = little_endian_read_16(command, 4);
1624             l2cap_emit_connection_parameter_update_response(handle, result);
1625             break;
1626 
1627         case CONNECTION_PARAMETER_UPDATE_REQUEST:
1628             connection = hci_connection_for_handle(handle);
1629             if (connection){
1630                 if (connection->role != HCI_ROLE_MASTER){
1631                     // reject command without notifying upper layer when not in master role
1632                     return 0;
1633                 }
1634                 int update_parameter = 1;
1635                 le_connection_parameter_range_t existing_range;
1636                 gap_get_connection_parameter_range(&existing_range);
1637                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
1638                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
1639                 uint16_t le_conn_latency = little_endian_read_16(command,12);
1640                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
1641 
1642                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
1643                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
1644 
1645                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
1646                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
1647 
1648                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
1649                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
1650 
1651                 if (update_parameter){
1652                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
1653                     connection->le_conn_interval_min = le_conn_interval_min;
1654                     connection->le_conn_interval_max = le_conn_interval_max;
1655                     connection->le_conn_latency = le_conn_latency;
1656                     connection->le_supervision_timeout = le_supervision_timeout;
1657                 } else {
1658                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
1659                 }
1660                 connection->le_con_param_update_identifier = sig_id;
1661             }
1662 
1663             if (!l2cap_event_packet_handler) break;
1664 
1665             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
1666             event[1] = 8;
1667             memcpy(&event[2], &command[4], 8);
1668             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1669             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
1670             break;
1671 
1672 #ifdef ENABLE_LE_DATA_CHANNELS
1673 
1674         case COMMAND_REJECT:
1675             // Find channel for this sig_id and connection handle
1676             channel = NULL;
1677             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1678             while (btstack_linked_list_iterator_has_next(&it)){
1679                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1680                 if (a_channel->con_handle   != handle) continue;
1681                 if (a_channel->local_sig_id != sig_id) continue;
1682                 channel = a_channel;
1683                 break;
1684             }
1685             if (!channel) break;
1686 
1687             // if received while waiting for le connection response, assume legacy device
1688             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
1689                 channel->state = L2CAP_STATE_CLOSED;
1690                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
1691                 l2cap_emit_le_channel_opened(channel, 0x0002);
1692 
1693                 // discard channel
1694                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1695                 btstack_memory_l2cap_channel_free(channel);
1696                 break;
1697             }
1698             break;
1699 
1700         case LE_CREDIT_BASED_CONNECTION_REQUEST:
1701 
1702             // get hci connection, bail if not found (must not happen)
1703             connection = hci_connection_for_handle(handle);
1704             if (!connection) return 0;
1705 
1706             // check if service registered
1707             le_psm  = little_endian_read_16(command, 4);
1708             service = l2cap_le_get_service(le_psm);
1709             source_cid = little_endian_read_16(command, 6);
1710 
1711             if (service){
1712                 if (source_cid < 0x40){
1713                     // 0x0009 Connection refused - Invalid Source CID
1714                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
1715                     return 1;
1716                 }
1717 
1718                 // go through list of channels for this ACL connection and check if we get a match
1719                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1720                 while (btstack_linked_list_iterator_has_next(&it)){
1721                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1722                     if (a_channel->con_handle != handle) continue;
1723                     if (a_channel->remote_cid != source_cid) continue;
1724                     // 0x000a Connection refused - Source CID already allocated
1725                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
1726                     return 1;
1727                 }
1728 
1729                 // security: check encryption
1730                 if (service->required_security_level >= LEVEL_2){
1731                     if (sm_encryption_key_size(handle) == 0){
1732                         // 0x0008 Connection refused - insufficient encryption
1733                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
1734                         return 1;
1735                     }
1736                     // anything less than 16 byte key size is insufficient
1737                     if (sm_encryption_key_size(handle) < 16){
1738                         // 0x0007 Connection refused – insufficient encryption key size
1739                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
1740                         return 1;
1741                     }
1742                 }
1743 
1744                 // security: check authencation
1745                 if (service->required_security_level >= LEVEL_3){
1746                     if (!sm_authenticated(handle)){
1747                         // 0x0005 Connection refused – insufficient authentication
1748                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
1749                         return 1;
1750                     }
1751                 }
1752 
1753                 // security: check authorization
1754                 if (service->required_security_level >= LEVEL_4){
1755                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
1756                         // 0x0006 Connection refused – insufficient authorization
1757                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
1758                         return 1;
1759                     }
1760                 }
1761 
1762                 // allocate channel
1763                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
1764                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
1765                 if (!channel){
1766                     // 0x0004 Connection refused – no resources available
1767                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
1768                     return 1;
1769                 }
1770 
1771                 channel->con_handle = handle;
1772                 channel->remote_cid = source_cid;
1773                 channel->remote_sig_id = sig_id;
1774                 channel->remote_mtu = little_endian_read_16(command, 8);
1775                 channel->remote_mps = little_endian_read_16(command, 10);
1776                 channel->credits_outgoing = little_endian_read_16(command, 12);
1777 
1778                 // set initial state
1779                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
1780                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
1781 
1782                 // add to connections list
1783                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1784 
1785                 // post connection request event
1786                 l2cap_emit_le_incoming_connection(channel);
1787 
1788             } else {
1789                 // Connection refused – LE_PSM not supported
1790                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1791             }
1792             break;
1793 
1794         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
1795             // Find channel for this sig_id and connection handle
1796             channel = NULL;
1797             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1798             while (btstack_linked_list_iterator_has_next(&it)){
1799                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1800                 if (a_channel->con_handle   != handle) continue;
1801                 if (a_channel->local_sig_id != sig_id) continue;
1802                 channel = a_channel;
1803                 break;
1804             }
1805             if (!channel) break;
1806 
1807             // cid + 0
1808             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
1809             if (result){
1810                 channel->state = L2CAP_STATE_CLOSED;
1811                 // map l2cap connection response result to BTstack status enumeration
1812                 l2cap_emit_le_channel_opened(channel, result);
1813 
1814                 // discard channel
1815                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1816                 btstack_memory_l2cap_channel_free(channel);
1817                 break;
1818             }
1819 
1820             // success
1821             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1822             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
1823             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
1824             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
1825             channel->state = L2CAP_STATE_OPEN;
1826             l2cap_emit_le_channel_opened(channel, result);
1827             break;
1828 
1829         case LE_FLOW_CONTROL_CREDIT:
1830             // find channel
1831             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1832             channel = l2cap_le_get_channel_for_local_cid(local_cid);
1833             if (!channel) {
1834                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
1835                 break;
1836             }
1837             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
1838             credits_before = channel->credits_outgoing;
1839             channel->credits_outgoing += new_credits;
1840             // check for credit overrun
1841             if (credits_before > channel->credits_outgoing){
1842                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
1843                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1844                 break;
1845             }
1846             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
1847             break;
1848 
1849         case DISCONNECTION_REQUEST:
1850             // find channel
1851             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1852             channel = l2cap_le_get_channel_for_local_cid(local_cid);
1853             if (!channel) {
1854                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
1855                 break;
1856             }
1857             channel->remote_sig_id = sig_id;
1858             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1859             break;
1860 
1861 #endif
1862 
1863         case DISCONNECTION_RESPONSE:
1864             break;
1865 
1866         default:
1867             // command unknown -> reject command
1868             return 0;
1869     }
1870     return 1;
1871 }
1872 #endif
1873 
1874 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
1875     UNUSED(packet_type);
1876     UNUSED(channel);
1877 
1878     l2cap_channel_t * l2cap_channel;
1879     UNUSED(l2cap_channel);
1880 
1881     // Get Channel ID
1882     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
1883     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
1884 
1885     switch (channel_id) {
1886 
1887 #ifdef ENABLE_CLASSIC
1888         case L2CAP_CID_SIGNALING: {
1889             uint16_t command_offset = 8;
1890             while (command_offset < size) {
1891                 // handle signaling commands
1892                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
1893 
1894                 // increment command_offset
1895                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1896             }
1897             break;
1898         }
1899 #endif
1900 
1901 #ifdef ENABLE_BLE
1902         case L2CAP_CID_SIGNALING_LE: {
1903             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
1904             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
1905             if (!valid){
1906                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
1907             }
1908             break;
1909         }
1910 #endif
1911 
1912         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1913             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
1914                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1915             }
1916             break;
1917 
1918         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1919             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
1920                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1921             }
1922             break;
1923 
1924         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1925             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
1926                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1927             }
1928             break;
1929 
1930         default:
1931 #ifdef ENABLE_CLASSIC
1932             // Find channel for this channel_id and connection handle
1933             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
1934             if (l2cap_channel) {
1935                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1936             }
1937 #endif
1938 #ifdef ENABLE_LE_DATA_CHANNELS
1939             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
1940             if (l2cap_channel) {
1941                 // credit counting
1942                 if (l2cap_channel->credits_incoming == 0){
1943                     log_error("LE Data Channel packet received but no incoming credits");
1944                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1945                     break;
1946                 }
1947                 l2cap_channel->credits_incoming--;
1948 
1949                 // automatic credits
1950                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
1951                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
1952                 }
1953 
1954                 // first fragment
1955                 uint16_t pos = 0;
1956                 if (!l2cap_channel->receive_sdu_len){
1957                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
1958                     l2cap_channel->receive_sdu_pos = 0;
1959                     pos  += 2;
1960                     size -= 2;
1961                 }
1962                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
1963                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
1964                 // done?
1965                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
1966                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
1967                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
1968                     l2cap_channel->receive_sdu_len = 0;
1969                 }
1970             } else {
1971                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
1972             }
1973 #endif
1974             break;
1975     }
1976 
1977     l2cap_run();
1978 }
1979 
1980 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
1981 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
1982     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
1983     if (index < 0) return;
1984     fixed_channels[index].callback = the_packet_handler;
1985 }
1986 
1987 #ifdef ENABLE_CLASSIC
1988 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
1989 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
1990     channel->state = L2CAP_STATE_CLOSED;
1991     l2cap_emit_channel_closed(channel);
1992     // discard channel
1993     l2cap_stop_rtx(channel);
1994     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1995     btstack_memory_l2cap_channel_free(channel);
1996 }
1997 
1998 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
1999     btstack_linked_list_iterator_t it;
2000     btstack_linked_list_iterator_init(&it, services);
2001     while (btstack_linked_list_iterator_has_next(&it)){
2002         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
2003         if ( service->psm == psm){
2004             return service;
2005         };
2006     }
2007     return NULL;
2008 }
2009 
2010 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
2011     return l2cap_get_service_internal(&l2cap_services, psm);
2012 }
2013 
2014 
2015 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
2016 
2017     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
2018 
2019     // check for alread registered psm
2020     l2cap_service_t *service = l2cap_get_service(psm);
2021     if (service) {
2022         log_error("l2cap_register_service: PSM %u already registered", psm);
2023         return L2CAP_SERVICE_ALREADY_REGISTERED;
2024     }
2025 
2026     // alloc structure
2027     service = btstack_memory_l2cap_service_get();
2028     if (!service) {
2029         log_error("l2cap_register_service: no memory for l2cap_service_t");
2030         return BTSTACK_MEMORY_ALLOC_FAILED;
2031     }
2032 
2033     // fill in
2034     service->psm = psm;
2035     service->mtu = mtu;
2036     service->packet_handler = service_packet_handler;
2037     service->required_security_level = security_level;
2038 
2039     // add to services list
2040     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2041 
2042     // enable page scan
2043     gap_connectable_control(1);
2044 
2045     return 0;
2046 }
2047 
2048 uint8_t l2cap_unregister_service(uint16_t psm){
2049 
2050     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2051 
2052     l2cap_service_t *service = l2cap_get_service(psm);
2053     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2054     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2055     btstack_memory_l2cap_service_free(service);
2056 
2057     // disable page scan when no services registered
2058     if (btstack_linked_list_empty(&l2cap_services)) {
2059         gap_connectable_control(0);
2060     }
2061     return 0;
2062 }
2063 #endif
2064 
2065 
2066 #ifdef ENABLE_LE_DATA_CHANNELS
2067 
2068 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
2069     if (!channel->waiting_for_can_send_now) return;
2070     if (channel->send_sdu_buffer) return;
2071     channel->waiting_for_can_send_now = 0;
2072     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
2073     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
2074 }
2075 
2076 // 1BH2222
2077 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
2078     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",
2079              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
2080     uint8_t event[19];
2081     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
2082     event[1] = sizeof(event) - 2;
2083     event[2] = channel->address_type;
2084     reverse_bd_addr(channel->address, &event[3]);
2085     little_endian_store_16(event,  9, channel->con_handle);
2086     little_endian_store_16(event, 11, channel->psm);
2087     little_endian_store_16(event, 13, channel->local_cid);
2088     little_endian_store_16(event, 15, channel->remote_cid);
2089     little_endian_store_16(event, 17, channel->remote_mtu);
2090     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2091     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2092 }
2093 // 11BH22222
2094 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
2095     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",
2096              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
2097              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2098     uint8_t event[23];
2099     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
2100     event[1] = sizeof(event) - 2;
2101     event[2] = status;
2102     event[3] = channel->address_type;
2103     reverse_bd_addr(channel->address, &event[4]);
2104     little_endian_store_16(event, 10, channel->con_handle);
2105     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2106     little_endian_store_16(event, 13, channel->psm);
2107     little_endian_store_16(event, 15, channel->local_cid);
2108     little_endian_store_16(event, 17, channel->remote_cid);
2109     little_endian_store_16(event, 19, channel->local_mtu);
2110     little_endian_store_16(event, 21, channel->remote_mtu);
2111     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2112     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2113 }
2114 
2115 static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
2116     btstack_linked_list_iterator_t it;
2117     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2118     while (btstack_linked_list_iterator_has_next(&it)){
2119         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2120         if ( channel->local_cid == local_cid) {
2121             return channel;
2122         }
2123     }
2124     return NULL;
2125 }
2126 
2127 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
2128 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
2129     channel->state = L2CAP_STATE_CLOSED;
2130     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
2131     // discard channel
2132     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2133     btstack_memory_l2cap_channel_free(channel);
2134 }
2135 
2136 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
2137     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
2138 }
2139 
2140 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
2141 
2142     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
2143 
2144     // check for alread registered psm
2145     l2cap_service_t *service = l2cap_le_get_service(psm);
2146     if (service) {
2147         return L2CAP_SERVICE_ALREADY_REGISTERED;
2148     }
2149 
2150     // alloc structure
2151     service = btstack_memory_l2cap_service_get();
2152     if (!service) {
2153         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2154         return BTSTACK_MEMORY_ALLOC_FAILED;
2155     }
2156 
2157     // fill in
2158     service->psm = psm;
2159     service->mtu = 0;
2160     service->packet_handler = packet_handler;
2161     service->required_security_level = security_level;
2162 
2163     // add to services list
2164     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
2165 
2166     // done
2167     return 0;
2168 }
2169 
2170 uint8_t l2cap_le_unregister_service(uint16_t psm) {
2171     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
2172     l2cap_service_t *service = l2cap_le_get_service(psm);
2173     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2174 
2175     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
2176     btstack_memory_l2cap_service_free(service);
2177     return 0;
2178 }
2179 
2180 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
2181     // get channel
2182     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2183     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2184 
2185     // validate state
2186     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2187         return ERROR_CODE_COMMAND_DISALLOWED;
2188     }
2189 
2190     // set state accept connection
2191     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
2192     channel->receive_sdu_buffer = receive_sdu_buffer;
2193     channel->local_mtu = mtu;
2194     channel->new_credits_incoming = initial_credits;
2195     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
2196 
2197     // test
2198     // channel->new_credits_incoming = 1;
2199 
2200     // go
2201     l2cap_run();
2202     return 0;
2203 }
2204 
2205 /**
2206  * @brief Deny incoming LE Data Channel connection due to resource constraints
2207  * @param local_cid             L2CAP LE Data Channel Identifier
2208  */
2209 
2210 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
2211     // get channel
2212     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2213     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2214 
2215     // validate state
2216     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2217         return ERROR_CODE_COMMAND_DISALLOWED;
2218     }
2219 
2220     // set state decline connection
2221     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
2222     channel->reason = 0x04; // no resources available
2223     l2cap_run();
2224     return 0;
2225 }
2226 
2227 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
2228     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
2229     uint16_t * out_local_cid) {
2230 
2231     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
2232 
2233 
2234     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2235     if (!connection) {
2236         log_error("no hci_connection for handle 0x%04x", con_handle);
2237         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2238     }
2239 
2240     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
2241     if (!channel) {
2242         return BTSTACK_MEMORY_ALLOC_FAILED;
2243     }
2244     log_info("l2cap_le_create_channel %p", channel);
2245 
2246     // store local_cid
2247     if (out_local_cid){
2248        *out_local_cid = channel->local_cid;
2249     }
2250 
2251     // provide buffer
2252     channel->con_handle = con_handle;
2253     channel->receive_sdu_buffer = receive_sdu_buffer;
2254     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
2255     channel->new_credits_incoming = initial_credits;
2256     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
2257 
2258     // add to connections list
2259     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2260 
2261     // go
2262     l2cap_run();
2263     return 0;
2264 }
2265 
2266 /**
2267  * @brief Provide credtis for LE Data Channel
2268  * @param local_cid             L2CAP LE Data Channel Identifier
2269  * @param credits               Number additional credits for peer
2270  */
2271 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
2272 
2273     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2274     if (!channel) {
2275         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2276         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2277     }
2278 
2279     // check state
2280     if (channel->state != L2CAP_STATE_OPEN){
2281         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
2282     }
2283 
2284     // assert incoming credits + credits <= 0xffff
2285     uint32_t total_credits = channel->credits_incoming;
2286     total_credits += channel->new_credits_incoming;
2287     total_credits += credits;
2288     if (total_credits > 0xffff){
2289         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
2290             channel->new_credits_incoming, credits);
2291     }
2292 
2293     // set credits_granted
2294     channel->new_credits_incoming += credits;
2295 
2296     // go
2297     l2cap_run();
2298     return 0;
2299 }
2300 
2301 /**
2302  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
2303  * @param local_cid             L2CAP LE Data Channel Identifier
2304  */
2305 int l2cap_le_can_send_now(uint16_t local_cid){
2306     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2307     if (!channel) {
2308         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2309         return 0;
2310     }
2311 
2312     // check state
2313     if (channel->state != L2CAP_STATE_OPEN) return 0;
2314 
2315     // check queue
2316     if (channel->send_sdu_buffer) return 0;
2317 
2318     // fine, go ahead
2319     return 1;
2320 }
2321 
2322 /**
2323  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
2324  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
2325  *       so packet handler should be ready to handle it
2326  * @param local_cid             L2CAP LE Data Channel Identifier
2327  */
2328 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
2329     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2330     if (!channel) {
2331         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
2332         return 0;
2333     }
2334     channel->waiting_for_can_send_now = 1;
2335     l2cap_le_notify_channel_can_send(channel);
2336     return 0;
2337 }
2338 
2339 /**
2340  * @brief Send data via LE Data Channel
2341  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
2342  * @param local_cid             L2CAP LE Data Channel Identifier
2343  * @param data                  data to send
2344  * @param size                  data size
2345  */
2346 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
2347 
2348     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2349     if (!channel) {
2350         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2351         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2352     }
2353 
2354     if (len > channel->remote_mtu){
2355         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
2356         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
2357     }
2358 
2359     if (channel->send_sdu_buffer){
2360         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
2361         return BTSTACK_ACL_BUFFERS_FULL;
2362     }
2363 
2364     channel->send_sdu_buffer = data;
2365     channel->send_sdu_len    = len;
2366     channel->send_sdu_pos    = 0;
2367 
2368     l2cap_run();
2369     return 0;
2370 }
2371 
2372 /**
2373  * @brief Disconnect from LE Data Channel
2374  * @param local_cid             L2CAP LE Data Channel Identifier
2375  */
2376 uint8_t l2cap_le_disconnect(uint16_t local_cid)
2377 {
2378     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2379     if (!channel) {
2380         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2381         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2382     }
2383 
2384     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2385     l2cap_run();
2386     return 0;
2387 }
2388 
2389 #endif
2390