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