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