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