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