xref: /btstack/src/l2cap.c (revision b1d43497a558ff7325db97cb370c09308c2c93e4)
1 /*
2  * Copyright (C) 2009 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  *
17  * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
21  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 /*
33  *  l2cap.c
34  *
35  *  Logical Link Control and Adaption Protocl (L2CAP)
36  *
37  *  Created by Matthias Ringwald on 5/16/09.
38  */
39 
40 #include "l2cap.h"
41 #include "hci.h"
42 #include "hci_dump.h"
43 #include "debug.h"
44 #include "btstack_memory.h"
45 
46 #include <stdarg.h>
47 #include <string.h>
48 
49 #include <stdio.h>
50 
51 // size of HCI ACL + L2CAP Header for regular data packets (8)
52 #define COMPLETE_L2CAP_HEADER (HCI_ACL_HEADER_SIZE + L2CAP_HEADER_SIZE)
53 
54 // minimum signaling MTU
55 #define L2CAP_MINIMAL_MTU 48
56 #define L2CAP_DEFAULT_MTU 672
57 
58 // nr of buffered acl packets in outgoing queue to get max performance
59 #define NR_BUFFERED_ACL_PACKETS 3
60 
61 // used to cache l2cap rejects, echo, and informational requests
62 #define NR_PENDING_SIGNALING_RESPONSES 5
63 
64 // offsets for L2CAP SIGNALING COMMANDS
65 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
66 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
67 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
68 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
69 
70 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
71 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
72 
73 // used to cache l2cap rejects, echo, and informational requests
74 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
75 static int signaling_responses_pending;
76 
77 static linked_list_t l2cap_channels = NULL;
78 static linked_list_t l2cap_services = NULL;
79 static void (*packet_handler) (void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) = null_packet_handler;
80 static int new_credits_blocked = 0;
81 
82 // prototypes
83 static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
84 static l2cap_service_t * l2cap_get_service(uint16_t psm);
85 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
86 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
87 static void l2cap_emit_connection_request(l2cap_channel_t *channel);
88 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel);
89 
90 
91 void l2cap_init(){
92 
93     new_credits_blocked = 0;
94     signaling_responses_pending = 0;
95 
96     //
97     // register callback with HCI
98     //
99     hci_register_packet_handler(&l2cap_packet_handler);
100 }
101 
102 
103 /** Register L2CAP packet handlers */
104 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
105 }
106 void l2cap_register_packet_handler(void (*handler)(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
107     packet_handler = handler;
108 }
109 
110 //  notify client/protocol handler
111 void l2cap_dispatch(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
112     if (channel->packet_handler) {
113         (* (channel->packet_handler))(type, channel->local_cid, data, size);
114     } else {
115         (*packet_handler)(channel->connection, type, channel->local_cid, data, size);
116     }
117 }
118 
119 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
120     uint8_t event[21];
121     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
122     event[1] = sizeof(event) - 2;
123     event[2] = status;
124     bt_flip_addr(&event[3], channel->address);
125     bt_store_16(event,  9, channel->handle);
126     bt_store_16(event, 11, channel->psm);
127     bt_store_16(event, 13, channel->local_cid);
128     bt_store_16(event, 15, channel->remote_cid);
129     bt_store_16(event, 17, channel->local_mtu);
130     bt_store_16(event, 19, channel->remote_mtu);
131     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
132     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
133 }
134 
135 void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
136     uint8_t event[4];
137     event[0] = L2CAP_EVENT_CHANNEL_CLOSED;
138     event[1] = sizeof(event) - 2;
139     bt_store_16(event, 2, channel->local_cid);
140     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
141     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
142 }
143 
144 void l2cap_emit_connection_request(l2cap_channel_t *channel) {
145     uint8_t event[16];
146     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
147     event[1] = sizeof(event) - 2;
148     bt_flip_addr(&event[2], channel->address);
149     bt_store_16(event,  8, channel->handle);
150     bt_store_16(event, 10, channel->psm);
151     bt_store_16(event, 12, channel->local_cid);
152     bt_store_16(event, 14, channel->remote_cid);
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_credits(l2cap_channel_t *channel, uint8_t credits) {
158     // track credits
159     channel->packets_granted += credits;
160     // log_info("l2cap_emit_credits for cid %u, credits given: %u (+%u)\n", channel->local_cid, channel->packets_granted, credits);
161 
162     uint8_t event[5];
163     event[0] = L2CAP_EVENT_CREDITS;
164     event[1] = sizeof(event) - 2;
165     bt_store_16(event, 2, channel->local_cid);
166     event[4] = credits;
167     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
168     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
169 }
170 
171 void l2cap_block_new_credits(uint8_t blocked){
172     new_credits_blocked = blocked;
173 }
174 
175 void l2cap_hand_out_credits(void){
176 
177     if (new_credits_blocked) return;    // we're told not to. used by daemon
178 
179     linked_item_t *it;
180     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
181         if (!hci_number_free_acl_slots()) return;
182         l2cap_channel_t * channel = (l2cap_channel_t *) it;
183         if (channel->state != L2CAP_STATE_OPEN) continue;
184         if (hci_number_outgoing_packets(channel->handle) < NR_BUFFERED_ACL_PACKETS && channel->packets_granted == 0) {
185             l2cap_emit_credits(channel, 1);
186         }
187     }
188 }
189 
190 l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
191     linked_item_t *it;
192     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
193         l2cap_channel_t * channel = (l2cap_channel_t *) it;
194         if ( channel->local_cid == local_cid) {
195             return channel;
196         }
197     }
198     return NULL;
199 }
200 
201 int  l2cap_can_send_packet_now(uint16_t local_cid){
202     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
203     if (!channel) return 0;
204     if (!channel->packets_granted) return 0;
205     return hci_can_send_packet_now(HCI_ACL_DATA_PACKET);
206 }
207 
208 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
209     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
210     if (channel) {
211         return channel->remote_mtu;
212     }
213     return 0;
214 }
215 
216 int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
217 
218     if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)){
219         log_info("l2cap_send_signaling_packet, cannot send\n");
220         return BTSTACK_ACL_BUFFERS_FULL;
221     }
222 
223     // log_info("l2cap_send_signaling_packet type %u\n", cmd);
224     uint8_t *acl_buffer = hci_get_outgoing_acl_packet_buffer();
225     va_list argptr;
226     va_start(argptr, identifier);
227     uint16_t len = l2cap_create_signaling_internal(acl_buffer, handle, cmd, identifier, argptr);
228     va_end(argptr);
229     // log_info("l2cap_send_signaling_packet con %u!\n", handle);
230     return hci_send_acl_packet(acl_buffer, len);
231 }
232 
233 uint8_t *l2cap_get_outgoing_buffer(void){
234     return hci_get_outgoing_acl_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
235 }
236 
237 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
238 
239     if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)){
240         log_info("l2cap_send_internal cid %u, cannot send\n", local_cid);
241         return BTSTACK_ACL_BUFFERS_FULL;
242     }
243 
244     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
245     if (!channel) {
246         log_error("l2cap_send_internal no channel for cid %u\n", local_cid);
247         return -1;   // TODO: define error
248     }
249 
250     if (channel->packets_granted == 0){
251         log_error("l2cap_send_internal cid %u, no credits!\n", local_cid);
252         return -1;  // TODO: define error
253     }
254 
255     --channel->packets_granted;
256 
257     log_debug("l2cap_send_internal cid %u, handle %u, 1 credit used, credits left %u;\n",
258                   local_cid, channel->handle, channel->packets_granted);
259 
260     uint8_t *acl_buffer = hci_get_outgoing_acl_packet_buffer();
261 
262     // 0 - Connection handle : PB=10 : BC=00
263     bt_store_16(acl_buffer, 0, channel->handle | (2 << 12) | (0 << 14));
264     // 2 - ACL length
265     bt_store_16(acl_buffer, 2,  len + 4);
266     // 4 - L2CAP packet length
267     bt_store_16(acl_buffer, 4,  len + 0);
268     // 6 - L2CAP channel DEST
269     bt_store_16(acl_buffer, 6, channel->remote_cid);
270     // send
271     int err = hci_send_acl_packet(acl_buffer, len+8);
272 
273     l2cap_hand_out_credits();
274 
275     return err;
276 }
277 
278 int l2cap_send_internal(uint16_t local_cid, uint8_t *data, uint16_t len){
279 
280     if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)){
281         log_info("l2cap_send_internal cid %u, cannot send\n", local_cid);
282         return BTSTACK_ACL_BUFFERS_FULL;
283     }
284 
285     uint8_t *acl_buffer = hci_get_outgoing_acl_packet_buffer();
286 
287     memcpy(&acl_buffer[8], data, len);
288 
289     return l2cap_send_prepared(local_cid, len);
290 }
291 
292 
293 // MARK: L2CAP_RUN
294 // process outstanding signaling tasks
295 void l2cap_run(void){
296 
297     // check pending signaling responses
298     while (signaling_responses_pending){
299 
300         if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)) break;
301 
302         hci_con_handle_t handle = signaling_responses[0].handle;
303         uint8_t sig_id = signaling_responses[0].sig_id;
304         uint16_t infoType = signaling_responses[0].data;    // INFORMATION_REQUEST
305         uint16_t result   = signaling_responses[0].data;    // CONNECTION_REQUEST
306 
307         switch (signaling_responses[0].code){
308             case CONNECTION_REQUEST:
309                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, result, 0);
310                 break;
311             case ECHO_REQUEST:
312                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
313                 break;
314             case INFORMATION_REQUEST:
315                 if (infoType == 2) {
316                     uint32_t features = 0;
317                     // extended features request supported, however no features present
318                     l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, 4, &features);
319                 } else {
320                     // all other types are not supported
321                     l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
322                 }
323                 break;
324             default:
325                 // should not happen
326                 break;
327         }
328 
329         // remove first item
330         signaling_responses_pending--;
331         int i;
332         for (i=0; i < signaling_responses_pending; i++){
333             signaling_responses[i] = signaling_responses[i+1];
334         }
335     }
336 
337     uint8_t  config_options[4];
338     linked_item_t *it;
339     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
340 
341         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) break;
342         if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)) break;
343 
344         l2cap_channel_t * channel = (l2cap_channel_t *) it;
345 
346         // log_info("l2cap_run: state %u, var 0x%02x\n", channel->state, channel->state_var);
347 
348         switch (channel->state){
349 
350             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
351                 // send connection request - set state first
352                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
353                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
354                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
355                 break;
356 
357             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
358                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, channel->reason, 0);
359                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
360                 linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
361                 btstack_memory_l2cap_channel_free(channel);
362                 break;
363 
364             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
365                 channel->state = L2CAP_STATE_CONFIG;
366                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ;
367                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
368                 break;
369 
370             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
371                 // success, start l2cap handshake
372                 channel->local_sig_id = l2cap_next_sig_id();
373                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
374                 l2cap_send_signaling_packet( channel->handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
375                 break;
376 
377             case L2CAP_STATE_CONFIG:
378                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
379                     channel->state_var &= ~L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP;
380                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP;
381                     l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, 0, 0, 0, NULL);
382                 }
383                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
384                     channel->state_var &= ~L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ;
385                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ;
386                     channel->local_sig_id = l2cap_next_sig_id();
387                     config_options[0] = 1; // MTU
388                     config_options[1] = 2; // len param
389                     bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
390                     l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options);
391                 }
392                 if (l2cap_channel_ready_for_open(channel)){
393                     channel->state = L2CAP_STATE_OPEN;
394                     l2cap_emit_channel_opened(channel, 0);  // success
395                     l2cap_emit_credits(channel, 1);
396                 }
397                 break;
398 
399             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
400                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
401                 l2cap_finialize_channel_close(channel);
402                 break;
403 
404             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
405                 channel->local_sig_id = l2cap_next_sig_id();
406                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
407                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
408                 break;
409             default:
410                 break;
411         }
412     }
413 }
414 
415 static uint16_t l2cap_max_l2cap_mtu(void){
416     return hci_max_acl_data_packet_length() - L2CAP_HEADER_SIZE;
417 }
418 
419 // open outgoing L2CAP channel
420 void l2cap_create_channel_internal(void * connection, btstack_packet_handler_t packet_handler,
421                                    bd_addr_t address, uint16_t psm, uint16_t mtu){
422 
423     // alloc structure
424     l2cap_channel_t * chan = btstack_memory_l2cap_channel_get();
425     if (!chan) {
426         // emit error event
427         l2cap_channel_t dummy_channel;
428         BD_ADDR_COPY(dummy_channel.address, address);
429         dummy_channel.psm = psm;
430         l2cap_emit_channel_opened(&dummy_channel, BTSTACK_MEMORY_ALLOC_FAILED);
431         return;
432     }
433     // limit local mtu to max acl packet length
434     if (mtu > l2cap_max_l2cap_mtu()) {
435         mtu = l2cap_max_l2cap_mtu();
436     }
437 
438     // fill in
439     BD_ADDR_COPY(chan->address, address);
440     chan->psm = psm;
441     chan->handle = 0;
442     chan->connection = connection;
443     chan->packet_handler = packet_handler;
444     chan->remote_mtu = L2CAP_MINIMAL_MTU;
445     chan->local_mtu = mtu;
446     chan->packets_granted = 0;
447 
448     // set initial state
449     chan->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
450     chan->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
451     chan->remote_sig_id = L2CAP_SIG_ID_INVALID;
452     chan->local_sig_id = L2CAP_SIG_ID_INVALID;
453 
454     // add to connections list
455     linked_list_add(&l2cap_channels, (linked_item_t *) chan);
456 
457     l2cap_run();
458 }
459 
460 void l2cap_disconnect_internal(uint16_t local_cid, uint8_t reason){
461     // find channel for local_cid
462     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
463     if (channel) {
464         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
465     }
466     // process
467     l2cap_run();
468 }
469 
470 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
471     linked_item_t *it = (linked_item_t *) &l2cap_channels;
472     while (it->next){
473         l2cap_channel_t * channel = (l2cap_channel_t *) it->next;
474         if ( ! BD_ADDR_CMP( channel->address, address) ){
475             if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
476                 // failure, forward error code
477                 l2cap_emit_channel_opened(channel, status);
478                 // discard channel
479                 it->next = it->next->next;
480                 btstack_memory_l2cap_channel_free(channel);
481             }
482         } else {
483             it = it->next;
484         }
485     }
486 }
487 
488 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
489     linked_item_t *it;
490     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
491         l2cap_channel_t * channel = (l2cap_channel_t *) it;
492         if ( ! BD_ADDR_CMP( channel->address, address) ){
493             if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
494                 // success, start l2cap handshake
495                 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
496                 channel->handle = handle;
497                 channel->local_cid = l2cap_next_local_cid();
498             }
499         }
500     }
501     // process
502     l2cap_run();
503 }
504 
505 void l2cap_event_handler( uint8_t *packet, uint16_t size ){
506 
507     bd_addr_t address;
508     hci_con_handle_t handle;
509     l2cap_channel_t * channel;
510     linked_item_t *it;
511     int hci_con_used;
512 
513     switch(packet[0]){
514 
515         // handle connection complete events
516         case HCI_EVENT_CONNECTION_COMPLETE:
517             bt_flip_addr(address, &packet[5]);
518             if (packet[2] == 0){
519                 handle = READ_BT_16(packet, 3);
520                 l2cap_handle_connection_success_for_addr(address, handle);
521             } else {
522                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
523             }
524             break;
525 
526         // handle successful create connection cancel command
527         case HCI_EVENT_COMMAND_COMPLETE:
528             if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) {
529                 if (packet[5] == 0){
530                     bt_flip_addr(address, &packet[6]);
531                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
532                     l2cap_handle_connection_failed_for_addr(address, 0x16);
533                 }
534             }
535             l2cap_run();    // try sending signaling packets first
536             break;
537 
538         case HCI_EVENT_COMMAND_STATUS:
539             l2cap_run();    // try sending signaling packets first
540             break;
541 
542         // handle disconnection complete events
543         case HCI_EVENT_DISCONNECTION_COMPLETE:
544             // send l2cap disconnect events for all channels on this handle
545             handle = READ_BT_16(packet, 3);
546             it = (linked_item_t *) &l2cap_channels;
547             while (it->next){
548                 l2cap_channel_t * channel = (l2cap_channel_t *) it->next;
549                 if ( channel->handle == handle ){
550                     // update prev item before free'ing next element - don't call l2cap_finalize_channel_close
551                     it->next = it->next->next;
552                     l2cap_emit_channel_closed(channel);
553                     btstack_memory_l2cap_channel_free(channel);
554                 } else {
555                     it = it->next;
556                 }
557             }
558             break;
559 
560         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
561             l2cap_run();    // try sending signaling packets first
562             l2cap_hand_out_credits();
563             break;
564 
565         // HCI Connection Timeouts
566         case L2CAP_EVENT_TIMEOUT_CHECK:
567             handle = READ_BT_16(packet, 2);
568             if (hci_authentication_active_for_handle(handle)) break;
569             hci_con_used = 0;
570             for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
571                 channel = (l2cap_channel_t *) it;
572                 if (channel->handle == handle) {
573                     hci_con_used = 1;
574                 }
575             }
576             if (hci_con_used) break;
577             if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) break;
578             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
579             break;
580 
581         case DAEMON_EVENT_HCI_PACKET_SENT:
582             for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
583                 channel = (l2cap_channel_t *) it;
584                 if (channel->packet_handler) {
585                     (* (channel->packet_handler))(HCI_EVENT_PACKET, channel->local_cid, packet, size);
586                 }
587             }
588             break;
589 
590         default:
591             break;
592     }
593 
594     // pass on
595     (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, packet, size);
596 }
597 
598 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
599     channel->remote_sig_id = identifier;
600     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
601     l2cap_run();
602 }
603 
604 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){
605     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
606         signaling_responses[signaling_responses_pending].handle = handle;
607         signaling_responses[signaling_responses_pending].code = code;
608         signaling_responses[signaling_responses_pending].sig_id = sig_id;
609         signaling_responses[signaling_responses_pending].data = data;
610         signaling_responses_pending++;
611         l2cap_run();
612     }
613 }
614 
615 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
616 
617     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid %u\n", handle, psm, source_cid);
618     l2cap_service_t *service = l2cap_get_service(psm);
619     if (!service) {
620         // 0x0002 PSM not supported
621         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002);
622         return;
623     }
624 
625     hci_connection_t * hci_connection = connection_for_handle( handle );
626     if (!hci_connection) {
627         //
628         log_error("no hci_connection for handle %u\n", handle);
629         return;
630     }
631     // alloc structure
632     // log_info("l2cap_handle_connection_request register channel\n");
633     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
634     if (!channel){
635         // 0x0004 No resources available
636         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004);
637         return;
638     }
639 
640     // fill in
641     BD_ADDR_COPY(channel->address, hci_connection->address);
642     channel->psm = psm;
643     channel->handle = handle;
644     channel->connection = service->connection;
645     channel->packet_handler = service->packet_handler;
646     channel->local_cid  = l2cap_next_local_cid();
647     channel->remote_cid = source_cid;
648     channel->local_mtu  = service->mtu;
649     channel->remote_mtu = L2CAP_DEFAULT_MTU;
650     channel->packets_granted = 0;
651     channel->remote_sig_id = sig_id;
652 
653     // limit local mtu to max acl packet length
654     if (channel->local_mtu > l2cap_max_l2cap_mtu()) {
655         channel->local_mtu = l2cap_max_l2cap_mtu();
656     }
657 
658     // set initial state
659     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
660     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
661 
662     // add to connections list
663     linked_list_add(&l2cap_channels, (linked_item_t *) channel);
664 
665     // emit incoming connection request
666     l2cap_emit_connection_request(channel);
667 }
668 
669 void l2cap_accept_connection_internal(uint16_t local_cid){
670     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
671     if (!channel) {
672         log_error("l2cap_accept_connection_internal called but local_cid 0x%x not found", local_cid);
673         return;
674     }
675 
676     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
677 
678     // process
679     l2cap_run();
680 }
681 
682 void l2cap_decline_connection_internal(uint16_t local_cid, uint8_t reason){
683     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
684     if (!channel) {
685         log_error( "l2cap_decline_connection_internal called but local_cid 0x%x not found", local_cid);
686         return;
687     }
688     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
689     channel->reason = reason;
690     l2cap_run();
691 }
692 
693 void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
694 
695     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
696 
697     // accept the other's configuration options
698     uint16_t end_pos = 4 + READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
699     uint16_t pos     = 8;
700     while (pos < end_pos){
701         uint8_t type   = command[pos++];
702         uint8_t length = command[pos++];
703         // MTU { type(8): 1, len(8):2, MTU(16) }
704         if ((type & 0x7f) == 1 && length == 2){
705             channel->remote_mtu = READ_BT_16(command, pos);
706             // log_info("l2cap cid %u, remote mtu %u\n", channel->local_cid, channel->remote_mtu);
707         }
708         pos += length;
709     }
710 }
711 
712 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
713     // log_info("l2cap_channel_ready_for_open 0x%02x\n", channel->state_var);
714     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
715     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
716     return 1;
717 }
718 
719 
720 void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
721 
722     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
723     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
724     uint16_t result = 0;
725 
726     log_info("signaling handler code %u, state %u\n", code, channel->state);
727 
728     // handle DISCONNECT REQUESTS seperately
729     if (code == DISCONNECTION_REQUEST){
730         switch (channel->state){
731             case L2CAP_STATE_CONFIG:
732             case L2CAP_STATE_OPEN:
733             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
734             case L2CAP_STATE_WAIT_DISCONNECT:
735                 l2cap_handle_disconnect_request(channel, identifier);
736                 break;
737 
738             default:
739                 // ignore in other states
740                 break;
741         }
742         return;
743     }
744 
745     switch (channel->state) {
746 
747         case L2CAP_STATE_WAIT_CONNECT_RSP:
748             switch (code){
749                 case CONNECTION_RESPONSE:
750                     result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
751                     switch (result) {
752                         case 0:
753                             // successful connection
754                             channel->remote_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
755                             channel->state = L2CAP_STATE_CONFIG;
756                             channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ;
757                             break;
758                         case 1:
759                             // connection pending. get some coffee
760                             break;
761                         default:
762                             // channel closed
763                             channel->state = L2CAP_STATE_CLOSED;
764 
765                             // map l2cap connection response result to BTstack status enumeration
766                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
767 
768                             // drop link key if security block
769                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
770                                 hci_drop_link_key_for_bd_addr(&channel->address);
771                             }
772 
773                             // discard channel
774                             linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
775                             btstack_memory_l2cap_channel_free(channel);
776                             break;
777                     }
778                     break;
779 
780                 default:
781                     //@TODO: implement other signaling packets
782                     break;
783             }
784             break;
785 
786         case L2CAP_STATE_CONFIG:
787             switch (code) {
788                 case CONFIGURE_REQUEST:
789                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ;
790                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP;
791                     l2cap_signaling_handle_configure_request(channel, command);
792                     break;
793                 case CONFIGURE_RESPONSE:
794                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP;
795                     break;
796                 default:
797                     break;
798             }
799             if (l2cap_channel_ready_for_open(channel)){
800                 // for open:
801                 channel->state = L2CAP_STATE_OPEN;
802                 l2cap_emit_channel_opened(channel, 0);
803                 l2cap_emit_credits(channel, 1);
804             }
805             break;
806 
807         case L2CAP_STATE_WAIT_DISCONNECT:
808             switch (code) {
809                 case DISCONNECTION_RESPONSE:
810                     l2cap_finialize_channel_close(channel);
811                     break;
812                 default:
813                     //@TODO: implement other signaling packets
814                     break;
815             }
816             break;
817 
818         case L2CAP_STATE_CLOSED:
819             // @TODO handle incoming requests
820             break;
821 
822         case L2CAP_STATE_OPEN:
823             //@TODO: implement other signaling packets, e.g. re-configure
824             break;
825         default:
826             break;
827     }
828     // log_info("new state %u\n", channel->state);
829 }
830 
831 
832 void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
833 
834     // get code, signalind identifier and command len
835     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
836     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
837 
838     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
839     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
840         return;
841     }
842 
843     // general commands without an assigned channel
844     switch(code) {
845 
846         case CONNECTION_REQUEST: {
847             uint16_t psm =        READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
848             uint16_t source_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
849             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
850             return;
851         }
852 
853         case ECHO_REQUEST:
854             l2cap_register_signaling_response(handle, code, sig_id, 0);
855             return;
856 
857         case INFORMATION_REQUEST: {
858             uint16_t infoType = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
859             l2cap_register_signaling_response(handle, code, sig_id, infoType);
860             return;
861         }
862 
863         default:
864             break;
865     }
866 
867 
868     // Get potential destination CID
869     uint16_t dest_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
870 
871     // Find channel for this sig_id and connection handle
872     linked_item_t *it;
873     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
874         l2cap_channel_t * channel = (l2cap_channel_t *) it;
875         if (channel->handle == handle) {
876             if (code & 1) {
877                 // match odd commands (responses) by previous signaling identifier
878                 if (channel->local_sig_id == sig_id) {
879                     l2cap_signaling_handler_channel(channel, command);
880                     break;
881                 }
882             } else {
883                 // match even commands (requests) by local channel id
884                 if (channel->local_cid == dest_cid) {
885                     l2cap_signaling_handler_channel(channel, command);
886                     break;
887                 }
888             }
889         }
890     }
891 }
892 
893 void l2cap_acl_handler( uint8_t *packet, uint16_t size ){
894 
895     // Get Channel ID
896     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
897 
898     // Signaling Packet?
899     if (channel_id == 1) {
900 
901         // Get Connection
902         hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
903 
904         uint16_t command_offset = 8;
905         while (command_offset < size) {
906 
907             // handle signaling commands
908             l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
909 
910             // increment command_offset
911             command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + READ_BT_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
912         }
913 
914         l2cap_run();
915 
916         return;
917     }
918 
919     // Find channel for this channel_id and connection handle
920     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(channel_id);
921     if (channel) {
922         l2cap_dispatch(channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
923     }
924 }
925 
926 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
927     switch (packet_type) {
928         case HCI_EVENT_PACKET:
929             l2cap_event_handler(packet, size);
930             break;
931         case HCI_ACL_DATA_PACKET:
932             l2cap_acl_handler(packet, size);
933             break;
934         default:
935             break;
936     }
937 }
938 
939 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
940 void l2cap_finialize_channel_close(l2cap_channel_t *channel){
941     channel->state = L2CAP_STATE_CLOSED;
942     l2cap_emit_channel_closed(channel);
943     // discard channel
944     linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
945     btstack_memory_l2cap_channel_free(channel);
946 }
947 
948 l2cap_service_t * l2cap_get_service(uint16_t psm){
949     linked_item_t *it;
950 
951     // close open channels
952     for (it = (linked_item_t *) l2cap_services; it ; it = it->next){
953         l2cap_service_t * service = ((l2cap_service_t *) it);
954         if ( service->psm == psm){
955             return service;
956         };
957     }
958     return NULL;
959 }
960 
961 void l2cap_register_service_internal(void *connection, btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t mtu){
962     // check for alread registered psm
963     // TODO: emit error event
964     l2cap_service_t *service = l2cap_get_service(psm);
965     if (service) {
966         log_error("l2cap_register_service_internal: PSM %u already registered\n", psm);
967         return;
968     }
969 
970     // alloc structure
971     // TODO: emit error event
972     service = btstack_memory_l2cap_service_get();
973     if (!service) {
974         log_error("l2cap_register_service_internal: no memory for l2cap_service_t\n");
975         return;
976     }
977 
978     // fill in
979     service->psm = psm;
980     service->mtu = mtu;
981     service->connection = connection;
982     service->packet_handler = packet_handler;
983 
984     // add to services list
985     linked_list_add(&l2cap_services, (linked_item_t *) service);
986 }
987 
988 void l2cap_unregister_service_internal(void *connection, uint16_t psm){
989     l2cap_service_t *service = l2cap_get_service(psm);
990     if (!service) return;
991     linked_list_remove(&l2cap_services, (linked_item_t *) service);
992     btstack_memory_l2cap_service_free(service);
993 }
994 
995 //
996 void l2cap_close_connection(void *connection){
997     linked_item_t *it;
998 
999     // close open channels - note to myself: no channel is freed, so no new for fancy iterator tricks
1000     l2cap_channel_t * channel;
1001     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
1002         channel = (l2cap_channel_t *) it;
1003         if (channel->connection == connection) {
1004             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1005         }
1006     }
1007 
1008     // unregister services
1009     it = (linked_item_t *) &l2cap_services;
1010     while (it->next) {
1011         l2cap_service_t * service = (l2cap_service_t *) it->next;
1012         if (service->connection == connection){
1013             it->next = it->next->next;
1014             btstack_memory_l2cap_service_free(service);
1015         } else {
1016             it = it->next;
1017         }
1018     }
1019 
1020     // process
1021     l2cap_run();
1022 }
1023