xref: /btstack/src/l2cap.c (revision b502e1b06db478d8280c56de96ec265ba0519aa3)
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 
44 #include <stdarg.h>
45 #include <string.h>
46 
47 #include <stdio.h>
48 
49 // size of HCI ACL + L2CAP Header for regular data packets
50 #define COMPLETE_L2CAP_HEADER 8
51 
52 // minimum signaling MTU
53 #define L2CAP_MINIMAL_MTU 48
54 #define L2CAP_DEFAULT_MTU 672
55 
56 // offsets for L2CAP SIGNALING COMMANDS
57 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
58 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
59 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
60 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
61 
62 static void null_packet_handler(connection_t * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
63 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
64 
65 static uint8_t * sig_buffer = NULL;
66 static linked_list_t l2cap_channels = NULL;
67 static linked_list_t l2cap_services = NULL;
68 static uint8_t * acl_buffer = NULL;
69 static void (*packet_handler) (connection_t * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) = null_packet_handler;
70 static connection_t * capture_connection = NULL;
71 
72 static uint8_t config_options[] = { 1, 2, 150, 0}; // mtu = 48
73 
74 void l2cap_init(){
75     sig_buffer = malloc( L2CAP_MINIMAL_MTU );
76     // acl_buffer = malloc( 255 + 8 );
77     acl_buffer = malloc( 400 + 8 );
78 
79     //
80     // register callback with HCI
81     //
82     hci_register_packet_handler(&l2cap_packet_handler);
83 }
84 
85 
86 /** Register L2CAP packet handlers */
87 static void null_packet_handler(connection_t * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
88 }
89 void l2cap_register_packet_handler(void (*handler)(connection_t * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
90     packet_handler = handler;
91 }
92 
93 //  notify client/protocol handler
94 void l2cap_dispatch(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
95     if (channel->packet_handler) {
96         (* (channel->packet_handler))(type, channel->local_cid, data, size);
97     } else {
98         switch (type){
99             case HCI_EVENT_PACKET:
100                 (*packet_handler)(channel->connection, HCI_EVENT_PACKET, 0, data, size);
101                 break;
102             case L2CAP_DATA_PACKET:
103                 (*packet_handler)(channel->connection, L2CAP_DATA_PACKET, channel->local_cid, data, size);
104                 break;
105             default:
106                 // ??
107                 break;
108         }
109     }
110 }
111 
112 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
113     uint8_t event[17];
114     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
115     event[1] = sizeof(event) - 2;
116     event[2] = status;
117     bt_flip_addr(&event[3], channel->address);
118     bt_store_16(event,  9, channel->handle);
119     bt_store_16(event, 11, channel->psm);
120     bt_store_16(event, 13, channel->local_cid);
121     bt_store_16(event, 15, channel->remote_cid);
122     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
123     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
124 }
125 
126 void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
127     uint8_t event[4];
128     event[0] = L2CAP_EVENT_CHANNEL_CLOSED;
129     event[1] = sizeof(event) - 2;
130     bt_store_16(event, 2, channel->local_cid);
131     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
132     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
133 }
134 
135 void l2cap_emit_connection_request(l2cap_channel_t *channel) {
136     uint8_t event[16];
137     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
138     event[1] = sizeof(event) - 2;
139     bt_flip_addr(&event[2], channel->address);
140     bt_store_16(event,  8, channel->handle);
141     bt_store_16(event, 10, channel->psm);
142     bt_store_16(event, 12, channel->local_cid);
143     bt_store_16(event, 14, channel->remote_cid);
144     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
145     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
146 }
147 
148 l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
149     linked_item_t *it;
150     l2cap_channel_t * channel;
151     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
152         channel = (l2cap_channel_t *) it;
153         if ( channel->local_cid == local_cid) {
154             return channel;
155         }
156     }
157     return NULL;
158 }
159 
160 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
161     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
162     if (channel) {
163         return channel->remote_mtu;
164     }
165     return 0;
166 }
167 
168 int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
169     // printf("l2cap_send_signaling_packet type %u\n", cmd);
170     va_list argptr;
171     va_start(argptr, identifier);
172     uint16_t len = l2cap_create_signaling_internal(sig_buffer, handle, cmd, identifier, argptr);
173     va_end(argptr);
174     return hci_send_acl_packet(sig_buffer, len);
175 }
176 
177 void l2cap_send_internal(uint16_t local_cid, uint8_t *data, uint16_t len){
178     // find channel for local_cid, construct l2cap packet and send
179     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
180     if (channel) {
181         // 0 - Connection handle : PB=10 : BC=00
182         bt_store_16(acl_buffer, 0, channel->handle | (2 << 12) | (0 << 14));
183         // 2 - ACL length
184         bt_store_16(acl_buffer, 2,  len + 4);
185         // 4 - L2CAP packet length
186         bt_store_16(acl_buffer, 4,  len + 0);
187         // 6 - L2CAP channel DEST
188         bt_store_16(acl_buffer, 6, channel->remote_cid);
189         // 8 - data
190         memcpy(&acl_buffer[8], data, len);
191         // send
192         hci_send_acl_packet(acl_buffer, len+8);
193     }
194 }
195 
196 // open outgoing L2CAP channel
197 void l2cap_create_channel_internal(connection_t * connection, bd_addr_t address, uint16_t psm){
198 
199     // alloc structure
200     l2cap_channel_t * chan = malloc(sizeof(l2cap_channel_t));
201     // TODO: emit error event
202     if (!chan) return;
203 
204     // fill in
205     BD_ADDR_COPY(chan->address, address);
206     chan->psm = psm;
207     chan->handle = 0;
208     chan->connection = connection;
209     chan->packet_handler = NULL;
210     chan->remote_mtu = L2CAP_MINIMAL_MTU;
211 
212     // set initial state
213     chan->state = L2CAP_STATE_CLOSED;
214     chan->sig_id = L2CAP_SIG_ID_INVALID;
215 
216     // add to connections list
217     linked_list_add(&l2cap_channels, (linked_item_t *) chan);
218 
219     // send connection request
220     // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
221     hci_send_cmd(&hci_create_connection, address, 0x18, 0, 0, 0, 0);
222 }
223 
224 void l2cap_disconnect_internal(uint16_t local_cid, uint8_t reason){
225     // find channel for local_cid
226     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
227     if (channel) {
228         channel->sig_id = l2cap_next_sig_id();
229         l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->sig_id, channel->remote_cid, channel->local_cid);
230         channel->state = L2CAP_STATE_WAIT_DISCONNECT;
231     }
232 }
233 
234 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
235     linked_item_t *it;
236     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
237         l2cap_channel_t * channel = (l2cap_channel_t *) it;
238         if ( ! BD_ADDR_CMP( channel->address, address) ){
239             if (channel->state == L2CAP_STATE_CLOSED) {
240                 // failure, forward error code
241                 l2cap_emit_channel_opened(channel, status);
242                 // discard channel
243                 linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
244                 free (channel);
245             }
246         }
247     }
248 }
249 
250 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
251     linked_item_t *it;
252     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
253         l2cap_channel_t * channel = (l2cap_channel_t *) it;
254         if ( ! BD_ADDR_CMP( channel->address, address) ){
255             if (channel->state == L2CAP_STATE_CLOSED) {
256                 // success, start l2cap handshake
257                 channel->handle = handle;
258                 channel->sig_id = l2cap_next_sig_id();
259                 channel->local_cid = l2cap_next_local_cid();
260                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
261                 l2cap_send_signaling_packet( channel->handle, CONNECTION_REQUEST, channel->sig_id, channel->psm, channel->local_cid);
262             }
263         }
264     }
265 }
266 
267 void l2cap_event_handler( uint8_t *packet, uint16_t size ){
268 
269     bd_addr_t address;
270     hci_con_handle_t handle;
271 
272     switch(packet[0]){
273 
274         // handle connection complete events
275         case HCI_EVENT_CONNECTION_COMPLETE:
276             bt_flip_addr(address, &packet[5]);
277             if (packet[2] == 0){
278                 handle = READ_BT_16(packet, 3);
279                 l2cap_handle_connection_success_for_addr(address, handle);
280             } else {
281                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
282             }
283             break;
284 
285         // handle successful create connection cancel command
286         case HCI_EVENT_COMMAND_COMPLETE:
287             if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) {
288                 if (packet[5] == 0){
289                     bt_flip_addr(address, &packet[6]);
290                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
291                     l2cap_handle_connection_failed_for_addr(address, 0x16);
292                 }
293             }
294             break;
295 
296         // handle disconnection complete events
297         case HCI_EVENT_DISCONNECTION_COMPLETE:
298             // send l2cap disconnect events for all channels on this handle
299             handle = READ_BT_16(packet, 3);
300             linked_item_t *it;
301             // only access next element to allows for removal
302             for (it = (linked_item_t *) &l2cap_channels; it->next ; it = it->next){
303                 l2cap_channel_t * channel = (l2cap_channel_t *) it->next;
304                 if ( channel->handle == handle ){
305                     // update prev item before free'ing next element
306                     it->next = it->next->next;
307                     l2cap_finialize_channel_close(channel);
308                 }
309             }
310             break;
311 
312         // HCI Connection Timeouts
313         case L2CAP_EVENT_TIMEOUT_CHECK:
314             if (!capture_connection){
315                 hci_con_handle_t handle = READ_BT_16(packet, 2);
316                 linked_item_t *it;
317                 l2cap_channel_t * channel;
318                 int used = 0;
319                 for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
320                     channel = (l2cap_channel_t *) it;
321                     if (channel->handle == handle) {
322                         used = 1;
323                     }
324                 }
325                 if (!used) {
326                     hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
327                 }
328             }
329             break;
330 
331         default:
332             break;
333     }
334 
335     // pass on
336     (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, packet, size);
337 }
338 
339 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
340     l2cap_send_signaling_packet( channel->handle, DISCONNECTION_RESPONSE, identifier, channel->local_cid, channel->remote_cid);
341     l2cap_finialize_channel_close(channel);
342 }
343 
344 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
345 
346     // printf("l2cap_handle_connection_request for handle %u, psm %u cid %u\n", handle, psm, source_cid);
347     l2cap_service_t *service = l2cap_get_service(psm);
348     if (!service) {
349         // 0x0002 PSM not supported
350         // printf("l2cap_handle_connection_request no PSM for psm %u/n", psm);
351         l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, 0x0002, 0);
352         return;
353     }
354 
355     hci_connection_t * hci_connection = connection_for_handle( handle );
356     if (!hci_connection) {
357         fprintf(stderr, "no hci_connection for handle %u\n", handle);
358         // TODO: emit error
359         return;
360     }
361     // alloc structure
362     // printf("l2cap_handle_connection_request register channel\n");
363     l2cap_channel_t * channel = malloc(sizeof(l2cap_channel_t));
364     // TODO: emit error event
365     if (!channel) return;
366 
367     // fill in
368     BD_ADDR_COPY(channel->address, hci_connection->address);
369     channel->psm = psm;
370     channel->handle = handle;
371     channel->connection = service->connection;
372     channel->packet_handler = service->packet_handler;
373     channel->local_cid  = l2cap_next_local_cid();
374     channel->remote_cid = source_cid;
375     channel->remote_mtu = L2CAP_MINIMAL_MTU;
376 
377     // set initial state
378     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
379 
380     // temp. store req sig id
381     channel->sig_id = sig_id;
382 
383     // add to connections list
384     linked_list_add(&l2cap_channels, (linked_item_t *) channel);
385 
386     // emit incoming connection request
387     l2cap_emit_connection_request(channel);
388 }
389 
390 void l2cap_accept_connection_internal(uint16_t local_cid){
391     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
392     if (!channel) {
393         fprintf(stderr, "l2cap_accept_connection_internal called but local_cid 0x%x not found", local_cid);
394         return;
395     }
396 
397     // accept connection
398     l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->sig_id, channel->local_cid, channel->remote_cid, 0, 0);
399 
400     // set real sig and state and start config
401     channel->sig_id = l2cap_next_sig_id();
402     channel->state  = L2CAP_STATE_WAIT_CONFIG_REQ_RSP_OR_CONFIG_REQ;
403     l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->sig_id, channel->remote_cid, 0, 4, &config_options);
404 
405     // printf("new state %u\n", channel->state);
406 }
407 
408 void l2cap_decline_connection_internal(uint16_t local_cid, uint8_t reason){
409     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
410     if (!channel) {
411         fprintf(stderr, "l2cap_decline_connection_internal called but local_cid 0x%x not found", local_cid);
412         return;
413     }
414     l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->sig_id, 0, 0, reason, 0);
415 
416     // discard channel
417     linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
418     free (channel);
419 }
420 
421 void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
422     // accept the other's configuration options
423     uint16_t end_pos = 4 + READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
424     uint16_t pos     = 8;
425     while (pos < end_pos){
426         uint8_t type   = command[pos++];
427         uint8_t length = command[pos++];
428         // MTU { type(8): 1, len(8):2, MTU(16) }
429         if ((type & 0x7f) == 1 && length == 2){
430             channel->remote_mtu = READ_BT_16(command, pos);
431             // printf("l2cap cid %u, remote mtu %u\n", channel->local_cid, channel->remote_mtu);
432         }
433         pos += length;
434     }
435     uint8_t identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
436     // send back received options
437     // l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, identifier, channel->remote_cid, 0, 0, len-4, &command[8]);
438     // send back OK
439     l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, identifier, channel->remote_cid, 0, 0, 0, NULL);
440 }
441 
442 void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
443 
444     uint8_t code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
445     uint8_t identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
446     uint16_t result = 0;
447 
448     // printf("signaling handler code %u\n", code);
449 
450     switch (channel->state) {
451 
452         case L2CAP_STATE_WAIT_CONNECT_RSP:
453             switch (code){
454                 case CONNECTION_RESPONSE:
455                     result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
456                     switch (result) {
457                         case 0:
458                             // successful connection
459                             channel->remote_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
460                             channel->sig_id = l2cap_next_sig_id();
461                             l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->sig_id, channel->remote_cid, 0, 4, &config_options);
462                             channel->state = L2CAP_STATE_WAIT_CONFIG_REQ_RSP_OR_CONFIG_REQ;
463                             break;
464                         case 1:
465                             // connection pending. get some coffee
466                             break;
467                         default:
468                             // map l2cap connection response result to BTstack status enumeration
469                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
470                             break;
471                     }
472                     break;
473 
474                 case DISCONNECTION_REQUEST:
475                     l2cap_handle_disconnect_request(channel, identifier);
476                     break;
477 
478                 default:
479                     //@TODO: implement other signaling packets
480                     break;
481             }
482             break;
483 
484         case L2CAP_STATE_WAIT_CONFIG_REQ_RSP_OR_CONFIG_REQ:
485             switch (code) {
486                 case CONFIGURE_RESPONSE:
487                     channel->state = L2CAP_STATE_WAIT_CONFIG_REQ;
488                     break;
489                 case CONFIGURE_REQUEST:
490                     l2cap_signaling_handle_configure_request(channel, command);
491                     channel->state = L2CAP_STATE_WAIT_CONFIG_REQ_RSP;
492                     break;
493                 case DISCONNECTION_REQUEST:
494                     l2cap_handle_disconnect_request(channel, identifier);
495                     break;
496                 default:
497                     //@TODO: implement other signaling packets
498                     break;
499             }
500             break;
501 
502         case L2CAP_STATE_WAIT_CONFIG_REQ:
503             switch (code) {
504                 case CONFIGURE_REQUEST:
505                     l2cap_signaling_handle_configure_request(channel, command);
506                     channel->state = L2CAP_STATE_OPEN;
507                     l2cap_emit_channel_opened(channel, 0);  // success
508                     break;
509                 case DISCONNECTION_REQUEST:
510                     l2cap_handle_disconnect_request(channel, identifier);
511                     break;
512                 default:
513                     //@TODO: implement other signaling packets
514                     break;
515             }
516             break;
517 
518         case L2CAP_STATE_WAIT_CONFIG_REQ_RSP:
519             switch (code) {
520                 case CONFIGURE_RESPONSE:
521                     channel->state = L2CAP_STATE_OPEN;
522                     l2cap_emit_channel_opened(channel, 0);  // success
523                     break;
524                 case DISCONNECTION_REQUEST:
525                     l2cap_handle_disconnect_request(channel, identifier);
526                     break;
527                 default:
528                     //@TODO: implement other signaling packets
529                     break;
530             }
531             break;
532 
533         case L2CAP_STATE_WAIT_DISCONNECT:
534             switch (code) {
535                 case DISCONNECTION_RESPONSE:
536                     l2cap_finialize_channel_close(channel);
537                     break;
538                 case DISCONNECTION_REQUEST:
539                     l2cap_handle_disconnect_request(channel, identifier);
540                     break;
541                 default:
542                     //@TODO: implement other signaling packets
543                     break;
544             }
545             break;
546 
547         case L2CAP_STATE_CLOSED:
548             // @TODO handle incoming requests
549             break;
550 
551         case L2CAP_STATE_OPEN:
552             switch (code) {
553                 case DISCONNECTION_REQUEST:
554                     l2cap_handle_disconnect_request(channel, identifier);
555                     break;
556                 default:
557                     //@TODO: implement other signaling packets, e.g. re-configure
558                     break;
559             }
560             break;
561         default:
562             break;
563     }
564     // printf("new state %u\n", channel->state);
565 }
566 
567 
568 void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
569 
570     // get code, signalind identifier and command len
571     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
572     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
573     uint16_t len   = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
574 
575     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
576     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
577         return;
578     }
579 
580     // general commands without an assigned channel
581     switch(code) {
582 
583         case CONNECTION_REQUEST: {
584             uint16_t psm =        READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
585             uint16_t source_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
586             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
587             break;
588         }
589 
590         case ECHO_REQUEST: {
591             // send back packet
592             l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, len, &command[L2CAP_SIGNALING_COMMAND_DATA_OFFSET]);
593             break;
594         }
595 
596         case INFORMATION_REQUEST: {
597             // we neither support connectionless L2CAP data nor support any flow control modes yet
598             uint16_t infoType = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
599             if (infoType == 2) {
600                 uint32_t features = 0;
601                 // extended features request supported, however no features present
602                 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, 4, &features);
603             } else {
604                 // all other types are not supported
605                 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
606             }
607             break;;
608         }
609 
610         default:
611             break;
612     }
613 
614 
615     // Get potential destination CID
616     uint16_t dest_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
617 
618     // Find channel for this sig_id and connection handle
619     linked_item_t *it;
620     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
621         l2cap_channel_t * channel = (l2cap_channel_t *) it;
622         if (channel->handle == handle) {
623             if (code & 1) {
624                 // match odd commands by previous signaling identifier
625                 if (channel->sig_id == sig_id) {
626                     l2cap_signaling_handler_channel(channel, command);
627                 }
628             } else {
629                 // match even commands by local channel id
630                 if (channel->local_cid == dest_cid) {
631                     l2cap_signaling_handler_channel(channel, command);
632                 }
633             }
634         }
635     }
636 }
637 
638 void l2cap_acl_handler( uint8_t *packet, uint16_t size ){
639 
640     // Capturing?
641     if (capture_connection) {
642         (*packet_handler)(capture_connection, HCI_ACL_DATA_PACKET, 0, packet, size);
643         return;
644     }
645 
646     // Get Channel ID
647     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
648 
649     // Signaling Packet?
650     if (channel_id == 1) {
651 
652         // Get Connection
653         hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
654 
655         uint16_t command_offset = 8;
656         while (command_offset < size) {
657 
658             // handle signaling commands
659             l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
660 
661             // increment command_offset
662             command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + READ_BT_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
663         }
664         return;
665     }
666 
667     // Find channel for this channel_id and connection handle
668     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(channel_id);
669     if (channel) {
670         l2cap_dispatch(channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
671     }
672 }
673 
674 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
675     switch (packet_type) {
676         case HCI_EVENT_PACKET:
677             l2cap_event_handler(packet, size);
678             break;
679         case HCI_ACL_DATA_PACKET:
680             l2cap_acl_handler(packet, size);
681             break;
682         default:
683             break;
684     }
685 }
686 
687 // finalize closed channel
688 void l2cap_finialize_channel_close(l2cap_channel_t *channel){
689     channel->state = L2CAP_STATE_CLOSED;
690     l2cap_emit_channel_closed(channel);
691 
692     // discard channel
693     linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
694     free (channel);
695 }
696 
697 l2cap_service_t * l2cap_get_service(uint16_t psm){
698     linked_item_t *it;
699 
700     // close open channels
701     for (it = (linked_item_t *) l2cap_services; it ; it = it->next){
702         l2cap_service_t * service = ((l2cap_service_t *) it);
703         if ( service->psm == psm){
704             return service;
705         };
706     }
707     return NULL;
708 }
709 
710 void l2cap_register_service_internal(connection_t *connection, btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t mtu){
711     // check for alread registered psm // TODO: emit error event
712     l2cap_service_t *service = l2cap_get_service(psm);
713     if (service) return;
714 
715     // alloc structure     // TODO: emit error event
716     service = malloc(sizeof(l2cap_service_t));
717     if (!service) return;
718 
719     // fill in
720     service->psm = psm;
721     service->mtu = mtu;
722     service->connection = connection;
723     service->packet_handler = packet_handler;
724 
725     // add to services list
726     linked_list_add(&l2cap_services, (linked_item_t *) service);
727 }
728 
729 void l2cap_unregister_service_internal(connection_t *connection, uint16_t psm){
730     l2cap_service_t *service = l2cap_get_service(psm);
731     if (!service) return;
732     linked_list_remove(&l2cap_services, (linked_item_t *) service);
733     free(service);
734 }
735 
736 //
737 void l2cap_close_connection(connection_t *connection){
738     linked_item_t *it;
739 
740     // close open channels
741     l2cap_channel_t * channel;
742     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
743         channel = (l2cap_channel_t *) it;
744         if (channel->connection == connection) {
745             channel->sig_id = l2cap_next_sig_id();
746             l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->sig_id, channel->remote_cid, channel->local_cid);
747             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
748         }
749     }
750 
751     // unregister services
752     it = (linked_item_t *) &l2cap_services;
753     while (it->next){
754         l2cap_service_t * service = (l2cap_service_t *) it->next;
755         if (service->connection == connection){
756             it->next = it->next->next;
757             free(service);
758         } else {
759             it = it->next;
760         }
761     }
762 }
763 
764 
765 void l2cap_set_capture_connection(connection_t * connection){
766     capture_connection = connection;
767 }
768 
769