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