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