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("btsock_l2cap_init...");
365 pthread_mutex_lock(&state_lock);
369 pthread_mutex_unlock(&state_lock);
371 return BT_STATUS_SUCCESS;
374 bt_status_t btsock_l2cap_cleanup()
376 pthread_mutex_lock(&state_lock);
379 btsock_l2cap_free_l(socks);
380 pthread_mutex_unlock(&state_lock);
382 return BT_STATUS_SUCCESS;
385 static inline BOOLEAN send_app_psm_or_chan_l(l2cap_socket *sock)
387 return sock_send_all(sock->our_fd, (const uint8_t*)&sock->channel, sizeof(sock->channel))
388 == sizeof(sock->channel);
391 static BOOLEAN send_app_connect_signal(int fd, const bt_bdaddr_t* addr,
392 int channel, int status, int send_fd, int tx_mtu)
394 sock_connect_signal_t cs;
395 cs.size = sizeof(cs);
397 cs.channel = channel;
399 cs.max_rx_packet_size = L2CAP_MAX_SDU_LENGTH;
400 cs.max_tx_packet_size = tx_mtu;
402 if (sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == sizeof(cs))
404 else APPL_TRACE_ERROR("sock_send_fd failed, fd:%d, send_fd:%d", fd, send_fd);
405 } else if (sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs)) {
411 static void on_srv_l2cap_listen_started(tBTA_JV_L2CAP_START *p_start, uint32_t id)
415 pthread_mutex_lock(&state_lock);
416 sock = btsock_l2cap_find_by_id_l(id);
418 if (p_start->status != BTA_JV_SUCCESS) {
419 APPL_TRACE_ERROR("Error starting l2cap_listen - status: 0x%04x", p_start->status);
420 btsock_l2cap_free_l(sock);
423 sock->handle = p_start->handle;
424 APPL_TRACE_DEBUG("on_srv_l2cap_listen_started() sock->handle =%d id:%d",
425 sock->handle, sock->id);
426 if(sock->server_psm_sent == FALSE) {
427 if (!send_app_psm_or_chan_l(sock)) {
429 APPL_TRACE_DEBUG("send_app_psm() failed, close rs->id:%d", sock->id);
430 btsock_l2cap_free_l(sock);
432 sock->server_psm_sent = TRUE;
437 pthread_mutex_unlock(&state_lock);
440 static void on_cl_l2cap_init(tBTA_JV_L2CAP_CL_INIT *p_init, uint32_t id)
444 pthread_mutex_lock(&state_lock);
445 sock = btsock_l2cap_find_by_id_l(id);
447 if (p_init->status != BTA_JV_SUCCESS) {
448 btsock_l2cap_free_l(sock);
450 sock->handle = p_init->handle;
453 pthread_mutex_unlock(&state_lock);
457 * Here we allocate a new sock instance to mimic the BluetoothSocket. The socket will be a clone
458 * of the sock representing the BluetoothServerSocket.
460 static void on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN *p_open, l2cap_socket *sock)
462 l2cap_socket *accept_rs;
463 uint32_t new_listen_id;
465 // Mutex locked by caller
466 accept_rs = btsock_l2cap_alloc_l(sock->name, (const bt_bdaddr_t*)p_open->rem_bda, FALSE, 0);
467 accept_rs->connected = TRUE;
468 accept_rs->security = sock->security;
469 accept_rs->fixed_chan = sock->fixed_chan;
470 accept_rs->channel = sock->channel;
471 accept_rs->handle = sock->handle;
472 accept_rs->app_uid = sock->app_uid;
473 sock->handle = -1; /* We should no longer associate this handle with the server socket */
474 accept_rs->is_le_coc = sock->is_le_coc;
476 /* Swap IDs to hand over the GAP connection to the accepted socket, and start a new server on
477 the newly create socket ID. */
478 new_listen_id = accept_rs->id;
479 accept_rs->id = sock->id;
480 sock->id = new_listen_id;
483 //start monitor the socket
484 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id);
485 btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
487 APPL_TRACE_DEBUG("sending connect signal & app fd: %d to app server to accept() the"
488 " connection", accept_rs->app_fd);
489 APPL_TRACE_DEBUG("server fd:%d, scn:%d", sock->our_fd, sock->channel);
490 send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0,
491 accept_rs->app_fd, p_open->tx_mtu);
492 accept_rs->app_fd = -1; // The fd is closed after sent to app in send_app_connect_signal()
493 // But for some reason we still leak a FD - either the server socket
494 // one or the accept socket one.
495 if(btSock_start_l2cap_server_l(sock) != BT_STATUS_SUCCESS) {
496 btsock_l2cap_free_l(sock);
501 static void on_srv_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN *p_open, l2cap_socket *sock)
503 l2cap_socket *accept_rs;
504 uint32_t new_listen_id;
506 // mutex locked by caller
507 accept_rs = btsock_l2cap_alloc_l(sock->name, (const bt_bdaddr_t*)p_open->rem_bda, FALSE, 0);
511 new_listen_id = accept_rs->id;
512 accept_rs->id = sock->id;
513 sock->id = new_listen_id;
515 accept_rs->handle = p_open->handle;
516 accept_rs->connected = TRUE;
517 accept_rs->security = sock->security;
518 accept_rs->fixed_chan = sock->fixed_chan;
519 accept_rs->channel = sock->channel;
520 accept_rs->app_uid = sock->app_uid;
522 //if we do not set a callback, this socket will be dropped */
523 *(p_open->p_p_cback) = (void*)btsock_l2cap_cbk;
524 *(p_open->p_user_data) = UINT_TO_PTR(accept_rs->id);
526 //start monitor the socket
527 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id);
528 btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
530 APPL_TRACE_DEBUG("sending connect signal & app fd:%dto app server to accept() the"
531 " connection", accept_rs->app_fd);
532 APPL_TRACE_DEBUG("server fd:%d, scn:%d", sock->our_fd, sock->channel);
533 send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0,
534 accept_rs->app_fd, p_open->tx_mtu);
535 accept_rs->app_fd = -1; //the fd is closed after sent to app
539 static void on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN *p_open, l2cap_socket *sock)
541 bd_copy(sock->addr.address, p_open->rem_bda, 0);
543 if (!send_app_psm_or_chan_l(sock)) {
544 APPL_TRACE_ERROR("send_app_psm_or_chan_l failed");
548 if (send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1, p_open->tx_mtu)) {
549 //start monitoring the socketpair to get call back when app writing data
550 APPL_TRACE_DEBUG("on_l2cap_connect_ind, connect signal sent, slot id:%d, psm:%d,"
551 " server:%d", sock->id, sock->channel, sock->server);
552 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
553 sock->connected = TRUE;
555 else APPL_TRACE_ERROR("send_app_connect_signal failed");
558 static void on_cl_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN *p_open, l2cap_socket *sock)
560 bd_copy(sock->addr.address, p_open->rem_bda, 0);
562 if (!send_app_psm_or_chan_l(sock)) {
563 APPL_TRACE_ERROR("send_app_psm_or_chan_l failed");
567 if (send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1, p_open->tx_mtu)) {
568 //start monitoring the socketpair to get call back when app writing data
569 APPL_TRACE_DEBUG("on_l2cap_connect_ind, connect signal sent, slot id:%d, Chan:%d,"
570 " server:%d", sock->id, sock->channel, sock->server);
571 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
572 sock->connected = TRUE;
574 else APPL_TRACE_ERROR("send_app_connect_signal failed");
577 static void on_l2cap_connect(tBTA_JV *p_data, uint32_t id)
580 tBTA_JV_L2CAP_OPEN *psm_open = &p_data->l2c_open;
581 tBTA_JV_L2CAP_LE_OPEN *le_open = &p_data->l2c_le_open;
583 pthread_mutex_lock(&state_lock);
584 sock = btsock_l2cap_find_by_id_l(id);
586 APPL_TRACE_ERROR("on_l2cap_connect on unknown socket");
588 if (sock->fixed_chan && le_open->status == BTA_JV_SUCCESS) {
590 on_cl_l2cap_le_connect_l(le_open, sock);
592 on_srv_l2cap_le_connect_l(le_open, sock);
593 } else if (!sock->fixed_chan && psm_open->status == BTA_JV_SUCCESS) {
595 on_cl_l2cap_psm_connect_l(psm_open, sock);
597 on_srv_l2cap_psm_connect_l(psm_open, sock);
600 btsock_l2cap_free_l(sock);
602 pthread_mutex_unlock(&state_lock);
605 static void on_l2cap_close(tBTA_JV_L2CAP_CLOSE * p_close, uint32_t id)
609 pthread_mutex_lock(&state_lock);
610 sock = btsock_l2cap_find_by_id_l(id);
612 APPL_TRACE_DEBUG("on_l2cap_close, slot id:%d, fd:%d, %s:%d, server:%d",
613 sock->id, sock->our_fd, sock->fixed_chan ? "fixed_chan" : "PSM",
614 sock->channel, sock->server);
615 // TODO: This does not seem to be called...
616 // I'm not sure if this will be called for non-server sockets?
617 if(!sock->fixed_chan && (sock->server == TRUE)) {
618 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP);
620 btsock_l2cap_free_l(sock);
622 pthread_mutex_unlock(&state_lock);
625 static void on_l2cap_outgoing_congest(tBTA_JV_L2CAP_CONG *p, uint32_t id)
629 pthread_mutex_lock(&state_lock);
630 sock = btsock_l2cap_find_by_id_l(id);
632 sock->outgoing_congest = p->cong ? 1 : 0;
633 //mointer the fd for any outgoing data
634 if (!sock->outgoing_congest) {
635 APPL_TRACE_DEBUG("on_l2cap_outgoing_congest: adding fd to btsock_thread...");
636 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
640 pthread_mutex_unlock(&state_lock);
643 static void on_l2cap_write_done(void* req_id, uint16_t len, uint32_t id)
647 if (req_id != NULL) {
648 osi_free(req_id); //free the buffer
653 pthread_mutex_lock(&state_lock);
654 sock = btsock_l2cap_find_by_id_l(id);
656 app_uid = sock->app_uid;
657 if (!sock->outgoing_congest) {
658 //monitor the fd for any outgoing data
659 APPL_TRACE_DEBUG("on_l2cap_write_done: adding fd to btsock_thread...");
660 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
663 pthread_mutex_unlock(&state_lock);
665 uid_set_add_tx(uid_set, app_uid, len);
668 static void on_l2cap_write_fixed_done(void* req_id, uint16_t len, uint32_t id)
672 if (req_id != NULL) {
673 osi_free(req_id); //free the buffer
677 pthread_mutex_lock(&state_lock);
678 sock = btsock_l2cap_find_by_id_l(id);
680 app_uid = sock->app_uid;
681 if (!sock->outgoing_congest) {
682 //monitor the fd for any outgoing data
683 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
686 pthread_mutex_unlock(&state_lock);
688 uid_set_add_tx(uid_set, app_uid, len);
691 static void on_l2cap_data_ind(tBTA_JV *evt, uint32_t id)
696 UINT32 bytes_read = 0;
698 pthread_mutex_lock(&state_lock);
699 sock = btsock_l2cap_find_by_id_l(id);
701 app_uid = sock->app_uid;
703 if (sock->fixed_chan) { /* we do these differently */
705 tBTA_JV_LE_DATA_IND *p_le_data_ind = &evt->le_data_ind;
706 BT_HDR *p_buf = p_le_data_ind->p_buf;
707 uint8_t *data = (uint8_t*)(p_buf + 1) + p_buf->offset;
709 if (packet_put_tail_l(sock, data, p_buf->len)) {
710 bytes_read = p_buf->len;
711 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
712 } else {//connection must be dropped
713 APPL_TRACE_DEBUG("on_l2cap_data_ind() unable to push data to socket - closing"
715 BTA_JvL2capCloseLE(sock->handle);
716 btsock_l2cap_free_l(sock);
721 UINT8 buffer[L2CAP_MAX_SDU_LENGTH];
724 if (BTA_JvL2capReady(sock->handle, &count) == BTA_JV_SUCCESS) {
725 if (BTA_JvL2capRead(sock->handle, sock->id, buffer, count) == BTA_JV_SUCCESS) {
726 if (packet_put_tail_l(sock, buffer, count)) {
728 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR,
730 } else {//connection must be dropped
731 APPL_TRACE_DEBUG("on_l2cap_data_ind() unable to push data to socket"
732 " - closing channel");
733 BTA_JvL2capClose(sock->handle);
734 btsock_l2cap_free_l(sock);
740 pthread_mutex_unlock(&state_lock);
742 uid_set_add_rx(uid_set, app_uid, bytes_read);
745 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data)
747 uint32_t sock_id = PTR_TO_UINT(user_data);
750 case BTA_JV_L2CAP_START_EVT:
751 on_srv_l2cap_listen_started(&p_data->l2c_start, sock_id);
754 case BTA_JV_L2CAP_CL_INIT_EVT:
755 on_cl_l2cap_init(&p_data->l2c_cl_init, sock_id);
758 case BTA_JV_L2CAP_OPEN_EVT:
759 on_l2cap_connect(p_data, sock_id);
760 BTA_JvSetPmProfile(p_data->l2c_open.handle, BTA_JV_PM_ID_1,BTA_JV_CONN_OPEN);
763 case BTA_JV_L2CAP_CLOSE_EVT:
764 APPL_TRACE_DEBUG("BTA_JV_L2CAP_CLOSE_EVT: id: %u", sock_id);
765 on_l2cap_close(&p_data->l2c_close, sock_id);
768 case BTA_JV_L2CAP_DATA_IND_EVT:
769 on_l2cap_data_ind(p_data, sock_id);
770 APPL_TRACE_DEBUG("BTA_JV_L2CAP_DATA_IND_EVT");
773 case BTA_JV_L2CAP_READ_EVT:
774 APPL_TRACE_DEBUG("BTA_JV_L2CAP_READ_EVT not used");
777 case BTA_JV_L2CAP_RECEIVE_EVT:
778 APPL_TRACE_DEBUG("BTA_JV_L2CAP_RECEIVE_EVT not used");
781 case BTA_JV_L2CAP_WRITE_EVT:
782 APPL_TRACE_DEBUG("BTA_JV_L2CAP_WRITE_EVT: id: %u", sock_id);
783 on_l2cap_write_done(UINT_TO_PTR(p_data->l2c_write.req_id), p_data->l2c_write.len, sock_id);
786 case BTA_JV_L2CAP_WRITE_FIXED_EVT:
787 APPL_TRACE_DEBUG("BTA_JV_L2CAP_WRITE_FIXED_EVT: id: %u", sock_id);
788 on_l2cap_write_fixed_done(UINT_TO_PTR(p_data->l2c_write_fixed.req_id), p_data->l2c_write.len, sock_id);
791 case BTA_JV_L2CAP_CONG_EVT:
792 on_l2cap_outgoing_congest(&p_data->l2c_cong, sock_id);
796 APPL_TRACE_ERROR("unhandled event %d, slot id: %u", event, sock_id);
801 /* L2CAP default options for OBEX socket connections */
802 const tL2CAP_FCR_OPTS obex_l2c_fcr_opts_def =
804 L2CAP_FCR_ERTM_MODE, /* Mandatory for OBEX over l2cap */
805 OBX_FCR_OPT_TX_WINDOW_SIZE_BR_EDR,/* Tx window size */
806 OBX_FCR_OPT_MAX_TX_B4_DISCNT, /* Maximum transmissions before disconnecting */
807 OBX_FCR_OPT_RETX_TOUT, /* Retransmission timeout (2 secs) */
808 OBX_FCR_OPT_MONITOR_TOUT, /* Monitor timeout (12 secs) */
809 OBX_FCR_OPT_MAX_PDU_SIZE /* MPS segment size */
811 const tL2CAP_ERTM_INFO obex_l2c_etm_opt =
813 L2CAP_FCR_ERTM_MODE, /* Mandatory for OBEX over l2cap */
814 L2CAP_FCR_CHAN_OPT_ERTM, /* Mandatory for OBEX over l2cap */
815 OBX_USER_RX_BUF_SIZE,
816 OBX_USER_TX_BUF_SIZE,
822 * When using a dynamic PSM, a PSM allocation is requested from btsock_l2cap_listen_or_connect().
823 * The PSM allocation event is refeived in the JV-callback - currently located in RFC-code -
824 * and this function is called with the newly allocated PSM.
826 void on_l2cap_psm_assigned(int id, int psm) {
828 /* Setup ETM settings:
829 * mtu will be set below */
830 pthread_mutex_lock(&state_lock);
831 sock = btsock_l2cap_find_by_id_l(id);
834 if(btSock_start_l2cap_server_l(sock) != BT_STATUS_SUCCESS) {
835 btsock_l2cap_free_l(sock);
838 pthread_mutex_unlock(&state_lock);
842 static bt_status_t btSock_start_l2cap_server_l(l2cap_socket *sock) {
844 bt_status_t stat = BT_STATUS_SUCCESS;
845 /* Setup ETM settings:
846 * mtu will be set below */
847 memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
849 cfg.fcr_present = TRUE;
850 cfg.fcr = obex_l2c_fcr_opts_def;
852 if (sock->fixed_chan) {
854 if (BTA_JvL2capStartServerLE(sock->security, 0, NULL, sock->channel,
855 L2CAP_DEFAULT_MTU, NULL, btsock_l2cap_cbk, UINT_TO_PTR(sock->id))
857 stat = BT_STATUS_FAIL;
860 /* If we have a channel specified in the request, just start the server,
861 * else we request a PSM and start the server after we receive a PSM. */
862 if (sock->channel < 0) {
863 if (sock->is_le_coc) {
864 if (BTA_JvGetChannelId(BTA_JV_CONN_TYPE_L2CAP_LE, UINT_TO_PTR(sock->id), 0)
866 stat = BT_STATUS_FAIL;
870 if (BTA_JvGetChannelId(BTA_JV_CONN_TYPE_L2CAP, UINT_TO_PTR(sock->id), 0)
872 stat = BT_STATUS_FAIL;
875 if (sock->is_le_coc) {
876 if (BTA_JvL2capStartServer(BTA_JV_CONN_TYPE_L2CAP_LE, sock->security, 0, NULL,
877 sock->channel, L2CAP_MAX_SDU_LENGTH, &cfg, btsock_l2cap_cbk, UINT_TO_PTR(sock->id))
879 stat = BT_STATUS_FAIL;
883 if (BTA_JvL2capStartServer(BTA_JV_CONN_TYPE_L2CAP, sock->security, 0, &obex_l2c_etm_opt,
884 sock->channel, L2CAP_MAX_SDU_LENGTH, &cfg, btsock_l2cap_cbk, UINT_TO_PTR(sock->id))
886 stat = BT_STATUS_FAIL;
893 static bt_status_t btsock_l2cap_listen_or_connect(const char *name, const bt_bdaddr_t *addr,
894 int channel, int* sock_fd, int flags, char listen, int app_uid)
900 BOOLEAN is_le_coc = FALSE;
903 return BT_STATUS_PARM_INVALID;
906 // We need to auto assign a PSM
909 fixed_chan = (channel & L2CAP_MASK_FIXED_CHANNEL) != 0;
910 is_le_coc = (channel & L2CAP_MASK_LE_COC_CHANNEL) != 0;
911 channel &=~ (L2CAP_MASK_FIXED_CHANNEL | L2CAP_MASK_LE_COC_CHANNEL);
915 return BT_STATUS_NOT_READY;
917 // TODO: This is kind of bad to lock here, but it is needed for the current design.
918 pthread_mutex_lock(&state_lock);
920 sock = btsock_l2cap_alloc_l(name, addr, listen, flags);
922 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)) {
1001 int sent = send(sock->our_fd, buf, len, MSG_DONTWAIT);
1003 if (sent == (signed)len)
1005 else if (sent >= 0) {
1006 packet_put_head_l(sock, buf + sent, len - sent);
1008 if (!sent) /* special case if other end not keeping up */
1012 packet_put_head_l(sock, buf, len);
1014 return errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN;
1021 void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id)
1024 char drop_it = FALSE;
1026 /* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to hold the lock. */
1027 pthread_mutex_lock(&state_lock);
1028 sock = btsock_l2cap_find_by_id_l(user_id);
1030 if ((flags & SOCK_THREAD_FD_RD) && !sock->server) {
1032 if (sock->connected) {
1035 if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(sock->our_fd, FIONREAD, &size)
1037 uint8_t *buffer = osi_malloc(L2CAP_MAX_SDU_LENGTH);
1038 /* Apparently we hijack the req_id (UINT32) to pass the pointer to the buffer to
1039 * the write complete callback, which call a free... wonder if this works on a
1040 * 64 bit platform? */
1041 /* The socket is created with SOCK_SEQPACKET, hence we read one message at
1042 * the time. The maximum size of a message is allocated to ensure data is
1043 * not lost. This is okay to do as Android uses virtual memory, hence even
1044 * if we only use a fraction of the memory it should not block for others
1045 * to use the memory. As the definition of ioctl(FIONREAD) do not clearly
1046 * define what value will be returned if multiple messages are written to
1047 * the socket before any message is read from the socket, we could
1048 * potentially risk to allocate way more memory than needed. One of the use
1049 * cases for this socket is obex where multiple 64kbyte messages are
1050 * typically written to the socket in a tight loop, hence we risk the ioctl
1051 * will return the total amount of data in the buffer, which could be
1052 * multiple 64kbyte chunks.
1053 * UPDATE: As the stack cannot handle 64kbyte buffers, the size is reduced
1054 * to around 8kbyte - and using malloc for buffer allocation here seems to
1056 * UPDATE: Since we are responsible for freeing the buffer in the
1057 * write_complete_ind, it is OK to use malloc. */
1058 int count = recv(fd, buffer, L2CAP_MAX_SDU_LENGTH,
1059 MSG_NOSIGNAL | MSG_DONTWAIT);
1060 APPL_TRACE_DEBUG("btsock_l2cap_signaled - %d bytes received from socket",
1063 // TODO(armansito): |buffer|, which is created above via
1064 // malloc, is being cast below to UINT32 to be used as
1065 // the |req_id| parameter of BTA_JvL2capWriteFixed and
1066 // BTA_JvL2capWrite. The "id" then gets freed in an
1067 // obscure callback elsewhere. We need to watch out for
1068 // this type of unsafe practice, as this is error prone
1069 // and difficult to follow.
1070 if (sock->fixed_chan) {
1071 if (BTA_JvL2capWriteFixed(sock->channel,
1072 (BD_ADDR*)&sock->addr,
1073 PTR_TO_UINT(buffer),
1074 btsock_l2cap_cbk, buffer,
1076 UINT_TO_PTR(user_id)) != BTA_JV_SUCCESS) {
1077 // On fail, free the buffer
1078 on_l2cap_write_fixed_done(buffer, count, user_id);
1081 if (BTA_JvL2capWrite(sock->handle, PTR_TO_UINT(buffer),
1083 UINT_TO_PTR(user_id)) != BTA_JV_SUCCESS) {
1084 // On fail, free the buffer
1085 on_l2cap_write_done(buffer, count, user_id);
1092 if (flags & SOCK_THREAD_FD_WR) {
1093 //app is ready to receive more data, tell stack to enable the data flow
1094 if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected)
1095 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
1097 if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) {
1099 if (drop_it || ioctl(sock->our_fd, FIONREAD, &size) != 0 || size == 0)
1100 btsock_l2cap_free_l(sock);
1103 pthread_mutex_unlock(&state_lock);