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