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.
90 static bt_status_t btSock_start_l2cap_server_l(l2cap_socket *sock);
92 static pthread_mutex_t state_lock;
94 l2cap_socket *socks = NULL;
95 static uid_set_t* uid_set = NULL;
98 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data);
100 /* TODO: Consider to remove this buffer, as we have a buffer in l2cap as well, and we risk
101 * a buffer overflow with this implementation if the socket data is not read from
102 * JAVA for a while. In such a case we should use flow control to tell the sender to
104 * BUT remember we need to avoid blocking the BTA task execution - hence we cannot
105 * directly write to the socket.
106 * we should be able to change to store the data pointer here, and just wait
107 * confirming the l2cap_ind until we have more space in the buffer. */
109 /* returns FALSE if none - caller must free "data" memory when done with it */
110 static char packet_get_head_l(l2cap_socket *sock, uint8_t **data, uint32_t *len)
112 struct packet *p = sock->first_packet;
118 *data = sock->first_packet->data;
120 *len = sock->first_packet->len;
121 sock->first_packet = p->next;
122 if (sock->first_packet)
123 sock->first_packet->prev = NULL;
125 sock->last_packet = NULL;
128 sock->bytes_buffered -= *len;
135 static struct packet *packet_alloc(const uint8_t *data, uint32_t len)
137 struct packet *p = osi_calloc(sizeof(*p));
138 uint8_t *buf = osi_malloc(len);
144 memcpy(p->data, data, len);
155 /* makes a copy of the data, returns TRUE on success */
156 static char packet_put_head_l(l2cap_socket *sock, const void *data, uint32_t len)
158 struct packet *p = packet_alloc((const uint8_t*)data, len);
161 * We do not check size limits here since this is used to undo "getting" a
162 * packet that the user read incompletely. That is to say the packet was
163 * already in the queue. We do check thos elimits in packet_put_tail_l() since
164 * that function is used to put new data into the queue.
171 p->next = sock->first_packet;
172 sock->first_packet = p;
176 sock->last_packet = p;
178 sock->bytes_buffered += len;
183 /* makes a copy of the data, returns TRUE on success */
184 static char packet_put_tail_l(l2cap_socket *sock, const void *data, uint32_t len)
186 struct packet *p = packet_alloc((const uint8_t*)data, len);
188 if (sock->bytes_buffered >= L2CAP_MAX_RX_BUFFER) {
189 LOG_ERROR(LOG_TAG, "packet_put_tail_l: buffer overflow");
194 LOG_ERROR(LOG_TAG, "packet_put_tail_l: unable to allocate packet...");
199 p->prev = sock->last_packet;
200 sock->last_packet = p;
204 sock->first_packet = p;
206 sock->bytes_buffered += len;
211 static inline void bd_copy(UINT8* dest, UINT8* src, BOOLEAN swap)
215 for (i =0; i < 6 ;i++)
218 else memcpy(dest, src, 6);
221 static char is_inited(void)
225 pthread_mutex_lock(&state_lock);
227 pthread_mutex_unlock(&state_lock);
232 /* only call with mutex taken */
233 static l2cap_socket *btsock_l2cap_find_by_id_l(uint32_t id)
235 l2cap_socket *sock = socks;
237 while (sock && sock->id != id)
243 static void btsock_l2cap_free_l(l2cap_socket *sock)
246 l2cap_socket *t = socks;
248 while(t && t != sock)
251 if (!t) /* prever double-frees */
255 sock->next->prev = sock->prev;
258 sock->prev->next = sock->next;
262 shutdown(sock->our_fd, SHUT_RDWR);
264 if (sock->app_fd != -1) {
267 APPL_TRACE_ERROR("SOCK_LIST: free(id = %d) - NO app_fd!", sock->id);
270 while (packet_get_head_l(sock, &buf, NULL))
273 //lower-level close() should be idempotent... so let's call it and see...
274 // Only call if we are non server connections
275 if (sock->handle && (sock->server == FALSE)) {
276 if (sock->fixed_chan)
277 BTA_JvL2capCloseLE(sock->handle);
279 BTA_JvL2capClose(sock->handle);
281 if ((sock->channel >= 0) && (sock->server == TRUE)) {
282 if (sock->fixed_chan) {
283 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP_LE);
285 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP);
289 APPL_TRACE_DEBUG("SOCK_LIST: free(id = %d)", sock->id);
293 static l2cap_socket *btsock_l2cap_alloc_l(const char *name, const bt_bdaddr_t *addr,
294 char is_server, int flags)
297 unsigned security = 0;
300 if (flags & BTSOCK_FLAG_ENCRYPT)
301 security |= is_server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
302 if (flags & BTSOCK_FLAG_AUTH)
303 security |= is_server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
304 if (flags & BTSOCK_FLAG_AUTH_MITM)
305 security |= is_server ? BTM_SEC_IN_MITM : BTM_SEC_OUT_MITM;
306 if (flags & BTSOCK_FLAG_AUTH_16_DIGIT)
307 security |= BTM_SEC_IN_MIN_16_DIGIT_PIN;
309 sock = osi_calloc(sizeof(*sock));
311 APPL_TRACE_ERROR("alloc failed");
315 if (socketpair(AF_LOCAL, SOCK_SEQPACKET, 0, fds)) {
316 APPL_TRACE_ERROR("socketpair failed, errno:%d", errno);
320 sock->our_fd = fds[0];
321 sock->app_fd = fds[1];
322 sock->security = security;
323 sock->server = is_server;
324 sock->connected = FALSE;
326 sock->server_psm_sent = FALSE;
330 strncpy(sock->name, name, sizeof(sock->name) - 1);
334 sock->first_packet = NULL;
335 sock->last_packet = NULL;
341 sock->id = (socks ? socks->id : 0) + 1;
343 /* paranoia cap on: verify no ID duplicates due to overflow and fix as needed */
347 while (t && t->id != sock->id) {
350 if (!t && sock->id) /* non-zeor handle is unique -> we're done */
352 /* if we're here, we found a duplicate */
353 if (!++sock->id) /* no zero IDs allowed */
356 APPL_TRACE_DEBUG("SOCK_LIST: alloc(id = %d)", sock->id);
366 bt_status_t btsock_l2cap_init(int handle, uid_set_t* set)
368 APPL_TRACE_DEBUG("btsock_l2cap_init...");
369 pthread_mutex_lock(&state_lock);
373 pthread_mutex_unlock(&state_lock);
375 return BT_STATUS_SUCCESS;
378 bt_status_t btsock_l2cap_cleanup()
380 pthread_mutex_lock(&state_lock);
383 btsock_l2cap_free_l(socks);
384 pthread_mutex_unlock(&state_lock);
386 return BT_STATUS_SUCCESS;
389 static inline BOOLEAN send_app_psm_or_chan_l(l2cap_socket *sock)
391 return sock_send_all(sock->our_fd, (const uint8_t*)&sock->channel, sizeof(sock->channel))
392 == sizeof(sock->channel);
395 static BOOLEAN send_app_connect_signal(int fd, const bt_bdaddr_t* addr,
396 int channel, int status, int send_fd, int tx_mtu)
398 sock_connect_signal_t cs;
399 cs.size = sizeof(cs);
401 cs.channel = channel;
403 cs.max_rx_packet_size = L2CAP_MAX_SDU_LENGTH;
404 cs.max_tx_packet_size = tx_mtu;
406 if (sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == sizeof(cs))
408 else APPL_TRACE_ERROR("sock_send_fd failed, fd:%d, send_fd:%d", fd, send_fd);
409 } else if (sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs)) {
415 static void on_srv_l2cap_listen_started(tBTA_JV_L2CAP_START *p_start, uint32_t id)
419 pthread_mutex_lock(&state_lock);
420 sock = btsock_l2cap_find_by_id_l(id);
422 if (p_start->status != BTA_JV_SUCCESS) {
423 APPL_TRACE_ERROR("Error starting l2cap_listen - status: 0x%04x", p_start->status);
424 btsock_l2cap_free_l(sock);
427 sock->handle = p_start->handle;
428 APPL_TRACE_DEBUG("on_srv_l2cap_listen_started() sock->handle =%d id:%d",
429 sock->handle, sock->id);
430 if(sock->server_psm_sent == FALSE) {
431 if (!send_app_psm_or_chan_l(sock)) {
433 APPL_TRACE_DEBUG("send_app_psm() failed, close rs->id:%d", sock->id);
434 btsock_l2cap_free_l(sock);
436 sock->server_psm_sent = TRUE;
441 pthread_mutex_unlock(&state_lock);
444 static void on_cl_l2cap_init(tBTA_JV_L2CAP_CL_INIT *p_init, uint32_t id)
448 pthread_mutex_lock(&state_lock);
449 sock = btsock_l2cap_find_by_id_l(id);
451 if (p_init->status != BTA_JV_SUCCESS) {
452 btsock_l2cap_free_l(sock);
454 sock->handle = p_init->handle;
457 pthread_mutex_unlock(&state_lock);
461 * Here we allocate a new sock instance to mimic the BluetoothSocket. The socket will be a clone
462 * of the sock representing the BluetoothServerSocket.
464 static void on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN *p_open, l2cap_socket *sock)
466 l2cap_socket *accept_rs;
467 uint32_t new_listen_id;
469 // Mutex locked by caller
470 accept_rs = btsock_l2cap_alloc_l(sock->name, (const bt_bdaddr_t*)p_open->rem_bda, FALSE, 0);
471 accept_rs->connected = TRUE;
472 accept_rs->security = sock->security;
473 accept_rs->fixed_chan = sock->fixed_chan;
474 accept_rs->channel = sock->channel;
475 accept_rs->handle = sock->handle;
476 accept_rs->app_uid = sock->app_uid;
477 sock->handle = -1; /* We should no longer associate this handle with the server socket */
479 /* Swap IDs to hand over the GAP connection to the accepted socket, and start a new server on
480 the newly create socket ID. */
481 new_listen_id = accept_rs->id;
482 accept_rs->id = sock->id;
483 sock->id = new_listen_id;
486 //start monitor the socket
487 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id);
488 btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
490 APPL_TRACE_DEBUG("sending connect signal & app fd: %d to app server to accept() the"
491 " connection", accept_rs->app_fd);
492 APPL_TRACE_DEBUG("server fd:%d, scn:%d", sock->our_fd, sock->channel);
493 send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0,
494 accept_rs->app_fd, p_open->tx_mtu);
495 accept_rs->app_fd = -1; // The fd is closed after sent to app in send_app_connect_signal()
496 // But for some reason we still leak a FD - either the server socket
497 // one or the accept socket one.
498 if(btSock_start_l2cap_server_l(sock) != BT_STATUS_SUCCESS) {
499 btsock_l2cap_free_l(sock);
504 static void on_srv_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN *p_open, l2cap_socket *sock)
506 l2cap_socket *accept_rs;
507 uint32_t new_listen_id;
509 // mutex locked by caller
510 accept_rs = btsock_l2cap_alloc_l(sock->name, (const bt_bdaddr_t*)p_open->rem_bda, FALSE, 0);
514 new_listen_id = accept_rs->id;
515 accept_rs->id = sock->id;
516 sock->id = new_listen_id;
518 accept_rs->handle = p_open->handle;
519 accept_rs->connected = TRUE;
520 accept_rs->security = sock->security;
521 accept_rs->fixed_chan = sock->fixed_chan;
522 accept_rs->channel = sock->channel;
523 accept_rs->app_uid = sock->app_uid;
525 //if we do not set a callback, this socket will be dropped */
526 *(p_open->p_p_cback) = (void*)btsock_l2cap_cbk;
527 *(p_open->p_user_data) = UINT_TO_PTR(accept_rs->id);
529 //start monitor the socket
530 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id);
531 btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
533 APPL_TRACE_DEBUG("sending connect signal & app fd:%dto app server to accept() the"
534 " connection", accept_rs->app_fd);
535 APPL_TRACE_DEBUG("server fd:%d, scn:%d", sock->our_fd, sock->channel);
536 send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0,
537 accept_rs->app_fd, p_open->tx_mtu);
538 accept_rs->app_fd = -1; //the fd is closed after sent to app
542 static void on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN *p_open, l2cap_socket *sock)
544 bd_copy(sock->addr.address, p_open->rem_bda, 0);
546 if (!send_app_psm_or_chan_l(sock)) {
547 APPL_TRACE_ERROR("send_app_psm_or_chan_l failed");
551 if (send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1, p_open->tx_mtu)) {
552 //start monitoring the socketpair to get call back when app writing data
553 APPL_TRACE_DEBUG("on_l2cap_connect_ind, connect signal sent, slot id:%d, psm:%d,"
554 " server:%d", sock->id, sock->channel, sock->server);
555 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
556 sock->connected = TRUE;
558 else APPL_TRACE_ERROR("send_app_connect_signal failed");
561 static void on_cl_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN *p_open, l2cap_socket *sock)
563 bd_copy(sock->addr.address, p_open->rem_bda, 0);
565 if (!send_app_psm_or_chan_l(sock)) {
566 APPL_TRACE_ERROR("send_app_psm_or_chan_l failed");
570 if (send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1, p_open->tx_mtu)) {
571 //start monitoring the socketpair to get call back when app writing data
572 APPL_TRACE_DEBUG("on_l2cap_connect_ind, connect signal sent, slot id:%d, Chan:%d,"
573 " server:%d", sock->id, sock->channel, sock->server);
574 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
575 sock->connected = TRUE;
577 else APPL_TRACE_ERROR("send_app_connect_signal failed");
580 static void on_l2cap_connect(tBTA_JV *p_data, uint32_t id)
583 tBTA_JV_L2CAP_OPEN *psm_open = &p_data->l2c_open;
584 tBTA_JV_L2CAP_LE_OPEN *le_open = &p_data->l2c_le_open;
586 pthread_mutex_lock(&state_lock);
587 sock = btsock_l2cap_find_by_id_l(id);
589 APPL_TRACE_ERROR("on_l2cap_connect on unknown socket");
591 if (sock->fixed_chan && le_open->status == BTA_JV_SUCCESS) {
593 on_cl_l2cap_le_connect_l(le_open, sock);
595 on_srv_l2cap_le_connect_l(le_open, sock);
596 } else if (!sock->fixed_chan && psm_open->status == BTA_JV_SUCCESS) {
598 on_cl_l2cap_psm_connect_l(psm_open, sock);
600 on_srv_l2cap_psm_connect_l(psm_open, sock);
603 btsock_l2cap_free_l(sock);
605 pthread_mutex_unlock(&state_lock);
608 static void on_l2cap_close(tBTA_JV_L2CAP_CLOSE * p_close, uint32_t id)
612 pthread_mutex_lock(&state_lock);
613 sock = btsock_l2cap_find_by_id_l(id);
615 APPL_TRACE_DEBUG("on_l2cap_close, slot id:%d, fd:%d, %s:%d, server:%d",
616 sock->id, sock->our_fd, sock->fixed_chan ? "fixed_chan" : "PSM",
617 sock->channel, sock->server);
619 // TODO: This does not seem to be called...
620 // I'm not sure if this will be called for non-server sockets?
621 if(!sock->fixed_chan && (sock->server == TRUE)) {
622 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP);
624 btsock_l2cap_free_l(sock);
626 pthread_mutex_unlock(&state_lock);
629 static void on_l2cap_outgoing_congest(tBTA_JV_L2CAP_CONG *p, uint32_t id)
633 pthread_mutex_lock(&state_lock);
634 sock = btsock_l2cap_find_by_id_l(id);
636 sock->outgoing_congest = p->cong ? 1 : 0;
637 //mointer the fd for any outgoing data
638 if (!sock->outgoing_congest) {
639 APPL_TRACE_DEBUG("on_l2cap_outgoing_congest: adding fd to btsock_thread...");
640 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
644 pthread_mutex_unlock(&state_lock);
647 static void on_l2cap_write_done(void* req_id, uint16_t len, uint32_t id)
651 if (req_id != NULL) {
652 osi_free(req_id); //free the buffer
657 pthread_mutex_lock(&state_lock);
658 sock = btsock_l2cap_find_by_id_l(id);
660 app_uid = sock->app_uid;
661 if (!sock->outgoing_congest) {
662 //monitor the fd for any outgoing data
663 APPL_TRACE_DEBUG("on_l2cap_write_done: adding fd to btsock_thread...");
664 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
667 pthread_mutex_unlock(&state_lock);
669 uid_set_add_tx(uid_set, app_uid, len);
672 static void on_l2cap_write_fixed_done(void* req_id, uint16_t len, uint32_t id)
676 if (req_id != NULL) {
677 osi_free(req_id); //free the buffer
681 pthread_mutex_lock(&state_lock);
682 sock = btsock_l2cap_find_by_id_l(id);
684 app_uid = sock->app_uid;
685 if (!sock->outgoing_congest) {
686 //monitor the fd for any outgoing data
687 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
690 pthread_mutex_unlock(&state_lock);
692 uid_set_add_tx(uid_set, app_uid, len);
695 static void on_l2cap_data_ind(tBTA_JV *evt, uint32_t id)
700 UINT32 bytes_read = 0;
702 pthread_mutex_lock(&state_lock);
703 sock = btsock_l2cap_find_by_id_l(id);
705 app_uid = sock->app_uid;
707 if (sock->fixed_chan) { /* we do these differently */
709 tBTA_JV_LE_DATA_IND *p_le_data_ind = &evt->le_data_ind;
710 BT_HDR *p_buf = p_le_data_ind->p_buf;
711 uint8_t *data = (uint8_t*)(p_buf + 1) + p_buf->offset;
713 if (packet_put_tail_l(sock, data, p_buf->len)) {
714 bytes_read = p_buf->len;
715 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
716 } else {//connection must be dropped
717 APPL_TRACE_DEBUG("on_l2cap_data_ind() unable to push data to socket - closing"
719 BTA_JvL2capCloseLE(sock->handle);
720 btsock_l2cap_free_l(sock);
725 UINT8 buffer[L2CAP_MAX_SDU_LENGTH];
728 if (BTA_JvL2capReady(sock->handle, &count) == BTA_JV_SUCCESS) {
729 if (BTA_JvL2capRead(sock->handle, sock->id, buffer, count) == BTA_JV_SUCCESS) {
730 if (packet_put_tail_l(sock, buffer, count)) {
732 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR,
734 } else {//connection must be dropped
735 APPL_TRACE_DEBUG("on_l2cap_data_ind() unable to push data to socket"
736 " - closing channel");
737 BTA_JvL2capClose(sock->handle);
738 btsock_l2cap_free_l(sock);
744 pthread_mutex_unlock(&state_lock);
746 uid_set_add_rx(uid_set, app_uid, bytes_read);
749 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data)
751 uint32_t sock_id = PTR_TO_UINT(user_data);
754 case BTA_JV_L2CAP_START_EVT:
755 on_srv_l2cap_listen_started(&p_data->l2c_start, sock_id);
758 case BTA_JV_L2CAP_CL_INIT_EVT:
759 on_cl_l2cap_init(&p_data->l2c_cl_init, sock_id);
762 case BTA_JV_L2CAP_OPEN_EVT:
763 on_l2cap_connect(p_data, sock_id);
764 BTA_JvSetPmProfile(p_data->l2c_open.handle, BTA_JV_PM_ID_1,BTA_JV_CONN_OPEN);
767 case BTA_JV_L2CAP_CLOSE_EVT:
768 APPL_TRACE_DEBUG("BTA_JV_L2CAP_CLOSE_EVT: id: %u", sock_id);
769 on_l2cap_close(&p_data->l2c_close, sock_id);
772 case BTA_JV_L2CAP_DATA_IND_EVT:
773 on_l2cap_data_ind(p_data, sock_id);
774 APPL_TRACE_DEBUG("BTA_JV_L2CAP_DATA_IND_EVT");
777 case BTA_JV_L2CAP_READ_EVT:
778 APPL_TRACE_DEBUG("BTA_JV_L2CAP_READ_EVT not used");
781 case BTA_JV_L2CAP_RECEIVE_EVT:
782 APPL_TRACE_DEBUG("BTA_JV_L2CAP_RECEIVE_EVT not used");
785 case BTA_JV_L2CAP_WRITE_EVT:
786 APPL_TRACE_DEBUG("BTA_JV_L2CAP_WRITE_EVT: id: %u", sock_id);
787 on_l2cap_write_done(UINT_TO_PTR(p_data->l2c_write.req_id), p_data->l2c_write.len, sock_id);
790 case BTA_JV_L2CAP_WRITE_FIXED_EVT:
791 APPL_TRACE_DEBUG("BTA_JV_L2CAP_WRITE_FIXED_EVT: id: %u", sock_id);
792 on_l2cap_write_fixed_done(UINT_TO_PTR(p_data->l2c_write_fixed.req_id), p_data->l2c_write.len, sock_id);
795 case BTA_JV_L2CAP_CONG_EVT:
796 on_l2cap_outgoing_congest(&p_data->l2c_cong, sock_id);
800 APPL_TRACE_ERROR("unhandled event %d, slot id: %u", event, sock_id);
805 /* L2CAP default options for OBEX socket connections */
806 const tL2CAP_FCR_OPTS obex_l2c_fcr_opts_def =
808 L2CAP_FCR_ERTM_MODE, /* Mandatory for OBEX over l2cap */
809 OBX_FCR_OPT_TX_WINDOW_SIZE_BR_EDR,/* Tx window size */
810 OBX_FCR_OPT_MAX_TX_B4_DISCNT, /* Maximum transmissions before disconnecting */
811 OBX_FCR_OPT_RETX_TOUT, /* Retransmission timeout (2 secs) */
812 OBX_FCR_OPT_MONITOR_TOUT, /* Monitor timeout (12 secs) */
813 OBX_FCR_OPT_MAX_PDU_SIZE /* MPS segment size */
815 const tL2CAP_ERTM_INFO obex_l2c_etm_opt =
817 L2CAP_FCR_ERTM_MODE, /* Mandatory for OBEX over l2cap */
818 L2CAP_FCR_CHAN_OPT_ERTM, /* Mandatory for OBEX over l2cap */
819 OBX_USER_RX_BUF_SIZE,
820 OBX_USER_TX_BUF_SIZE,
826 * When using a dynamic PSM, a PSM allocation is requested from btsock_l2cap_listen_or_connect().
827 * The PSM allocation event is refeived in the JV-callback - currently located in RFC-code -
828 * and this function is called with the newly allocated PSM.
830 void on_l2cap_psm_assigned(int id, int psm) {
832 /* Setup ETM settings:
833 * mtu will be set below */
834 pthread_mutex_lock(&state_lock);
835 sock = btsock_l2cap_find_by_id_l(id);
838 if(btSock_start_l2cap_server_l(sock) != BT_STATUS_SUCCESS) {
839 btsock_l2cap_free_l(sock);
842 pthread_mutex_unlock(&state_lock);
846 static bt_status_t btSock_start_l2cap_server_l(l2cap_socket *sock) {
848 bt_status_t stat = BT_STATUS_SUCCESS;
849 /* Setup ETM settings:
850 * mtu will be set below */
851 memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
853 cfg.fcr_present = TRUE;
854 cfg.fcr = obex_l2c_fcr_opts_def;
856 if (sock->fixed_chan) {
858 if (BTA_JvL2capStartServerLE(sock->security, 0, NULL, sock->channel,
859 L2CAP_DEFAULT_MTU, NULL, btsock_l2cap_cbk, UINT_TO_PTR(sock->id))
861 stat = BT_STATUS_FAIL;
864 /* If we have a channel specified in the request, just start the server,
865 * else we request a PSM and start the server after we receive a PSM. */
866 if(sock->channel < 0) {
867 if(BTA_JvGetChannelId(BTA_JV_CONN_TYPE_L2CAP, UINT_TO_PTR(sock->id), 0)
869 stat = BT_STATUS_FAIL;
871 if (BTA_JvL2capStartServer(sock->security, 0, &obex_l2c_etm_opt,
872 sock->channel, L2CAP_MAX_SDU_LENGTH, &cfg, btsock_l2cap_cbk, UINT_TO_PTR(sock->id))
874 stat = BT_STATUS_FAIL;
880 static bt_status_t btsock_l2cap_listen_or_connect(const char *name, const bt_bdaddr_t *addr,
881 int channel, int* sock_fd, int flags, char listen, int app_uid)
889 return BT_STATUS_PARM_INVALID;
892 // We need to auto assign a PSM
895 fixed_chan = (channel & L2CAP_MASK_FIXED_CHANNEL) != 0;
896 channel &=~ L2CAP_MASK_FIXED_CHANNEL;
900 return BT_STATUS_NOT_READY;
902 // TODO: This is kind of bad to lock here, but it is needed for the current design.
903 pthread_mutex_lock(&state_lock);
905 sock = btsock_l2cap_alloc_l(name, addr, listen, flags);
907 return BT_STATUS_NOMEM;
909 sock->fixed_chan = fixed_chan;
910 sock->channel = channel;
911 sock->app_uid = app_uid;
913 stat = BT_STATUS_SUCCESS;
915 /* Setup ETM settings:
916 * mtu will be set below */
917 memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
919 cfg.fcr_present = TRUE;
920 cfg.fcr = obex_l2c_fcr_opts_def;
922 /* "role" is never initialized in rfcomm code */
924 stat = btSock_start_l2cap_server_l(sock);
927 if (BTA_JvL2capConnectLE(sock->security, 0, NULL, channel,
928 L2CAP_DEFAULT_MTU, NULL, sock->addr.address, btsock_l2cap_cbk,
929 UINT_TO_PTR(sock->id)) != BTA_JV_SUCCESS)
930 stat = BT_STATUS_FAIL;
933 if (BTA_JvL2capConnect(sock->security, 0, &obex_l2c_etm_opt,
934 channel, L2CAP_MAX_SDU_LENGTH, &cfg, sock->addr.address,
935 btsock_l2cap_cbk, UINT_TO_PTR(sock->id)) != BTA_JV_SUCCESS)
936 stat = BT_STATUS_FAIL;
940 if (stat == BT_STATUS_SUCCESS) {
941 *sock_fd = sock->app_fd;
942 /* We pass the FD to JAVA, but since it runs in another process, we need to also close
943 * it in native, either straight away, as done when accepting an incoming connection,
944 * or when doing cleanup after this socket */
945 sock->app_fd = -1; /*This leaks the file descriptor. The FD should be closed in
946 JAVA but it apparently do not work */
947 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION,
950 btsock_l2cap_free_l(sock);
952 pthread_mutex_unlock(&state_lock);
957 bt_status_t btsock_l2cap_listen(const char* name, int channel, int* sock_fd, int flags, int app_uid)
959 return btsock_l2cap_listen_or_connect(name, NULL, channel, sock_fd, flags, 1, app_uid);
962 bt_status_t btsock_l2cap_connect(const bt_bdaddr_t *bd_addr, int channel, int* sock_fd, int flags, int app_uid)
964 return btsock_l2cap_listen_or_connect(NULL, bd_addr, channel, sock_fd, flags, 0, app_uid);
967 /* return TRUE if we have more to send and should wait for user readiness, FALSE else
968 * (for example: unrecoverable error or no data)
970 static BOOLEAN flush_incoming_que_on_wr_signal_l(l2cap_socket *sock)
975 while (packet_get_head_l(sock, &buf, &len)) {
976 int sent = send(sock->our_fd, buf, len, MSG_DONTWAIT);
978 if (sent == (signed)len)
980 else if (sent >= 0) {
981 packet_put_head_l(sock, buf + sent, len - sent);
983 if (!sent) /* special case if other end not keeping up */
987 packet_put_head_l(sock, buf, len);
989 return errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN;
996 void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id)
999 char drop_it = FALSE;
1001 /* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to hold the lock. */
1002 pthread_mutex_lock(&state_lock);
1003 sock = btsock_l2cap_find_by_id_l(user_id);
1005 if ((flags & SOCK_THREAD_FD_RD) && !sock->server) {
1007 if (sock->connected) {
1010 if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(sock->our_fd, FIONREAD, &size)
1012 uint8_t *buffer = osi_malloc(L2CAP_MAX_SDU_LENGTH);
1013 //uint8_t *buffer = (uint8_t*)osi_getbuf(L2CAP_MAX_SDU_LENGTH);
1014 /* Apparently we hijack the req_id (UINT32) to pass the pointer to the buffer to
1015 * the write complete callback, which call a free... wonder if this works on a
1016 * 64 bit platform? */
1017 if (buffer != NULL) {
1018 /* The socket is created with SOCK_SEQPACKET, hence we read one message at
1019 * the time. The maximum size of a message is allocated to ensure data is
1020 * not lost. This is okay to do as Android uses virtual memory, hence even
1021 * if we only use a fraction of the memory it should not block for others
1022 * to use the memory. As the definition of ioctl(FIONREAD) do not clearly
1023 * define what value will be returned if multiple messages are written to
1024 * the socket before any message is read from the socket, we could
1025 * potentially risk to allocate way more memory than needed. One of the use
1026 * cases for this socket is obex where multiple 64kbyte messages are
1027 * typically written to the socket in a tight loop, hence we risk the ioctl
1028 * will return the total amount of data in the buffer, which could be
1029 * multiple 64kbyte chunks.
1030 * UPDATE: As the stack cannot handle 64kbyte buffers, the size is reduced
1031 * to around 8kbyte - and using malloc for buffer allocation here seems to
1033 * UPDATE: Since we are responsible for freeing the buffer in the
1034 * write_complete_ind, it is OK to use malloc. */
1035 int count = recv(fd, buffer, L2CAP_MAX_SDU_LENGTH,
1036 MSG_NOSIGNAL | MSG_DONTWAIT);
1037 APPL_TRACE_DEBUG("btsock_l2cap_signaled - %d bytes received from socket",
1040 // TODO(armansito): |buffer|, which is created above via
1041 // malloc, is being cast below to UINT32 to be used as
1042 // the |req_id| parameter of BTA_JvL2capWriteFixed and
1043 // BTA_JvL2capWrite. The "id" then gets freed in an
1044 // obscure callback elsewhere. We need to watch out for
1045 // this type of unsafe practice, as this is error prone
1046 // and difficult to follow.
1047 if (sock->fixed_chan) {
1048 if(BTA_JvL2capWriteFixed(sock->channel, (BD_ADDR*)&sock->addr,
1049 PTR_TO_UINT(buffer), btsock_l2cap_cbk, buffer, count,
1050 UINT_TO_PTR(user_id)) != BTA_JV_SUCCESS) {
1051 // On fail, free the buffer
1052 on_l2cap_write_fixed_done(buffer, count, user_id);
1055 if(BTA_JvL2capWrite(sock->handle, PTR_TO_UINT(buffer), buffer, count,
1056 UINT_TO_PTR(user_id)) != BTA_JV_SUCCESS) {
1057 // On fail, free the buffer
1058 on_l2cap_write_done(buffer, count, user_id);
1062 // This cannot happen.
1063 APPL_TRACE_ERROR("Unable to allocate memory for data packet from JAVA...")
1069 if (flags & SOCK_THREAD_FD_WR) {
1070 //app is ready to receive more data, tell stack to enable the data flow
1071 if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected)
1072 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
1074 if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) {
1076 if (drop_it || ioctl(sock->our_fd, FIONREAD, &size) != 0 || size == 0)
1077 btsock_l2cap_free_l(sock);
1080 pthread_mutex_unlock(&state_lock);