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