xref: /btstack/src/l2cap.c (revision 83e7cdd948f2a1a6e3c1630bfa189f2ebf07b275)
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 "debug.h"
50 #include "btstack_memory.h"
51 
52 #include <stdarg.h>
53 #include <string.h>
54 
55 #include <stdio.h>
56 
57 // nr of buffered acl packets in outgoing queue to get max performance
58 #define NR_BUFFERED_ACL_PACKETS 3
59 
60 // used to cache l2cap rejects, echo, and informational requests
61 #define NR_PENDING_SIGNALING_RESPONSES 3
62 
63 // offsets for L2CAP SIGNALING COMMANDS
64 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
65 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
66 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
67 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
68 
69 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
70 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
71 
72 // used to cache l2cap rejects, echo, and informational requests
73 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
74 static int signaling_responses_pending;
75 
76 static linked_list_t l2cap_channels;
77 static linked_list_t l2cap_services;
78 static linked_list_t l2cap_le_channels;
79 static linked_list_t l2cap_le_services;
80 static void (*packet_handler) (void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) = null_packet_handler;
81 
82 static btstack_packet_handler_t attribute_protocol_packet_handler;
83 static btstack_packet_handler_t security_protocol_packet_handler;
84 static btstack_packet_handler_t connectionless_channel_packet_handler;
85 static uint8_t require_security_level2_for_outgoing_sdp;
86 
87 // prototypes
88 static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
89 static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
90 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
91 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
92 static void l2cap_emit_connection_request(l2cap_channel_t *channel);
93 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel);
94 
95 
96 void l2cap_init(void){
97     signaling_responses_pending = 0;
98 
99     l2cap_channels = NULL;
100     l2cap_services = NULL;
101     l2cap_le_services = NULL;
102     l2cap_le_channels = NULL;
103 
104     packet_handler = null_packet_handler;
105     attribute_protocol_packet_handler = NULL;
106     security_protocol_packet_handler = NULL;
107     connectionless_channel_packet_handler = NULL;
108 
109     require_security_level2_for_outgoing_sdp = 0;
110 
111     //
112     // register callback with HCI
113     //
114     hci_register_packet_handler(&l2cap_packet_handler);
115     hci_connectable_control(0); // no services yet
116 }
117 
118 
119 /** Register L2CAP packet handlers */
120 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
121 }
122 void l2cap_register_packet_handler(void (*handler)(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
123     packet_handler = handler;
124 }
125 
126 //  notify client/protocol handler
127 static void l2cap_dispatch(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
128     if (channel->packet_handler) {
129         (* (channel->packet_handler))(type, channel->local_cid, data, size);
130     } else {
131         (*packet_handler)(channel->connection, type, channel->local_cid, data, size);
132     }
133 }
134 
135 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
136     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",
137              status, bd_addr_to_str(channel->address), channel->handle, channel->psm,
138              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
139     uint8_t event[23];
140     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
141     event[1] = sizeof(event) - 2;
142     event[2] = status;
143     bt_flip_addr(&event[3], channel->address);
144     bt_store_16(event,  9, channel->handle);
145     bt_store_16(event, 11, channel->psm);
146     bt_store_16(event, 13, channel->local_cid);
147     bt_store_16(event, 15, channel->remote_cid);
148     bt_store_16(event, 17, channel->local_mtu);
149     bt_store_16(event, 19, channel->remote_mtu);
150     bt_store_16(event, 21, channel->flush_timeout);
151     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
152     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
153 }
154 
155 void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
156     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
157     uint8_t event[4];
158     event[0] = L2CAP_EVENT_CHANNEL_CLOSED;
159     event[1] = sizeof(event) - 2;
160     bt_store_16(event, 2, channel->local_cid);
161     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
162     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
163 }
164 
165 void l2cap_emit_connection_request(l2cap_channel_t *channel) {
166     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
167              bd_addr_to_str(channel->address), channel->handle,  channel->psm, channel->local_cid, channel->remote_cid);
168     uint8_t event[16];
169     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
170     event[1] = sizeof(event) - 2;
171     bt_flip_addr(&event[2], channel->address);
172     bt_store_16(event,  8, channel->handle);
173     bt_store_16(event, 10, channel->psm);
174     bt_store_16(event, 12, channel->local_cid);
175     bt_store_16(event, 14, channel->remote_cid);
176     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
177     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
178 }
179 
180 static void l2cap_emit_connection_parameter_update_response(uint16_t handle, uint16_t result){
181     uint8_t event[6];
182     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
183     event[1] = 4;
184     bt_store_16(event, 2, handle);
185     bt_store_16(event, 4, result);
186     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
187     (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, event, sizeof(event));
188 }
189 
190 static void l2cap_emit_service_registered(void *connection, uint8_t status, uint16_t psm){
191     log_info("L2CAP_EVENT_SERVICE_REGISTERED status 0x%x psm 0x%x", status, psm);
192     uint8_t event[5];
193     event[0] = L2CAP_EVENT_SERVICE_REGISTERED;
194     event[1] = sizeof(event) - 2;
195     event[2] = status;
196     bt_store_16(event, 3, psm);
197     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
198     (*packet_handler)(connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
199 }
200 
201 static void l2cap_emit_credits(l2cap_channel_t *channel, uint8_t credits) {
202 
203     log_info("L2CAP_EVENT_CREDITS local_cid 0x%x credits %u", channel->local_cid, credits);
204 
205     uint8_t event[5];
206     event[0] = L2CAP_EVENT_CREDITS;
207     event[1] = sizeof(event) - 2;
208     bt_store_16(event, 2, channel->local_cid);
209     event[4] = credits;
210     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
211     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
212 }
213 
214 static void l2cap_hand_out_credits(void){
215     linked_list_iterator_t it;
216     linked_list_iterator_init(&it, &l2cap_channels);
217     while (linked_list_iterator_has_next(&it)){
218         l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it);
219         if (channel->state != L2CAP_STATE_OPEN) continue;
220         if (!hci_number_free_acl_slots_for_handle(channel->handle)) return;
221         l2cap_emit_credits(channel, 1);
222     }
223 }
224 
225 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
226     linked_list_iterator_t it;
227     linked_list_iterator_init(&it, &l2cap_channels);
228     while (linked_list_iterator_has_next(&it)){
229         l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it);
230         if ( channel->local_cid == local_cid) {
231             return channel;
232         }
233     }
234     return NULL;
235 }
236 
237 int  l2cap_can_send_packet_now(uint16_t local_cid){
238     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
239     if (!channel) return 0;
240     return hci_can_send_acl_packet_now(channel->handle);
241 }
242 
243 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
244     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
245     if (!channel) return 0;
246     return hci_can_send_prepared_acl_packet_now(channel->handle);
247 }
248 
249 // @deprecated
250 int l2cap_can_send_connectionless_packet_now(void){
251     // TODO provide real handle
252     return l2cap_can_send_fixed_channel_packet_now(0x1234);
253 }
254 
255 int  l2cap_can_send_fixed_channel_packet_now(uint16_t handle){
256     return hci_can_send_acl_packet_now(handle);
257 }
258 
259 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
260     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
261     if (channel) {
262         return channel->remote_mtu;
263     }
264     return 0;
265 }
266 
267 static l2cap_channel_t * l2cap_channel_for_rtx_timer(timer_source_t * ts){
268     linked_list_iterator_t it;
269     linked_list_iterator_init(&it, &l2cap_channels);
270     while (linked_list_iterator_has_next(&it)){
271         l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it);
272         if ( &channel->rtx == ts) {
273             return channel;
274         }
275     }
276     return NULL;
277 }
278 
279 static void l2cap_rtx_timeout(timer_source_t * ts){
280     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
281     if (!ts) return;
282 
283     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
284 
285     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
286     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
287     // notify client
288     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
289 
290     // discard channel
291     // no need to stop timer here, it is removed from list during timer callback
292     linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
293     btstack_memory_l2cap_channel_free(channel);
294 }
295 
296 static void l2cap_stop_rtx(l2cap_channel_t * channel){
297     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
298     run_loop_remove_timer(&channel->rtx);
299 }
300 
301 static void l2cap_start_rtx(l2cap_channel_t * channel){
302     l2cap_stop_rtx(channel);
303     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
304     run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
305     run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
306     run_loop_add_timer(&channel->rtx);
307 }
308 
309 static void l2cap_start_ertx(l2cap_channel_t * channel){
310     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
311     l2cap_stop_rtx(channel);
312     run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
313     run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
314     run_loop_add_timer(&channel->rtx);
315 }
316 
317 void l2cap_require_security_level_2_for_outgoing_sdp(void){
318     require_security_level2_for_outgoing_sdp = 1;
319 }
320 
321 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
322     return (psm == PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
323 }
324 
325 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
326 
327     if (!hci_can_send_acl_packet_now(handle)){
328         log_info("l2cap_send_signaling_packet, cannot send");
329         return BTSTACK_ACL_BUFFERS_FULL;
330     }
331 
332     // log_info("l2cap_send_signaling_packet type %u", cmd);
333     hci_reserve_packet_buffer();
334     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
335     va_list argptr;
336     va_start(argptr, identifier);
337     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
338     va_end(argptr);
339     // log_info("l2cap_send_signaling_packet con %u!", handle);
340     return hci_send_acl_packet_buffer(len);
341 }
342 
343 #ifdef HAVE_BLE
344 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
345 
346     if (!hci_can_send_acl_packet_now(handle)){
347         log_info("l2cap_send_signaling_packet, cannot send");
348         return BTSTACK_ACL_BUFFERS_FULL;
349     }
350 
351     // log_info("l2cap_send_signaling_packet type %u", cmd);
352     hci_reserve_packet_buffer();
353     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
354     va_list argptr;
355     va_start(argptr, identifier);
356     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
357     va_end(argptr);
358     // log_info("l2cap_send_signaling_packet con %u!", handle);
359     return hci_send_acl_packet_buffer(len);
360 }
361 #endif
362 
363 uint8_t *l2cap_get_outgoing_buffer(void){
364     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
365 }
366 
367 int l2cap_reserve_packet_buffer(void){
368     return hci_reserve_packet_buffer();
369 }
370 
371 void l2cap_release_packet_buffer(void){
372     hci_release_packet_buffer();
373 }
374 
375 
376 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
377 
378     if (!hci_is_packet_buffer_reserved()){
379         log_error("l2cap_send_prepared called without reserving packet first");
380         return BTSTACK_ACL_BUFFERS_FULL;
381     }
382 
383     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
384     if (!channel) {
385         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
386         return -1;   // TODO: define error
387     }
388 
389     if (!hci_can_send_prepared_acl_packet_now(channel->handle)){
390         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
391         return BTSTACK_ACL_BUFFERS_FULL;
392     }
393 
394     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->handle);
395 
396     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
397 
398     int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
399 
400     // 0 - Connection handle : PB=pb : BC=00
401     bt_store_16(acl_buffer, 0, channel->handle | (pb << 12) | (0 << 14));
402     // 2 - ACL length
403     bt_store_16(acl_buffer, 2,  len + 4);
404     // 4 - L2CAP packet length
405     bt_store_16(acl_buffer, 4,  len + 0);
406     // 6 - L2CAP channel DEST
407     bt_store_16(acl_buffer, 6, channel->remote_cid);
408     // send
409     int err = hci_send_acl_packet_buffer(len+8);
410 
411     l2cap_hand_out_credits();
412 
413     return err;
414 }
415 
416 int l2cap_send_prepared_connectionless(uint16_t handle, uint16_t cid, uint16_t len){
417 
418     if (!hci_is_packet_buffer_reserved()){
419         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
420         return BTSTACK_ACL_BUFFERS_FULL;
421     }
422 
423     if (!hci_can_send_prepared_acl_packet_now(handle)){
424         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", handle, cid);
425         return BTSTACK_ACL_BUFFERS_FULL;
426     }
427 
428     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", handle, cid);
429 
430     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
431 
432     int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
433 
434     // 0 - Connection handle : PB=pb : BC=00
435     bt_store_16(acl_buffer, 0, handle | (pb << 12) | (0 << 14));
436     // 2 - ACL length
437     bt_store_16(acl_buffer, 2,  len + 4);
438     // 4 - L2CAP packet length
439     bt_store_16(acl_buffer, 4,  len + 0);
440     // 6 - L2CAP channel DEST
441     bt_store_16(acl_buffer, 6, cid);
442     // send
443     int err = hci_send_acl_packet_buffer(len+8);
444 
445     l2cap_hand_out_credits();
446 
447     return err;
448 }
449 
450 int l2cap_send_internal(uint16_t local_cid, uint8_t *data, uint16_t len){
451 
452     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
453     if (!channel) {
454         log_error("l2cap_send_internal no channel for cid 0x%02x", local_cid);
455         return -1;   // TODO: define error
456     }
457 
458     if (len > channel->remote_mtu){
459         log_error("l2cap_send_internal cid 0x%02x, data length exceeds remote MTU.", local_cid);
460         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
461     }
462 
463     if (!hci_can_send_acl_packet_now(channel->handle)){
464         log_info("l2cap_send_internal cid 0x%02x, cannot send", local_cid);
465         return BTSTACK_ACL_BUFFERS_FULL;
466     }
467 
468     hci_reserve_packet_buffer();
469     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
470 
471     memcpy(&acl_buffer[8], data, len);
472 
473     return l2cap_send_prepared(local_cid, len);
474 }
475 
476 int l2cap_send_connectionless(uint16_t handle, uint16_t cid, uint8_t *data, uint16_t len){
477 
478     if (!hci_can_send_acl_packet_now(handle)){
479         log_info("l2cap_send_internal cid 0x%02x, cannot send", cid);
480         return BTSTACK_ACL_BUFFERS_FULL;
481     }
482 
483     hci_reserve_packet_buffer();
484     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
485 
486     memcpy(&acl_buffer[8], data, len);
487 
488     return l2cap_send_prepared_connectionless(handle, cid, len);
489 }
490 
491 int l2cap_send_echo_request(uint16_t handle, uint8_t *data, uint16_t len){
492     return l2cap_send_signaling_packet(handle, ECHO_REQUEST, 0x77, len, data);
493 }
494 
495 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
496     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
497 }
498 
499 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
500     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
501 }
502 
503 
504 
505 // MARK: L2CAP_RUN
506 // process outstanding signaling tasks
507 static void l2cap_run(void){
508 
509     // log_info("l2cap_run: entered");
510 
511     // check pending signaling responses
512     while (signaling_responses_pending){
513 
514         hci_con_handle_t handle = signaling_responses[0].handle;
515 
516         if (!hci_can_send_acl_packet_now(handle)) break;
517 
518         uint8_t  sig_id = signaling_responses[0].sig_id;
519         uint16_t infoType = signaling_responses[0].data;    // INFORMATION_REQUEST
520         uint16_t result   = signaling_responses[0].data;    // CONNECTION_REQUEST, COMMAND_REJECT
521         uint8_t  response_code = signaling_responses[0].code;
522 
523         // remove first item before sending (to avoid sending response mutliple times)
524         signaling_responses_pending--;
525         int i;
526         for (i=0; i < signaling_responses_pending; i++){
527             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
528         }
529 
530         switch (response_code){
531             case CONNECTION_REQUEST:
532                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, result, 0);
533                 // also disconnect if result is 0x0003 - security blocked
534                 if (result == 0x0003){
535                     hci_disconnect_security_block(handle);
536                 }
537                 break;
538             case ECHO_REQUEST:
539                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
540                 break;
541             case INFORMATION_REQUEST:
542                 switch (infoType){
543                     case 1: { // Connectionless MTU
544                         uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
545                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
546                         break;
547                     }
548                     case 2: { // Extended Features Supported
549                         // extended features request supported, features: fixed channels, unicast connectionless data reception
550                         uint32_t features = 0x280;
551                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
552                         break;
553                     }
554                     case 3: { // Fixed Channels Supported
555                         uint8_t map[8];
556                         memset(map, 0, 8);
557                         map[0] = 0x01;  // L2CAP Signaling Channel (0x01) + Connectionless reception (0x02)
558                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
559                         break;
560                     }
561                     default:
562                         // all other types are not supported
563                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
564                         break;
565                 }
566                 break;
567             case COMMAND_REJECT:
568                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
569 #ifdef HAVE_BLE
570             case COMMAND_REJECT_LE:
571                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
572                 break;
573 #endif
574             default:
575                 // should not happen
576                 break;
577         }
578     }
579 
580     uint8_t  config_options[4];
581     linked_list_iterator_t it;
582     linked_list_iterator_init(&it, &l2cap_channels);
583     while (linked_list_iterator_has_next(&it)){
584 
585         l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it);
586         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
587         switch (channel->state){
588 
589             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
590             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
591                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
592                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
593                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
594                     l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
595                 }
596                 break;
597 
598             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
599                 if (!hci_can_send_command_packet_now()) break;
600                 // send connection request - set state first
601                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
602                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
603                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
604                 break;
605 
606             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
607                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
608                 channel->state = L2CAP_STATE_INVALID;
609                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
610                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
611                 l2cap_stop_rtx(channel);
612                 linked_list_iterator_remove(&it);
613                 btstack_memory_l2cap_channel_free(channel);
614                 break;
615 
616             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
617                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
618                 channel->state = L2CAP_STATE_CONFIG;
619                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
620                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
621                 break;
622 
623             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
624                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
625                 // success, start l2cap handshake
626                 channel->local_sig_id = l2cap_next_sig_id();
627                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
628                 l2cap_send_signaling_packet( channel->handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
629                 l2cap_start_rtx(channel);
630                 break;
631 
632             case L2CAP_STATE_CONFIG:
633                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
634                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
635                     uint16_t flags = 0;
636                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
637                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
638                         flags = 1;
639                     } else {
640                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
641                     }
642                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
643                         l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
644                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
645                         config_options[0] = 1; // MTU
646                         config_options[1] = 2; // len param
647                         bt_store_16( (uint8_t*)&config_options, 2, channel->remote_mtu);
648                         l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 4, &config_options);
649                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
650                     } else {
651                         l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 0, NULL);
652                     }
653                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
654                 }
655                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
656                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
657                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
658                     channel->local_sig_id = l2cap_next_sig_id();
659                     config_options[0] = 1; // MTU
660                     config_options[1] = 2; // len param
661                     bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
662                     l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options);
663                     l2cap_start_rtx(channel);
664                 }
665                 if (l2cap_channel_ready_for_open(channel)){
666                     channel->state = L2CAP_STATE_OPEN;
667                     l2cap_emit_channel_opened(channel, 0);  // success
668                     l2cap_emit_credits(channel, 1);
669                 }
670                 break;
671 
672             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
673                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
674                 channel->state = L2CAP_STATE_INVALID;
675                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
676                 // 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 :)
677                 l2cap_finialize_channel_close(channel);  // -- remove from list
678                 break;
679 
680             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
681                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
682                 channel->local_sig_id = l2cap_next_sig_id();
683                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
684                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
685                 break;
686             default:
687                 break;
688         }
689     }
690 
691 #ifdef HAVE_BLE
692     // send l2cap con paramter update if necessary
693     hci_connections_get_iterator(&it);
694     while(linked_list_iterator_has_next(&it)){
695         hci_connection_t * connection = (hci_connection_t *) linked_list_iterator_next(&it);
696         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
697         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
698         switch (connection->le_con_parameter_update_state){
699             case CON_PARAMETER_UPDATE_SEND_REQUEST:
700                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
701                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
702                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
703                 break;
704             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
705                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
706                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
707                 break;
708             case CON_PARAMETER_UPDATE_DENY:
709                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
710                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
711                 break;
712             default:
713                 break;
714         }
715     }
716 #endif
717 
718     // log_info("l2cap_run: exit");
719 }
720 
721 uint16_t l2cap_max_mtu(void){
722     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
723 }
724 
725 uint16_t l2cap_max_le_mtu(void){
726     return l2cap_max_mtu();
727 }
728 
729 static void l2cap_handle_connection_complete(uint16_t handle, l2cap_channel_t * channel){
730     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
731         log_info("l2cap_handle_connection_complete expected state");
732         // success, start l2cap handshake
733         channel->handle = handle;
734         channel->local_cid = l2cap_next_local_cid();
735         // check remote SSP feature first
736         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
737     }
738 }
739 
740 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
741     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
742 
743     // we have been waiting for remote supported features, if both support SSP,
744     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));
745     if (hci_ssp_supported_on_both_sides(channel->handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
746         // request security level 2
747         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
748         gap_request_security_level(channel->handle, LEVEL_2);
749         return;
750     }
751     // fine, go ahead
752     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
753 }
754 
755 // open outgoing L2CAP channel
756 void l2cap_create_channel_internal(void * connection, btstack_packet_handler_t channel_packet_handler,
757                                    bd_addr_t address, uint16_t psm, uint16_t mtu){
758 
759     log_info("L2CAP_CREATE_CHANNEL_MTU addr %s psm 0x%x mtu %u", bd_addr_to_str(address), psm, mtu);
760 
761     // alloc structure
762     l2cap_channel_t * chan = btstack_memory_l2cap_channel_get();
763     if (!chan) {
764         // emit error event
765         l2cap_channel_t dummy_channel;
766         BD_ADDR_COPY(dummy_channel.address, address);
767         dummy_channel.psm = psm;
768         l2cap_emit_channel_opened(&dummy_channel, BTSTACK_MEMORY_ALLOC_FAILED);
769         return;
770     }
771     // Init memory (make valgrind happy)
772     memset(chan, 0, sizeof(l2cap_channel_t));
773     // limit local mtu to max acl packet length - l2cap header
774     if (mtu > l2cap_max_mtu()) {
775         mtu = l2cap_max_mtu();
776     }
777 
778     // fill in
779     BD_ADDR_COPY(chan->address, address);
780     chan->psm = psm;
781     chan->handle = 0;
782     chan->connection = connection;
783     chan->packet_handler = channel_packet_handler;
784     chan->remote_mtu = L2CAP_MINIMAL_MTU;
785     chan->local_mtu = mtu;
786 
787     // set initial state
788     chan->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
789     chan->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
790     chan->remote_sig_id = L2CAP_SIG_ID_INVALID;
791     chan->local_sig_id = L2CAP_SIG_ID_INVALID;
792     chan->required_security_level = LEVEL_0;
793 
794     // add to connections list
795     linked_list_add(&l2cap_channels, (linked_item_t *) chan);
796 
797     // check if hci connection is already usable
798     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
799     if (conn){
800         log_info("l2cap_create_channel_internal, hci connection already exists");
801         l2cap_handle_connection_complete(conn->con_handle, chan);
802         // check if remote supported fearures are already received
803         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
804             l2cap_handle_remote_supported_features_received(chan);
805         }
806     }
807 
808     l2cap_run();
809 }
810 
811 void l2cap_disconnect_internal(uint16_t local_cid, uint8_t reason){
812     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
813     // find channel for local_cid
814     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
815     if (channel) {
816         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
817     }
818     // process
819     l2cap_run();
820 }
821 
822 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
823     linked_list_iterator_t it;
824     linked_list_iterator_init(&it, &l2cap_channels);
825     while (linked_list_iterator_has_next(&it)){
826         l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it);
827         if ( BD_ADDR_CMP( channel->address, address) != 0) continue;
828         // channel for this address found
829         switch (channel->state){
830             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
831             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
832                 // failure, forward error code
833                 l2cap_emit_channel_opened(channel, status);
834                 // discard channel
835                 l2cap_stop_rtx(channel);
836                 linked_list_iterator_remove(&it);
837                 btstack_memory_l2cap_channel_free(channel);
838                 break;
839             default:
840                 break;
841         }
842     }
843 }
844 
845 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
846     linked_list_iterator_t it;
847     linked_list_iterator_init(&it, &l2cap_channels);
848     while (linked_list_iterator_has_next(&it)){
849         l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it);
850         if ( ! BD_ADDR_CMP( channel->address, address) ){
851             l2cap_handle_connection_complete(handle, channel);
852         }
853     }
854     // process
855     l2cap_run();
856 }
857 
858 static void l2cap_event_handler(uint8_t *packet, uint16_t size){
859 
860     bd_addr_t address;
861     hci_con_handle_t handle;
862     linked_list_iterator_t it;
863     int hci_con_used;
864 
865     switch(packet[0]){
866 
867         // handle connection complete events
868         case HCI_EVENT_CONNECTION_COMPLETE:
869             bt_flip_addr(address, &packet[5]);
870             if (packet[2] == 0){
871                 handle = READ_BT_16(packet, 3);
872                 l2cap_handle_connection_success_for_addr(address, handle);
873             } else {
874                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
875             }
876             break;
877 
878         // handle successful create connection cancel command
879         case HCI_EVENT_COMMAND_COMPLETE:
880             if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) {
881                 if (packet[5] == 0){
882                     bt_flip_addr(address, &packet[6]);
883                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
884                     l2cap_handle_connection_failed_for_addr(address, 0x16);
885                 }
886             }
887             l2cap_run();    // try sending signaling packets first
888             break;
889 
890         case HCI_EVENT_COMMAND_STATUS:
891             l2cap_run();    // try sending signaling packets first
892             break;
893 
894         // handle disconnection complete events
895         case HCI_EVENT_DISCONNECTION_COMPLETE:
896             // send l2cap disconnect events for all channels on this handle and free them
897             handle = READ_BT_16(packet, 3);
898             linked_list_iterator_init(&it, &l2cap_channels);
899             while (linked_list_iterator_has_next(&it)){
900                 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it);
901                 if (channel->handle != handle) continue;
902                 l2cap_emit_channel_closed(channel);
903                 l2cap_stop_rtx(channel);
904                 linked_list_iterator_remove(&it);
905                 btstack_memory_l2cap_channel_free(channel);
906             }
907             break;
908 
909         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
910             l2cap_run();    // try sending signaling packets first
911             l2cap_hand_out_credits();
912             break;
913 
914         // HCI Connection Timeouts
915         case L2CAP_EVENT_TIMEOUT_CHECK:
916             handle = READ_BT_16(packet, 2);
917             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
918             if (hci_authentication_active_for_handle(handle)) break;
919             hci_con_used = 0;
920             linked_list_iterator_init(&it, &l2cap_channels);
921             while (linked_list_iterator_has_next(&it)){
922                 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it);
923                 if (channel->handle != handle) continue;
924                 hci_con_used = 1;
925                 break;
926             }
927             if (hci_con_used) break;
928             if (!hci_can_send_command_packet_now()) break;
929             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
930             break;
931 
932         case DAEMON_EVENT_HCI_PACKET_SENT:
933             l2cap_run();    // try sending signaling packets first
934             l2cap_hand_out_credits();
935 
936             linked_list_iterator_init(&it, &l2cap_channels);
937             while (linked_list_iterator_has_next(&it)){
938                 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it);
939                 if (!channel->packet_handler) continue;
940                 (* (channel->packet_handler))(HCI_EVENT_PACKET, channel->local_cid, packet, size);
941             }
942             if (attribute_protocol_packet_handler) {
943                 (*attribute_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
944             }
945             if (security_protocol_packet_handler) {
946                 (*security_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
947             }
948             if (connectionless_channel_packet_handler) {
949                 (*connectionless_channel_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
950             }
951             break;
952 
953         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
954             handle = READ_BT_16(packet, 3);
955             linked_list_iterator_init(&it, &l2cap_channels);
956             while (linked_list_iterator_has_next(&it)){
957                 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it);
958                 if (channel->handle != handle) continue;
959                 l2cap_handle_remote_supported_features_received(channel);
960                 break;
961             }
962             break;
963 
964         case GAP_SECURITY_LEVEL:
965             handle = READ_BT_16(packet, 2);
966             log_info("l2cap - security level update");
967             linked_list_iterator_init(&it, &l2cap_channels);
968             while (linked_list_iterator_has_next(&it)){
969                 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it);
970                 if (channel->handle != handle) continue;
971 
972                 log_info("l2cap - state %u", channel->state);
973 
974                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
975                 gap_security_level_t required_level = channel->required_security_level;
976 
977                 switch (channel->state){
978                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
979                         if (actual_level >= required_level){
980                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
981                             l2cap_emit_connection_request(channel);
982                         } else {
983                             channel->reason = 0x0003; // security block
984                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
985                         }
986                         break;
987 
988                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
989                         if (actual_level >= required_level){
990                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
991                         } else {
992                             // disconnnect, authentication not good enough
993                             hci_disconnect_security_block(handle);
994                         }
995                         break;
996 
997                     default:
998                         break;
999                 }
1000             }
1001             break;
1002 
1003         default:
1004             break;
1005     }
1006 
1007     // pass on: main packet handler, att and sm packet handlers
1008     (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, packet, size);
1009     if (attribute_protocol_packet_handler){
1010         (*attribute_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
1011     }
1012     if (security_protocol_packet_handler) {
1013         (*security_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
1014     }
1015     if (connectionless_channel_packet_handler) {
1016         (*connectionless_channel_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
1017     }
1018 
1019     l2cap_run();
1020 }
1021 
1022 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
1023     channel->remote_sig_id = identifier;
1024     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1025     l2cap_run();
1026 }
1027 
1028 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){
1029     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
1030     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
1031         signaling_responses[signaling_responses_pending].handle = handle;
1032         signaling_responses[signaling_responses_pending].code = code;
1033         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1034         signaling_responses[signaling_responses_pending].data = data;
1035         signaling_responses_pending++;
1036         l2cap_run();
1037     }
1038 }
1039 
1040 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1041 
1042     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1043     l2cap_service_t *service = l2cap_get_service(psm);
1044     if (!service) {
1045         // 0x0002 PSM not supported
1046         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002);
1047         return;
1048     }
1049 
1050     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1051     if (!hci_connection) {
1052         //
1053         log_error("no hci_connection for handle %u", handle);
1054         return;
1055     }
1056 
1057     // alloc structure
1058     // log_info("l2cap_handle_connection_request register channel");
1059     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1060     if (!channel){
1061         // 0x0004 No resources available
1062         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004);
1063         return;
1064     }
1065     // Init memory (make valgrind happy)
1066     memset(channel, 0, sizeof(l2cap_channel_t));
1067     // fill in
1068     BD_ADDR_COPY(channel->address, hci_connection->address);
1069     channel->psm = psm;
1070     channel->handle = handle;
1071     channel->connection = service->connection;
1072     channel->packet_handler = service->packet_handler;
1073     channel->local_cid  = l2cap_next_local_cid();
1074     channel->remote_cid = source_cid;
1075     channel->local_mtu  = service->mtu;
1076     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1077     channel->remote_sig_id = sig_id;
1078     channel->required_security_level = service->required_security_level;
1079 
1080     // limit local mtu to max acl packet length - l2cap header
1081     if (channel->local_mtu > l2cap_max_mtu()) {
1082         channel->local_mtu = l2cap_max_mtu();
1083     }
1084 
1085     // set initial state
1086     channel->state =     L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1087     channel->state_var = L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
1088 
1089     // add to connections list
1090     linked_list_add(&l2cap_channels, (linked_item_t *) channel);
1091 
1092     // assert security requirements
1093     gap_request_security_level(handle, channel->required_security_level);
1094 }
1095 
1096 void l2cap_accept_connection_internal(uint16_t local_cid){
1097     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1098     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1099     if (!channel) {
1100         log_error("l2cap_accept_connection_internal called but local_cid 0x%x not found", local_cid);
1101         return;
1102     }
1103 
1104     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1105 
1106     // process
1107     l2cap_run();
1108 }
1109 
1110 void l2cap_decline_connection_internal(uint16_t local_cid, uint8_t reason){
1111     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x, reason %x", local_cid, reason);
1112     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1113     if (!channel) {
1114         log_error( "l2cap_decline_connection_internal called but local_cid 0x%x not found", local_cid);
1115         return;
1116     }
1117     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1118     channel->reason = reason;
1119     l2cap_run();
1120 }
1121 
1122 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1123 
1124     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1125 
1126     uint16_t flags = READ_BT_16(command, 6);
1127     if (flags & 1) {
1128         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1129     }
1130 
1131     // accept the other's configuration options
1132     uint16_t end_pos = 4 + READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1133     uint16_t pos     = 8;
1134     while (pos < end_pos){
1135         uint8_t option_hint = command[pos] >> 7;
1136         uint8_t option_type = command[pos] & 0x7f;
1137         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
1138         pos++;
1139         uint8_t length = command[pos++];
1140         // MTU { type(8): 1, len(8):2, MTU(16) }
1141         if (option_type == 1 && length == 2){
1142             channel->remote_mtu = READ_BT_16(command, pos);
1143             // log_info("l2cap cid 0x%02x, remote mtu %u", channel->local_cid, channel->remote_mtu);
1144             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1145         }
1146         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
1147         if (option_type == 2 && length == 2){
1148             channel->flush_timeout = READ_BT_16(command, pos);
1149         }
1150         // check for unknown options
1151         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1152             log_info("l2cap cid %u, unknown options", channel->local_cid);
1153             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
1154         }
1155         pos += length;
1156     }
1157 }
1158 
1159 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
1160     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
1161     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
1162     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1163     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1164     if (channel->state == L2CAP_STATE_OPEN) return 0;
1165     return 1;
1166 }
1167 
1168 
1169 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
1170 
1171     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1172     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1173     uint16_t result = 0;
1174 
1175     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1176 
1177     // handle DISCONNECT REQUESTS seperately
1178     if (code == DISCONNECTION_REQUEST){
1179         switch (channel->state){
1180             case L2CAP_STATE_CONFIG:
1181             case L2CAP_STATE_OPEN:
1182             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1183             case L2CAP_STATE_WAIT_DISCONNECT:
1184                 l2cap_handle_disconnect_request(channel, identifier);
1185                 break;
1186 
1187             default:
1188                 // ignore in other states
1189                 break;
1190         }
1191         return;
1192     }
1193 
1194     // @STATEMACHINE(l2cap)
1195     switch (channel->state) {
1196 
1197         case L2CAP_STATE_WAIT_CONNECT_RSP:
1198             switch (code){
1199                 case CONNECTION_RESPONSE:
1200                     l2cap_stop_rtx(channel);
1201                     result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1202                     switch (result) {
1203                         case 0:
1204                             // successful connection
1205                             channel->remote_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1206                             channel->state = L2CAP_STATE_CONFIG;
1207                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1208                             break;
1209                         case 1:
1210                             // connection pending. get some coffee, but start the ERTX
1211                             l2cap_start_ertx(channel);
1212                             break;
1213                         default:
1214                             // channel closed
1215                             channel->state = L2CAP_STATE_CLOSED;
1216                             // map l2cap connection response result to BTstack status enumeration
1217                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1218 
1219                             // drop link key if security block
1220                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
1221                                 hci_drop_link_key_for_bd_addr(channel->address);
1222                             }
1223 
1224                             // discard channel
1225                             linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
1226                             btstack_memory_l2cap_channel_free(channel);
1227                             break;
1228                     }
1229                     break;
1230 
1231                 default:
1232                     //@TODO: implement other signaling packets
1233                     break;
1234             }
1235             break;
1236 
1237         case L2CAP_STATE_CONFIG:
1238             result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1239             switch (code) {
1240                 case CONFIGURE_REQUEST:
1241                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1242                     l2cap_signaling_handle_configure_request(channel, command);
1243                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
1244                         // only done if continuation not set
1245                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
1246                     }
1247                     break;
1248                 case CONFIGURE_RESPONSE:
1249                     l2cap_stop_rtx(channel);
1250                     switch (result){
1251                         case 0: // success
1252                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
1253                             break;
1254                         case 4: // pending
1255                             l2cap_start_ertx(channel);
1256                             break;
1257                         default:
1258                             // retry on negative result
1259                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1260                             break;
1261                     }
1262                     break;
1263                 default:
1264                     break;
1265             }
1266             if (l2cap_channel_ready_for_open(channel)){
1267                 // for open:
1268                 channel->state = L2CAP_STATE_OPEN;
1269                 l2cap_emit_channel_opened(channel, 0);
1270                 l2cap_emit_credits(channel, 1);
1271             }
1272             break;
1273 
1274         case L2CAP_STATE_WAIT_DISCONNECT:
1275             switch (code) {
1276                 case DISCONNECTION_RESPONSE:
1277                     l2cap_finialize_channel_close(channel);
1278                     break;
1279                 default:
1280                     //@TODO: implement other signaling packets
1281                     break;
1282             }
1283             break;
1284 
1285         case L2CAP_STATE_CLOSED:
1286             // @TODO handle incoming requests
1287             break;
1288 
1289         case L2CAP_STATE_OPEN:
1290             //@TODO: implement other signaling packets, e.g. re-configure
1291             break;
1292         default:
1293             break;
1294     }
1295     // log_info("new state %u", channel->state);
1296 }
1297 
1298 
1299 static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
1300 
1301     // get code, signalind identifier and command len
1302     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1303     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1304 
1305     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
1306     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
1307         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1308         return;
1309     }
1310 
1311     // general commands without an assigned channel
1312     switch(code) {
1313 
1314         case CONNECTION_REQUEST: {
1315             uint16_t psm =        READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1316             uint16_t source_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
1317             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
1318             return;
1319         }
1320 
1321         case ECHO_REQUEST:
1322             l2cap_register_signaling_response(handle, code, sig_id, 0);
1323             return;
1324 
1325         case INFORMATION_REQUEST: {
1326             uint16_t infoType = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1327             l2cap_register_signaling_response(handle, code, sig_id, infoType);
1328             return;
1329         }
1330 
1331         default:
1332             break;
1333     }
1334 
1335 
1336     // Get potential destination CID
1337     uint16_t dest_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1338 
1339     // Find channel for this sig_id and connection handle
1340     linked_list_iterator_t it;
1341     linked_list_iterator_init(&it, &l2cap_channels);
1342     while (linked_list_iterator_has_next(&it)){
1343         l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it);
1344         if (channel->handle != handle) continue;
1345         if (code & 1) {
1346             // match odd commands (responses) by previous signaling identifier
1347             if (channel->local_sig_id == sig_id) {
1348                 l2cap_signaling_handler_channel(channel, command);
1349                 break;
1350             }
1351         } else {
1352             // match even commands (requests) by local channel id
1353             if (channel->local_cid == dest_cid) {
1354                 l2cap_signaling_handler_channel(channel, command);
1355                 break;
1356             }
1357         }
1358     }
1359 }
1360 
1361 static void l2cap_acl_handler( uint8_t *packet, uint16_t size ){
1362 
1363     // Get Channel ID
1364     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
1365     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
1366 
1367     switch (channel_id) {
1368 
1369         case L2CAP_CID_SIGNALING: {
1370 
1371             uint16_t command_offset = 8;
1372             while (command_offset < size) {
1373 
1374                 // handle signaling commands
1375                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
1376 
1377                 // increment command_offset
1378                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + READ_BT_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1379             }
1380             break;
1381         }
1382 
1383         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1384             if (attribute_protocol_packet_handler) {
1385                 (*attribute_protocol_packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1386             }
1387             break;
1388 
1389         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1390             if (security_protocol_packet_handler) {
1391                 (*security_protocol_packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1392             }
1393             break;
1394 
1395         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1396             if (connectionless_channel_packet_handler) {
1397                 (*connectionless_channel_packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1398             }
1399             break;
1400 
1401         case L2CAP_CID_SIGNALING_LE: {
1402             switch (packet[8]){
1403                 case CONNECTION_PARAMETER_UPDATE_RESPONSE: {
1404                     uint16_t result = READ_BT_16(packet, 12);
1405                     l2cap_emit_connection_parameter_update_response(handle, result);
1406                     break;
1407                 }
1408                 case CONNECTION_PARAMETER_UPDATE_REQUEST: {
1409                     uint8_t event[10];
1410                     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
1411                     event[1] = 8;
1412                     memcpy(&event[2], &packet[12], 8);
1413 
1414                     hci_connection_t * connection = hci_connection_for_handle(handle);
1415                     if (connection){
1416                         if (connection->role != HCI_ROLE_MASTER){
1417                             // reject command without notifying upper layer when not in master role
1418                             uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
1419                             l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1420                             break;
1421                         }
1422                         int update_parameter = 1;
1423                         le_connection_parameter_range_t existing_range;
1424                         gap_le_get_connection_parameter_range(existing_range);
1425                         uint16_t le_conn_interval_min = READ_BT_16(packet,12);
1426                         uint16_t le_conn_interval_max = READ_BT_16(packet,14);
1427                         uint16_t le_conn_latency = READ_BT_16(packet,16);
1428                         uint16_t le_supervision_timeout = READ_BT_16(packet,18);
1429 
1430                         if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
1431                         if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
1432 
1433                         if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
1434                         if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
1435 
1436                         if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
1437                         if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
1438 
1439                         if (update_parameter){
1440                             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
1441                             connection->le_conn_interval_min = le_conn_interval_min;
1442                             connection->le_conn_interval_max = le_conn_interval_max;
1443                             connection->le_conn_latency = le_conn_latency;
1444                             connection->le_supervision_timeout = le_supervision_timeout;
1445                         } else {
1446                             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
1447                         }
1448                         connection->le_con_param_update_identifier = packet[COMPLETE_L2CAP_HEADER + 1];
1449                     }
1450 
1451                     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1452                     (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, event, sizeof(event));
1453 
1454                     break;
1455                 }
1456                 default: {
1457                     uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
1458                     l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1459                     break;
1460                 }
1461             }
1462             break;
1463         }
1464 
1465         default: {
1466             // Find channel for this channel_id and connection handle
1467             l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(channel_id);
1468             if (channel) {
1469                 l2cap_dispatch(channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1470             }
1471             break;
1472         }
1473     }
1474 }
1475 
1476 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1477     switch (packet_type) {
1478         case HCI_EVENT_PACKET:
1479             l2cap_event_handler(packet, size);
1480             break;
1481         case HCI_ACL_DATA_PACKET:
1482             l2cap_acl_handler(packet, size);
1483             break;
1484         default:
1485             break;
1486     }
1487     l2cap_run();
1488 }
1489 
1490 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
1491 void l2cap_finialize_channel_close(l2cap_channel_t *channel){
1492     channel->state = L2CAP_STATE_CLOSED;
1493     l2cap_emit_channel_closed(channel);
1494     // discard channel
1495     l2cap_stop_rtx(channel);
1496     linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
1497     btstack_memory_l2cap_channel_free(channel);
1498 }
1499 
1500 static l2cap_service_t * l2cap_get_service_internal(linked_list_t * services, uint16_t psm){
1501     linked_list_iterator_t it;
1502     linked_list_iterator_init(&it, services);
1503     while (linked_list_iterator_has_next(&it)){
1504         l2cap_service_t * service = (l2cap_service_t *) linked_list_iterator_next(&it);
1505         if ( service->psm == psm){
1506             return service;
1507         };
1508     }
1509     return NULL;
1510 }
1511 
1512 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
1513     return l2cap_get_service_internal(&l2cap_services, psm);
1514 }
1515 
1516 void l2cap_register_service_internal(void *connection, btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
1517 
1518     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u connection %p", psm, mtu, connection);
1519 
1520     // check for alread registered psm
1521     // TODO: emit error event
1522     l2cap_service_t *service = l2cap_get_service(psm);
1523     if (service) {
1524         log_error("l2cap_register_service_internal: PSM %u already registered", psm);
1525         l2cap_emit_service_registered(connection, L2CAP_SERVICE_ALREADY_REGISTERED, psm);
1526         return;
1527     }
1528 
1529     // alloc structure
1530     // TODO: emit error event
1531     service = btstack_memory_l2cap_service_get();
1532     if (!service) {
1533         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
1534         l2cap_emit_service_registered(connection, BTSTACK_MEMORY_ALLOC_FAILED, psm);
1535         return;
1536     }
1537 
1538     // fill in
1539     service->psm = psm;
1540     service->mtu = mtu;
1541     service->connection = connection;
1542     service->packet_handler = service_packet_handler;
1543     service->required_security_level = security_level;
1544 
1545     // add to services list
1546     linked_list_add(&l2cap_services, (linked_item_t *) service);
1547 
1548     // enable page scan
1549     hci_connectable_control(1);
1550 
1551     // done
1552     l2cap_emit_service_registered(connection, 0, psm);
1553 }
1554 
1555 void l2cap_unregister_service_internal(void *connection, uint16_t psm){
1556 
1557     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
1558 
1559     l2cap_service_t *service = l2cap_get_service(psm);
1560     if (!service) return;
1561     linked_list_remove(&l2cap_services, (linked_item_t *) service);
1562     btstack_memory_l2cap_service_free(service);
1563 
1564     // disable page scan when no services registered
1565     if (!linked_list_empty(&l2cap_services)) return;
1566     hci_connectable_control(0);
1567 }
1568 
1569 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
1570 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
1571     switch(channel_id){
1572         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1573             attribute_protocol_packet_handler = the_packet_handler;
1574             break;
1575         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1576             security_protocol_packet_handler = the_packet_handler;
1577             break;
1578         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1579             connectionless_channel_packet_handler = the_packet_handler;
1580             break;
1581     }
1582 }
1583 
1584 #ifdef HAVE_BLE
1585 
1586 
1587 #if 0
1588 static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm){
1589     return l2cap_get_service_internal(&l2cap_le_services, psm);
1590 }
1591 /**
1592  * @brief Regster L2CAP LE Credit Based Flow Control Mode service
1593  * @param
1594  */
1595 void l2cap_le_register_service_internal(void * connection, btstack_packet_handler_t packet_handler, uint16_t psm,
1596     uint16_t mtu, uint16_t mps, uint16_t initial_credits, gap_security_level_t security_level){
1597 
1598     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x mtu %u connection %p", psm, mtu, connection);
1599 
1600     // check for alread registered psm
1601     // TODO: emit error event
1602     l2cap_service_t *service = l2cap_le_get_service(psm);
1603     if (service) {
1604         log_error("l2cap_le_register_service_internal: PSM %u already registered", psm);
1605         l2cap_emit_service_registered(connection, L2CAP_SERVICE_ALREADY_REGISTERED, psm);
1606         return;
1607     }
1608 
1609     // alloc structure
1610     // TODO: emit error event
1611     service = btstack_memory_l2cap_service_get();
1612     if (!service) {
1613         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
1614         l2cap_emit_service_registered(connection, BTSTACK_MEMORY_ALLOC_FAILED, psm);
1615         return;
1616     }
1617 
1618     // fill in
1619     service->psm = psm;
1620     service->mtu = mtu;
1621     service->mps = mps;
1622     service->connection = connection;
1623     service->packet_handler = packet_handler;
1624     service->required_security_level = security_level;
1625 
1626     // add to services list
1627     linked_list_add(&l2cap_le_services, (linked_item_t *) service);
1628 
1629     // done
1630     l2cap_emit_service_registered(connection, 0, psm);
1631 }
1632 
1633 void l2cap_le_unregister_service_internal(void * connection, uint16_t psm) {
1634 
1635     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
1636 
1637     l2cap_service_t *service = l2cap_le_get_service(psm);
1638     if (!service) return;
1639     linked_list_remove(&l2cap_le_services, (linked_item_t *) service);
1640     btstack_memory_l2cap_service_free(service);
1641 }
1642 #endif
1643 #endif
1644