2 * Copyright (C) 2014 Samsung System LSI
3 * Copyright (C) 2013 The Android Open Source Project
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 #define LOG_TAG "bt_btif_sock"
20 #include "btif_sock_l2cap.h"
25 #include <sys/ioctl.h>
26 #include <sys/socket.h>
27 #include <sys/types.h>
30 #include <hardware/bt_sock.h>
32 #include "osi/include/allocator.h"
33 #include "osi/include/log.h"
35 #include "bt_target.h"
37 #include "bta_jv_api.h"
38 #include "bta_jv_co.h"
39 #include "btif_common.h"
40 #include "btif_sock_sdp.h"
41 #include "btif_sock_thread.h"
42 #include "btif_sock_util.h"
44 #include "btif_util.h"
48 #include "bt_common.h"
55 #define asrt(s) if (!(s)) APPL_TRACE_ERROR("## %s assert %s failed at line:%d ##",__FUNCTION__, \
59 struct packet *next, *prev;
64 typedef struct l2cap_socket {
66 struct l2cap_socket *prev; //link to prev list item
67 struct l2cap_socket *next; //link to next list item
68 bt_bdaddr_t addr; //other side's address
69 char name[256]; //user-friendly name of the service
70 uint32_t id; //just a tag to find this struct
71 int app_uid; // The UID of the app who requested this socket
72 int handle; //handle from lower layers
73 unsigned security; //security flags
74 int channel; //channel (fixed_chan) or PSM (!fixed_chan)
75 int our_fd; //fd from our side
76 int app_fd; //fd from app's side
78 unsigned bytes_buffered;
79 struct packet *first_packet; //fist packet to be delivered to app
80 struct packet *last_packet; //last packet to be delivered to app
82 fixed_queue_t *incoming_que; //data that came in but has not yet been read
83 unsigned fixed_chan :1; //fixed channel (or psm?)
84 unsigned server :1; //is a server? (or connecting?)
85 unsigned connected :1; //is connected?
86 unsigned outgoing_congest :1; //should we hold?
87 unsigned server_psm_sent :1; //The server shall only send PSM once.
88 BOOLEAN is_le_coc; //is le connection oriented channel?
91 static bt_status_t btSock_start_l2cap_server_l(l2cap_socket *sock);
93 static pthread_mutex_t state_lock;
95 l2cap_socket *socks = NULL;
96 static uid_set_t* uid_set = NULL;
99 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data);
101 /* TODO: Consider to remove this buffer, as we have a buffer in l2cap as well, and we risk
102 * a buffer overflow with this implementation if the socket data is not read from
103 * JAVA for a while. In such a case we should use flow control to tell the sender to
105 * BUT remember we need to avoid blocking the BTA task execution - hence we cannot
106 * directly write to the socket.
107 * we should be able to change to store the data pointer here, and just wait
108 * confirming the l2cap_ind until we have more space in the buffer. */
110 /* returns FALSE if none - caller must free "data" memory when done with it */
111 static char packet_get_head_l(l2cap_socket *sock, uint8_t **data, uint32_t *len)
113 struct packet *p = sock->first_packet;
119 *data = sock->first_packet->data;
121 *len = sock->first_packet->len;
122 sock->first_packet = p->next;
123 if (sock->first_packet)
124 sock->first_packet->prev = NULL;
126 sock->last_packet = NULL;
129 sock->bytes_buffered -= *len;
136 static struct packet *packet_alloc(const uint8_t *data, uint32_t len)
138 struct packet *p = osi_calloc(sizeof(*p));
139 uint8_t *buf = osi_malloc(len);
143 memcpy(p->data, data, len);
147 /* makes a copy of the data, returns TRUE on success */
148 static char packet_put_head_l(l2cap_socket *sock, const void *data, uint32_t len)
150 struct packet *p = packet_alloc((const uint8_t*)data, len);
153 * We do not check size limits here since this is used to undo "getting" a
154 * packet that the user read incompletely. That is to say the packet was
155 * already in the queue. We do check thos elimits in packet_put_tail_l() since
156 * that function is used to put new data into the queue.
163 p->next = sock->first_packet;
164 sock->first_packet = p;
168 sock->last_packet = p;
170 sock->bytes_buffered += len;
175 /* makes a copy of the data, returns TRUE on success */
176 static char packet_put_tail_l(l2cap_socket *sock, const void *data, uint32_t len)
178 struct packet *p = packet_alloc((const uint8_t*)data, len);
180 if (sock->bytes_buffered >= L2CAP_MAX_RX_BUFFER) {
181 LOG_ERROR(LOG_TAG, "packet_put_tail_l: buffer overflow");
186 LOG_ERROR(LOG_TAG, "packet_put_tail_l: unable to allocate packet...");
191 p->prev = sock->last_packet;
192 sock->last_packet = p;
196 sock->first_packet = p;
198 sock->bytes_buffered += len;
203 static inline void bd_copy(UINT8* dest, UINT8* src, BOOLEAN swap)
207 for (i =0; i < 6 ;i++)
210 else memcpy(dest, src, 6);
213 static char is_inited(void)
217 pthread_mutex_lock(&state_lock);
219 pthread_mutex_unlock(&state_lock);
224 /* only call with mutex taken */
225 static l2cap_socket *btsock_l2cap_find_by_id_l(uint32_t id)
227 l2cap_socket *sock = socks;
229 while (sock && sock->id != id)
235 static void btsock_l2cap_free_l(l2cap_socket *sock)
238 l2cap_socket *t = socks;
240 while(t && t != sock)
243 if (!t) /* prever double-frees */
247 sock->next->prev = sock->prev;
250 sock->prev->next = sock->next;
254 shutdown(sock->our_fd, SHUT_RDWR);
256 if (sock->app_fd != -1) {
259 APPL_TRACE_ERROR("SOCK_LIST: free(id = %d) - NO app_fd!", sock->id);
262 while (packet_get_head_l(sock, &buf, NULL))
265 //lower-level close() should be idempotent... so let's call it and see...
268 // Only call if we are non server connections
269 if (sock->handle >= 0 && (sock->server == FALSE)) {
270 BTA_JvL2capClose(sock->handle);
272 if ((sock->channel >= 0) && (sock->server == TRUE)) {
273 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP);
278 // Only call if we are non server connections
279 if (sock->handle && (sock->server == FALSE)) {
280 if (sock->fixed_chan)
281 BTA_JvL2capCloseLE(sock->handle);
283 BTA_JvL2capClose(sock->handle);
285 if ((sock->channel >= 0) && (sock->server == TRUE)) {
286 if (sock->fixed_chan)
287 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP_LE);
289 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP);
293 APPL_TRACE_DEBUG("%s: free(id = %d)", __func__, sock->id);
297 static l2cap_socket *btsock_l2cap_alloc_l(const char *name, const bt_bdaddr_t *addr,
298 char is_server, int flags)
300 unsigned security = 0;
302 l2cap_socket *sock = osi_calloc(sizeof(*sock));
304 if (flags & BTSOCK_FLAG_ENCRYPT)
305 security |= is_server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
306 if (flags & BTSOCK_FLAG_AUTH)
307 security |= is_server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
308 if (flags & BTSOCK_FLAG_AUTH_MITM)
309 security |= is_server ? BTM_SEC_IN_MITM : BTM_SEC_OUT_MITM;
310 if (flags & BTSOCK_FLAG_AUTH_16_DIGIT)
311 security |= BTM_SEC_IN_MIN_16_DIGIT_PIN;
313 if (socketpair(AF_LOCAL, SOCK_SEQPACKET, 0, fds)) {
314 APPL_TRACE_ERROR("socketpair failed, errno:%d", errno);
318 sock->our_fd = fds[0];
319 sock->app_fd = fds[1];
320 sock->security = security;
321 sock->server = is_server;
322 sock->connected = FALSE;
324 sock->server_psm_sent = FALSE;
328 strncpy(sock->name, name, sizeof(sock->name) - 1);
332 sock->first_packet = NULL;
333 sock->last_packet = NULL;
339 sock->id = (socks ? socks->id : 0) + 1;
341 /* paranoia cap on: verify no ID duplicates due to overflow and fix as needed */
345 while (t && t->id != sock->id) {
348 if (!t && sock->id) /* non-zeor handle is unique -> we're done */
350 /* if we're here, we found a duplicate */
351 if (!++sock->id) /* no zero IDs allowed */
354 APPL_TRACE_DEBUG("SOCK_LIST: alloc(id = %d)", sock->id);
362 bt_status_t btsock_l2cap_init(int handle, uid_set_t* set)
364 APPL_TRACE_DEBUG("%s handle = %d", __func__);
365 pthread_mutex_init(&state_lock, NULL);
366 pthread_mutex_lock(&state_lock);
370 pthread_mutex_unlock(&state_lock);
372 return BT_STATUS_SUCCESS;
375 bt_status_t btsock_l2cap_cleanup()
377 pthread_mutex_lock(&state_lock);
380 btsock_l2cap_free_l(socks);
381 pthread_mutex_unlock(&state_lock);
382 pthread_mutex_destroy(&state_lock);
384 return BT_STATUS_SUCCESS;
387 static inline BOOLEAN send_app_psm_or_chan_l(l2cap_socket *sock)
389 return sock_send_all(sock->our_fd, (const uint8_t*)&sock->channel, sizeof(sock->channel))
390 == sizeof(sock->channel);
393 static BOOLEAN send_app_connect_signal(int fd, const bt_bdaddr_t* addr,
394 int channel, int status, int send_fd, int tx_mtu)
396 sock_connect_signal_t cs;
397 cs.size = sizeof(cs);
399 cs.channel = channel;
401 cs.max_rx_packet_size = L2CAP_MAX_SDU_LENGTH;
402 cs.max_tx_packet_size = tx_mtu;
404 if (sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == sizeof(cs))
406 else APPL_TRACE_ERROR("sock_send_fd failed, fd:%d, send_fd:%d", fd, send_fd);
407 } else if (sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs)) {
413 static void on_srv_l2cap_listen_started(tBTA_JV_L2CAP_START *p_start, uint32_t id)
417 pthread_mutex_lock(&state_lock);
418 sock = btsock_l2cap_find_by_id_l(id);
420 if (p_start->status != BTA_JV_SUCCESS) {
421 APPL_TRACE_ERROR("Error starting l2cap_listen - status: 0x%04x", p_start->status);
422 btsock_l2cap_free_l(sock);
425 sock->handle = p_start->handle;
426 APPL_TRACE_DEBUG("on_srv_l2cap_listen_started() sock->handle =%d id:%d",
427 sock->handle, sock->id);
428 if(sock->server_psm_sent == FALSE) {
429 if (!send_app_psm_or_chan_l(sock)) {
431 APPL_TRACE_DEBUG("send_app_psm() failed, close rs->id:%d", sock->id);
432 btsock_l2cap_free_l(sock);
434 sock->server_psm_sent = TRUE;
439 pthread_mutex_unlock(&state_lock);
442 static void on_cl_l2cap_init(tBTA_JV_L2CAP_CL_INIT *p_init, uint32_t id)
446 pthread_mutex_lock(&state_lock);
447 sock = btsock_l2cap_find_by_id_l(id);
449 if (p_init->status != BTA_JV_SUCCESS) {
450 btsock_l2cap_free_l(sock);
452 sock->handle = p_init->handle;
455 pthread_mutex_unlock(&state_lock);
459 * Here we allocate a new sock instance to mimic the BluetoothSocket. The socket will be a clone
460 * of the sock representing the BluetoothServerSocket.
462 static void on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN *p_open, l2cap_socket *sock)
464 l2cap_socket *accept_rs;
465 uint32_t new_listen_id;
467 // Mutex locked by caller
468 accept_rs = btsock_l2cap_alloc_l(sock->name, (const bt_bdaddr_t*)p_open->rem_bda, FALSE, 0);
469 accept_rs->connected = TRUE;
470 accept_rs->security = sock->security;
471 accept_rs->fixed_chan = sock->fixed_chan;
472 accept_rs->channel = sock->channel;
473 accept_rs->handle = sock->handle;
474 accept_rs->app_uid = sock->app_uid;
475 sock->handle = -1; /* We should no longer associate this handle with the server socket */
476 accept_rs->is_le_coc = sock->is_le_coc;
478 /* Swap IDs to hand over the GAP connection to the accepted socket, and start a new server on
479 the newly create socket ID. */
480 new_listen_id = accept_rs->id;
481 accept_rs->id = sock->id;
482 sock->id = new_listen_id;
485 //start monitor the socket
486 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id);
487 btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
489 APPL_TRACE_DEBUG("sending connect signal & app fd: %d to app server to accept() the"
490 " connection", accept_rs->app_fd);
491 APPL_TRACE_DEBUG("server fd:%d, scn:%d", sock->our_fd, sock->channel);
492 send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0,
493 accept_rs->app_fd, p_open->tx_mtu);
494 accept_rs->app_fd = -1; // The fd is closed after sent to app in send_app_connect_signal()
495 // But for some reason we still leak a FD - either the server socket
496 // one or the accept socket one.
497 if(btSock_start_l2cap_server_l(sock) != BT_STATUS_SUCCESS) {
498 btsock_l2cap_free_l(sock);
503 static void on_srv_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN *p_open, l2cap_socket *sock)
505 l2cap_socket *accept_rs;
506 uint32_t new_listen_id;
508 // mutex locked by caller
509 accept_rs = btsock_l2cap_alloc_l(sock->name, (const bt_bdaddr_t*)p_open->rem_bda, FALSE, 0);
513 new_listen_id = accept_rs->id;
514 accept_rs->id = sock->id;
515 sock->id = new_listen_id;
517 accept_rs->handle = p_open->handle;
518 accept_rs->connected = TRUE;
519 accept_rs->security = sock->security;
520 accept_rs->fixed_chan = sock->fixed_chan;
521 accept_rs->channel = sock->channel;
522 accept_rs->app_uid = sock->app_uid;
524 //if we do not set a callback, this socket will be dropped */
525 *(p_open->p_p_cback) = (void*)btsock_l2cap_cbk;
526 *(p_open->p_user_data) = UINT_TO_PTR(accept_rs->id);
528 //start monitor the socket
529 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id);
530 btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
532 APPL_TRACE_DEBUG("sending connect signal & app fd:%dto app server to accept() the"
533 " connection", accept_rs->app_fd);
534 APPL_TRACE_DEBUG("server fd:%d, scn:%d", sock->our_fd, sock->channel);
535 send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0,
536 accept_rs->app_fd, p_open->tx_mtu);
537 accept_rs->app_fd = -1; //the fd is closed after sent to app
541 static void on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN *p_open, l2cap_socket *sock)
543 bd_copy(sock->addr.address, p_open->rem_bda, 0);
545 if (!send_app_psm_or_chan_l(sock)) {
546 APPL_TRACE_ERROR("send_app_psm_or_chan_l failed");
550 if (send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1, p_open->tx_mtu)) {
551 //start monitoring the socketpair to get call back when app writing data
552 APPL_TRACE_DEBUG("on_l2cap_connect_ind, connect signal sent, slot id:%d, psm:%d,"
553 " server:%d", sock->id, sock->channel, sock->server);
554 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
555 sock->connected = TRUE;
557 else APPL_TRACE_ERROR("send_app_connect_signal failed");
560 static void on_cl_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN *p_open, l2cap_socket *sock)
562 bd_copy(sock->addr.address, p_open->rem_bda, 0);
564 if (!send_app_psm_or_chan_l(sock)) {
565 APPL_TRACE_ERROR("send_app_psm_or_chan_l failed");
569 if (send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1, p_open->tx_mtu)) {
570 //start monitoring the socketpair to get call back when app writing data
571 APPL_TRACE_DEBUG("on_l2cap_connect_ind, connect signal sent, slot id:%d, Chan:%d,"
572 " server:%d", sock->id, sock->channel, sock->server);
573 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
574 sock->connected = TRUE;
576 else APPL_TRACE_ERROR("send_app_connect_signal failed");
579 static void on_l2cap_connect(tBTA_JV *p_data, uint32_t id)
582 tBTA_JV_L2CAP_OPEN *psm_open = &p_data->l2c_open;
583 tBTA_JV_L2CAP_LE_OPEN *le_open = &p_data->l2c_le_open;
585 pthread_mutex_lock(&state_lock);
586 sock = btsock_l2cap_find_by_id_l(id);
588 APPL_TRACE_ERROR("on_l2cap_connect on unknown socket");
590 if (sock->fixed_chan && le_open->status == BTA_JV_SUCCESS) {
592 on_cl_l2cap_le_connect_l(le_open, sock);
594 on_srv_l2cap_le_connect_l(le_open, sock);
595 } else if (!sock->fixed_chan && psm_open->status == BTA_JV_SUCCESS) {
597 on_cl_l2cap_psm_connect_l(psm_open, sock);
599 on_srv_l2cap_psm_connect_l(psm_open, sock);
602 btsock_l2cap_free_l(sock);
604 pthread_mutex_unlock(&state_lock);
607 static void on_l2cap_close(tBTA_JV_L2CAP_CLOSE * p_close, uint32_t id)
611 pthread_mutex_lock(&state_lock);
612 sock = btsock_l2cap_find_by_id_l(id);
614 APPL_TRACE_DEBUG("on_l2cap_close, slot id:%d, fd:%d, %s:%d, server:%d",
615 sock->id, sock->our_fd, sock->fixed_chan ? "fixed_chan" : "PSM",
616 sock->channel, sock->server);
617 // TODO: This does not seem to be called...
618 // I'm not sure if this will be called for non-server sockets?
619 if(!sock->fixed_chan && (sock->server == TRUE)) {
620 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP);
622 btsock_l2cap_free_l(sock);
624 pthread_mutex_unlock(&state_lock);
627 static void on_l2cap_outgoing_congest(tBTA_JV_L2CAP_CONG *p, uint32_t id)
631 pthread_mutex_lock(&state_lock);
632 sock = btsock_l2cap_find_by_id_l(id);
634 sock->outgoing_congest = p->cong ? 1 : 0;
635 //mointer the fd for any outgoing data
636 if (!sock->outgoing_congest) {
637 APPL_TRACE_DEBUG("on_l2cap_outgoing_congest: adding fd to btsock_thread...");
638 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
642 pthread_mutex_unlock(&state_lock);
645 static void on_l2cap_write_done(void* req_id, uint16_t len, uint32_t id)
649 if (req_id != NULL) {
650 osi_free(req_id); //free the buffer
655 pthread_mutex_lock(&state_lock);
656 sock = btsock_l2cap_find_by_id_l(id);
658 app_uid = sock->app_uid;
659 if (!sock->outgoing_congest) {
660 //monitor the fd for any outgoing data
661 APPL_TRACE_DEBUG("on_l2cap_write_done: adding fd to btsock_thread...");
662 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
665 pthread_mutex_unlock(&state_lock);
667 uid_set_add_tx(uid_set, app_uid, len);
670 static void on_l2cap_write_fixed_done(void* req_id, uint16_t len, uint32_t id)
674 if (req_id != NULL) {
675 osi_free(req_id); //free the buffer
679 pthread_mutex_lock(&state_lock);
680 sock = btsock_l2cap_find_by_id_l(id);
682 app_uid = sock->app_uid;
683 if (!sock->outgoing_congest) {
684 //monitor the fd for any outgoing data
685 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
688 pthread_mutex_unlock(&state_lock);
690 uid_set_add_tx(uid_set, app_uid, len);
693 static void on_l2cap_data_ind(tBTA_JV *evt, uint32_t id)
698 UINT32 bytes_read = 0;
700 pthread_mutex_lock(&state_lock);
701 sock = btsock_l2cap_find_by_id_l(id);
703 app_uid = sock->app_uid;
705 if (sock->fixed_chan) { /* we do these differently */
707 tBTA_JV_LE_DATA_IND *p_le_data_ind = &evt->le_data_ind;
708 BT_HDR *p_buf = p_le_data_ind->p_buf;
709 uint8_t *data = (uint8_t*)(p_buf + 1) + p_buf->offset;
711 if (packet_put_tail_l(sock, data, p_buf->len)) {
712 bytes_read = p_buf->len;
713 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
714 } else {//connection must be dropped
715 APPL_TRACE_DEBUG("on_l2cap_data_ind() unable to push data to socket - closing"
717 BTA_JvL2capCloseLE(sock->handle);
718 btsock_l2cap_free_l(sock);
723 UINT8 buffer[L2CAP_MAX_SDU_LENGTH];
726 if (BTA_JvL2capReady(sock->handle, &count) == BTA_JV_SUCCESS) {
727 if (BTA_JvL2capRead(sock->handle, sock->id, buffer, count) == BTA_JV_SUCCESS) {
728 if (packet_put_tail_l(sock, buffer, count)) {
730 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR,
732 } else {//connection must be dropped
733 APPL_TRACE_DEBUG("on_l2cap_data_ind() unable to push data to socket"
734 " - closing channel");
735 BTA_JvL2capClose(sock->handle);
736 btsock_l2cap_free_l(sock);
742 pthread_mutex_unlock(&state_lock);
744 uid_set_add_rx(uid_set, app_uid, bytes_read);
747 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data)
749 uint32_t sock_id = PTR_TO_UINT(user_data);
752 case BTA_JV_L2CAP_START_EVT:
753 on_srv_l2cap_listen_started(&p_data->l2c_start, sock_id);
756 case BTA_JV_L2CAP_CL_INIT_EVT:
757 on_cl_l2cap_init(&p_data->l2c_cl_init, sock_id);
760 case BTA_JV_L2CAP_OPEN_EVT:
761 on_l2cap_connect(p_data, sock_id);
762 BTA_JvSetPmProfile(p_data->l2c_open.handle, BTA_JV_PM_ID_1,BTA_JV_CONN_OPEN);
765 case BTA_JV_L2CAP_CLOSE_EVT:
766 APPL_TRACE_DEBUG("BTA_JV_L2CAP_CLOSE_EVT: id: %u", sock_id);
767 on_l2cap_close(&p_data->l2c_close, sock_id);
770 case BTA_JV_L2CAP_DATA_IND_EVT:
771 on_l2cap_data_ind(p_data, sock_id);
772 APPL_TRACE_DEBUG("BTA_JV_L2CAP_DATA_IND_EVT");
775 case BTA_JV_L2CAP_READ_EVT:
776 APPL_TRACE_DEBUG("BTA_JV_L2CAP_READ_EVT not used");
779 case BTA_JV_L2CAP_WRITE_EVT:
780 APPL_TRACE_DEBUG("BTA_JV_L2CAP_WRITE_EVT: id: %u", sock_id);
781 on_l2cap_write_done(UINT_TO_PTR(p_data->l2c_write.req_id), p_data->l2c_write.len, sock_id);
784 case BTA_JV_L2CAP_WRITE_FIXED_EVT:
785 APPL_TRACE_DEBUG("BTA_JV_L2CAP_WRITE_FIXED_EVT: id: %u", sock_id);
786 on_l2cap_write_fixed_done(UINT_TO_PTR(p_data->l2c_write_fixed.req_id), p_data->l2c_write.len, sock_id);
789 case BTA_JV_L2CAP_CONG_EVT:
790 on_l2cap_outgoing_congest(&p_data->l2c_cong, sock_id);
794 APPL_TRACE_ERROR("unhandled event %d, slot id: %u", event, sock_id);
799 /* L2CAP default options for OBEX socket connections */
800 const tL2CAP_FCR_OPTS obex_l2c_fcr_opts_def =
802 L2CAP_FCR_ERTM_MODE, /* Mandatory for OBEX over l2cap */
803 OBX_FCR_OPT_TX_WINDOW_SIZE_BR_EDR,/* Tx window size */
804 OBX_FCR_OPT_MAX_TX_B4_DISCNT, /* Maximum transmissions before disconnecting */
805 OBX_FCR_OPT_RETX_TOUT, /* Retransmission timeout (2 secs) */
806 OBX_FCR_OPT_MONITOR_TOUT, /* Monitor timeout (12 secs) */
807 OBX_FCR_OPT_MAX_PDU_SIZE /* MPS segment size */
809 const tL2CAP_ERTM_INFO obex_l2c_etm_opt =
811 L2CAP_FCR_ERTM_MODE, /* Mandatory for OBEX over l2cap */
812 L2CAP_FCR_CHAN_OPT_ERTM, /* Mandatory for OBEX over l2cap */
813 OBX_USER_RX_BUF_SIZE,
814 OBX_USER_TX_BUF_SIZE,
820 * When using a dynamic PSM, a PSM allocation is requested from btsock_l2cap_listen_or_connect().
821 * The PSM allocation event is refeived in the JV-callback - currently located in RFC-code -
822 * and this function is called with the newly allocated PSM.
824 void on_l2cap_psm_assigned(int id, int psm) {
826 /* Setup ETM settings:
827 * mtu will be set below */
828 pthread_mutex_lock(&state_lock);
829 sock = btsock_l2cap_find_by_id_l(id);
832 if(btSock_start_l2cap_server_l(sock) != BT_STATUS_SUCCESS) {
833 btsock_l2cap_free_l(sock);
836 pthread_mutex_unlock(&state_lock);
840 static bt_status_t btSock_start_l2cap_server_l(l2cap_socket *sock) {
842 bt_status_t stat = BT_STATUS_SUCCESS;
843 /* Setup ETM settings:
844 * mtu will be set below */
845 memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
847 cfg.fcr_present = TRUE;
848 cfg.fcr = obex_l2c_fcr_opts_def;
850 if (sock->fixed_chan) {
852 if (BTA_JvL2capStartServerLE(sock->security, 0, NULL, sock->channel,
853 L2CAP_DEFAULT_MTU, NULL, btsock_l2cap_cbk, UINT_TO_PTR(sock->id))
855 stat = BT_STATUS_FAIL;
858 /* If we have a channel specified in the request, just start the server,
859 * else we request a PSM and start the server after we receive a PSM. */
860 if (sock->channel < 0) {
861 if (sock->is_le_coc) {
862 if (BTA_JvGetChannelId(BTA_JV_CONN_TYPE_L2CAP_LE, UINT_TO_PTR(sock->id), 0)
864 stat = BT_STATUS_FAIL;
868 if (BTA_JvGetChannelId(BTA_JV_CONN_TYPE_L2CAP, UINT_TO_PTR(sock->id), 0)
870 stat = BT_STATUS_FAIL;
873 if (sock->is_le_coc) {
874 if (BTA_JvL2capStartServer(BTA_JV_CONN_TYPE_L2CAP_LE, sock->security, 0, NULL,
875 sock->channel, L2CAP_MAX_SDU_LENGTH, &cfg, btsock_l2cap_cbk, UINT_TO_PTR(sock->id))
877 stat = BT_STATUS_FAIL;
881 if (BTA_JvL2capStartServer(BTA_JV_CONN_TYPE_L2CAP, sock->security, 0, &obex_l2c_etm_opt,
882 sock->channel, L2CAP_MAX_SDU_LENGTH, &cfg, btsock_l2cap_cbk, UINT_TO_PTR(sock->id))
884 stat = BT_STATUS_FAIL;
891 static bt_status_t btsock_l2cap_listen_or_connect(const char *name, const bt_bdaddr_t *addr,
892 int channel, int* sock_fd, int flags, char listen, int app_uid)
898 BOOLEAN is_le_coc = FALSE;
901 return BT_STATUS_PARM_INVALID;
904 // We need to auto assign a PSM
907 fixed_chan = (channel & L2CAP_MASK_FIXED_CHANNEL) != 0;
908 is_le_coc = (channel & L2CAP_MASK_LE_COC_CHANNEL) != 0;
909 channel &=~ (L2CAP_MASK_FIXED_CHANNEL | L2CAP_MASK_LE_COC_CHANNEL);
913 return BT_STATUS_NOT_READY;
915 // TODO: This is kind of bad to lock here, but it is needed for the current design.
916 pthread_mutex_lock(&state_lock);
918 sock = btsock_l2cap_alloc_l(name, addr, listen, flags);
920 pthread_mutex_unlock(&state_lock);
921 return BT_STATUS_NOMEM;
924 sock->fixed_chan = fixed_chan;
925 sock->channel = channel;
926 sock->app_uid = app_uid;
927 sock->is_le_coc = is_le_coc;
929 stat = BT_STATUS_SUCCESS;
931 /* Setup ETM settings:
932 * mtu will be set below */
933 memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
935 cfg.fcr_present = TRUE;
936 cfg.fcr = obex_l2c_fcr_opts_def;
938 /* "role" is never initialized in rfcomm code */
940 stat = btSock_start_l2cap_server_l(sock);
943 if (BTA_JvL2capConnectLE(sock->security, 0, NULL, channel,
944 L2CAP_DEFAULT_MTU, NULL, sock->addr.address, btsock_l2cap_cbk,
945 UINT_TO_PTR(sock->id)) != BTA_JV_SUCCESS)
946 stat = BT_STATUS_FAIL;
949 if (sock->is_le_coc) {
950 if (BTA_JvL2capConnect(BTA_JV_CONN_TYPE_L2CAP_LE, sock->security, 0, NULL,
951 channel, L2CAP_MAX_SDU_LENGTH, &cfg, sock->addr.address,
952 btsock_l2cap_cbk, UINT_TO_PTR(sock->id)) != BTA_JV_SUCCESS)
953 stat = BT_STATUS_FAIL;
957 if (BTA_JvL2capConnect(BTA_JV_CONN_TYPE_L2CAP, sock->security, 0, &obex_l2c_etm_opt,
958 channel, L2CAP_MAX_SDU_LENGTH, &cfg, sock->addr.address,
959 btsock_l2cap_cbk, UINT_TO_PTR(sock->id)) != BTA_JV_SUCCESS)
960 stat = BT_STATUS_FAIL;
965 if (stat == BT_STATUS_SUCCESS) {
966 *sock_fd = sock->app_fd;
967 /* We pass the FD to JAVA, but since it runs in another process, we need to also close
968 * it in native, either straight away, as done when accepting an incoming connection,
969 * or when doing cleanup after this socket */
970 sock->app_fd = -1; /*This leaks the file descriptor. The FD should be closed in
971 JAVA but it apparently do not work */
972 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION,
975 btsock_l2cap_free_l(sock);
977 pthread_mutex_unlock(&state_lock);
982 bt_status_t btsock_l2cap_listen(const char* name, int channel, int* sock_fd, int flags, int app_uid)
984 return btsock_l2cap_listen_or_connect(name, NULL, channel, sock_fd, flags, 1, app_uid);
987 bt_status_t btsock_l2cap_connect(const bt_bdaddr_t *bd_addr, int channel, int* sock_fd, int flags, int app_uid)
989 return btsock_l2cap_listen_or_connect(NULL, bd_addr, channel, sock_fd, flags, 0, app_uid);
992 /* return TRUE if we have more to send and should wait for user readiness, FALSE else
993 * (for example: unrecoverable error or no data)
995 static BOOLEAN flush_incoming_que_on_wr_signal_l(l2cap_socket *sock)
1000 while (packet_get_head_l(sock, &buf, &len)) {
1002 OSI_NO_INTR(sent = send(sock->our_fd, buf, len, MSG_DONTWAIT));
1003 int saved_errno = errno;
1005 if (sent == (signed)len)
1007 else if (sent >= 0) {
1008 packet_put_head_l(sock, buf + sent, len - sent);
1010 if (!sent) /* special case if other end not keeping up */
1014 packet_put_head_l(sock, buf, len);
1016 return saved_errno == EWOULDBLOCK || saved_errno == EAGAIN;
1023 void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id)
1026 char drop_it = FALSE;
1028 /* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to hold the lock. */
1029 pthread_mutex_lock(&state_lock);
1030 sock = btsock_l2cap_find_by_id_l(user_id);
1032 if ((flags & SOCK_THREAD_FD_RD) && !sock->server) {
1034 if (sock->connected) {
1037 if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(sock->our_fd, FIONREAD, &size)
1039 uint8_t *buffer = osi_malloc(L2CAP_MAX_SDU_LENGTH);
1040 /* Apparently we hijack the req_id (UINT32) to pass the pointer to the buffer to
1041 * the write complete callback, which call a free... wonder if this works on a
1042 * 64 bit platform? */
1043 /* The socket is created with SOCK_SEQPACKET, hence we read one message at
1044 * the time. The maximum size of a message is allocated to ensure data is
1045 * not lost. This is okay to do as Android uses virtual memory, hence even
1046 * if we only use a fraction of the memory it should not block for others
1047 * to use the memory. As the definition of ioctl(FIONREAD) do not clearly
1048 * define what value will be returned if multiple messages are written to
1049 * the socket before any message is read from the socket, we could
1050 * potentially risk to allocate way more memory than needed. One of the use
1051 * cases for this socket is obex where multiple 64kbyte messages are
1052 * typically written to the socket in a tight loop, hence we risk the ioctl
1053 * will return the total amount of data in the buffer, which could be
1054 * multiple 64kbyte chunks.
1055 * UPDATE: As the stack cannot handle 64kbyte buffers, the size is reduced
1056 * to around 8kbyte - and using malloc for buffer allocation here seems to
1058 * UPDATE: Since we are responsible for freeing the buffer in the
1059 * write_complete_ind, it is OK to use malloc. */
1061 OSI_NO_INTR(count = recv(fd, buffer, L2CAP_MAX_SDU_LENGTH,
1062 MSG_NOSIGNAL | MSG_DONTWAIT));
1063 APPL_TRACE_DEBUG("btsock_l2cap_signaled - %d bytes received from socket",
1066 // TODO(armansito): |buffer|, which is created above via
1067 // malloc, is being cast below to UINT32 to be used as
1068 // the |req_id| parameter of BTA_JvL2capWriteFixed and
1069 // BTA_JvL2capWrite. The "id" then gets freed in an
1070 // obscure callback elsewhere. We need to watch out for
1071 // this type of unsafe practice, as this is error prone
1072 // and difficult to follow.
1073 if (sock->fixed_chan) {
1074 if (BTA_JvL2capWriteFixed(sock->channel,
1075 (BD_ADDR*)&sock->addr,
1076 PTR_TO_UINT(buffer),
1077 btsock_l2cap_cbk, buffer,
1079 UINT_TO_PTR(user_id)) != BTA_JV_SUCCESS) {
1080 // On fail, free the buffer
1081 on_l2cap_write_fixed_done(buffer, count, user_id);
1084 if (BTA_JvL2capWrite(sock->handle, PTR_TO_UINT(buffer),
1086 UINT_TO_PTR(user_id)) != BTA_JV_SUCCESS) {
1087 // On fail, free the buffer
1088 on_l2cap_write_done(buffer, count, user_id);
1095 if (flags & SOCK_THREAD_FD_WR) {
1096 //app is ready to receive more data, tell stack to enable the data flow
1097 if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected)
1098 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
1100 if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) {
1102 if (drop_it || ioctl(sock->our_fd, FIONREAD, &size) != 0 || size == 0)
1103 btsock_l2cap_free_l(sock);
1106 pthread_mutex_unlock(&state_lock);