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