Home | History | Annotate | Download | only in src
      1 /******************************************************************************
      2  *
      3  *  Copyright (C) 2009-2012 Broadcom Corporation
      4  *
      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:
      8  *
      9  *  http://www.apache.org/licenses/LICENSE-2.0
     10  *
     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.
     16  *
     17  ******************************************************************************/
     18 
     19 #define LOG_TAG "bt_btif_sock_rfcomm"
     20 
     21 #include <assert.h>
     22 #include <errno.h>
     23 #include <features.h>
     24 #include <pthread.h>
     25 #include <string.h>
     26 #include <sys/ioctl.h>
     27 #include <sys/socket.h>
     28 #include <sys/types.h>
     29 #include <unistd.h>
     30 
     31 #include <hardware/bluetooth.h>
     32 #include <hardware/bt_sock.h>
     33 
     34 #include "bt_target.h"
     35 #include "bta_api.h"
     36 #include "bta_jv_api.h"
     37 #include "bta_jv_co.h"
     38 #include "btif_common.h"
     39 #include "btif_sock_sdp.h"
     40 #include "btif_sock_thread.h"
     41 #include "btif_sock_util.h"
     42 #include "btif_uid.h"
     43 #include "btif_util.h"
     44 #include "btm_api.h"
     45 #include "btm_int.h"
     46 #include "btu.h"
     47 #include "bt_common.h"
     48 #include "hcimsgs.h"
     49 #include "osi/include/compat.h"
     50 #include "osi/include/list.h"
     51 #include "osi/include/log.h"
     52 #include "osi/include/osi.h"
     53 #include "port_api.h"
     54 #include "sdp_api.h"
     55 
     56 /* The JV interface can have only one user, hence we need to call a few
     57  * L2CAP functions from this file. */
     58 #include "btif_sock_l2cap.h"
     59 
     60 #define MAX_RFC_CHANNEL 30  // Maximum number of RFCOMM channels (1-30 inclusive).
     61 #define MAX_RFC_SESSION 7   // Maximum number of devices we can have an RFCOMM connection with.
     62 
     63 typedef struct {
     64   int outgoing_congest : 1;
     65   int pending_sdp_request : 1;
     66   int doing_sdp_request : 1;
     67   int server : 1;
     68   int connected : 1;
     69   int closing : 1;
     70 } flags_t;
     71 
     72 typedef struct {
     73   flags_t f;
     74   uint32_t id;  // Non-zero indicates a valid (in-use) slot.
     75   int security;
     76   int scn;      // Server channel number
     77   int scn_notified;
     78   bt_bdaddr_t addr;
     79   int is_service_uuid_valid;
     80   uint8_t service_uuid[16];
     81   char service_name[256];
     82   int fd;
     83   int app_fd;  // Temporary storage for the half of the socketpair that's sent back to upper layers.
     84   int app_uid; // UID of the app for which this socket was created.
     85   int mtu;
     86   uint8_t *packet;
     87   int sdp_handle;
     88   int rfc_handle;
     89   int rfc_port_handle;
     90   int role;
     91   list_t *incoming_queue;
     92 } rfc_slot_t;
     93 
     94 static rfc_slot_t rfc_slots[MAX_RFC_CHANNEL];
     95 static uint32_t rfc_slot_id;
     96 static volatile int pth = -1; // poll thread handle
     97 static pthread_mutex_t slot_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
     98 static uid_set_t* uid_set = NULL;
     99 
    100 static rfc_slot_t *find_free_slot(void);
    101 static void cleanup_rfc_slot(rfc_slot_t *rs);
    102 static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data);
    103 static void *rfcomm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data);
    104 static bool send_app_scn(rfc_slot_t *rs);
    105 
    106 static bool is_init_done(void) {
    107   return pth != -1;
    108 }
    109 
    110 bt_status_t btsock_rfc_init(int poll_thread_handle, uid_set_t* set) {
    111   pth = poll_thread_handle;
    112   uid_set = set;
    113 
    114   memset(rfc_slots, 0, sizeof(rfc_slots));
    115   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
    116     rfc_slots[i].scn = -1;
    117     rfc_slots[i].sdp_handle = 0;
    118     rfc_slots[i].fd = INVALID_FD;
    119     rfc_slots[i].app_fd = INVALID_FD;
    120     rfc_slots[i].incoming_queue = list_new(osi_free);
    121     assert(rfc_slots[i].incoming_queue != NULL);
    122   }
    123 
    124   BTA_JvEnable(jv_dm_cback);
    125 
    126   return BT_STATUS_SUCCESS;
    127 }
    128 
    129 void btsock_rfc_cleanup(void) {
    130   pth = -1;
    131   uid_set = NULL;
    132 
    133   pthread_mutex_lock(&slot_lock);
    134   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
    135     if (rfc_slots[i].id)
    136       cleanup_rfc_slot(&rfc_slots[i]);
    137     list_free(rfc_slots[i].incoming_queue);
    138     rfc_slots[i].incoming_queue = NULL;
    139   }
    140   pthread_mutex_unlock(&slot_lock);
    141 }
    142 
    143 static rfc_slot_t *find_free_slot(void) {
    144   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i)
    145     if (rfc_slots[i].fd == INVALID_FD)
    146       return &rfc_slots[i];
    147   return NULL;
    148 }
    149 
    150 static rfc_slot_t *find_rfc_slot_by_id(uint32_t id) {
    151   assert(id != 0);
    152 
    153   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i)
    154     if (rfc_slots[i].id == id)
    155       return &rfc_slots[i];
    156 
    157   LOG_ERROR(LOG_TAG, "%s unable to find RFCOMM slot id: %d", __func__, id);
    158   return NULL;
    159 }
    160 
    161 static rfc_slot_t *find_rfc_slot_by_pending_sdp(void) {
    162   uint32_t min_id = UINT32_MAX;
    163   int slot = -1;
    164   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i)
    165     if (rfc_slots[i].id && rfc_slots[i].f.pending_sdp_request && rfc_slots[i].id < min_id) {
    166       min_id = rfc_slots[i].id;
    167       slot = i;
    168     }
    169 
    170   return (slot == -1) ? NULL : &rfc_slots[slot];
    171 }
    172 
    173 static bool is_requesting_sdp(void) {
    174   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i)
    175     if (rfc_slots[i].id && rfc_slots[i].f.doing_sdp_request)
    176       return true;
    177   return false;
    178 }
    179 
    180 static rfc_slot_t *alloc_rfc_slot(const bt_bdaddr_t *addr, const char *name, const uint8_t *uuid, int channel, int flags, bool server) {
    181   int security = 0;
    182   if(flags & BTSOCK_FLAG_ENCRYPT)
    183       security |= server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
    184   if(flags & BTSOCK_FLAG_AUTH)
    185       security |= server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
    186   if(flags & BTSOCK_FLAG_AUTH_MITM)
    187       security |= server ? BTM_SEC_IN_MITM : BTM_SEC_OUT_MITM;
    188   if(flags & BTSOCK_FLAG_AUTH_16_DIGIT)
    189       security |= BTM_SEC_IN_MIN_16_DIGIT_PIN;
    190 
    191   rfc_slot_t *slot = find_free_slot();
    192   if (!slot) {
    193     LOG_ERROR(LOG_TAG, "%s unable to find free RFCOMM slot.", __func__);
    194     return NULL;
    195   }
    196 
    197   int fds[2] = { INVALID_FD, INVALID_FD };
    198   if (socketpair(AF_LOCAL, SOCK_STREAM, 0, fds) == -1) {
    199     LOG_ERROR(LOG_TAG, "%s error creating socketpair: %s", __func__, strerror(errno));
    200     return NULL;
    201   }
    202 
    203   // Increment slot id and make sure we don't use id=0.
    204   if (++rfc_slot_id == 0)
    205     rfc_slot_id = 1;
    206 
    207   slot->fd = fds[0];
    208   slot->app_fd = fds[1];
    209   slot->security = security;
    210   slot->scn = channel;
    211   slot->app_uid = -1;
    212 
    213   if(!is_uuid_empty(uuid)) {
    214     memcpy(slot->service_uuid, uuid, sizeof(slot->service_uuid));
    215     slot->is_service_uuid_valid = true;
    216   } else {
    217     memset(slot->service_uuid, 0, sizeof(slot->service_uuid));
    218     slot->is_service_uuid_valid = false;
    219   }
    220   if(name && *name) {
    221     strlcpy(slot->service_name, name, sizeof(slot->service_name));
    222   } else {
    223     memset(slot->service_name, 0, sizeof(slot->service_name));
    224   }
    225   if (addr)
    226     slot->addr = *addr;
    227 
    228   slot->id = rfc_slot_id;
    229   slot->f.server = server;
    230 
    231   return slot;
    232 }
    233 
    234 static rfc_slot_t *create_srv_accept_rfc_slot(rfc_slot_t *srv_rs, const bt_bdaddr_t *addr, int open_handle, int new_listen_handle) {
    235   rfc_slot_t *accept_rs = alloc_rfc_slot(addr, srv_rs->service_name, srv_rs->service_uuid, srv_rs->scn, 0, false);
    236   if (!accept_rs) {
    237     LOG_ERROR(LOG_TAG, "%s unable to allocate RFCOMM slot.", __func__);
    238     return NULL;
    239   }
    240 
    241   accept_rs->f.server = false;
    242   accept_rs->f.connected = true;
    243   accept_rs->security = srv_rs->security;
    244   accept_rs->mtu = srv_rs->mtu;
    245   accept_rs->role = srv_rs->role;
    246   accept_rs->rfc_handle = open_handle;
    247   accept_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(open_handle);
    248   accept_rs->app_uid = srv_rs->app_uid;
    249 
    250   srv_rs->rfc_handle = new_listen_handle;
    251   srv_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(new_listen_handle);
    252 
    253   assert(accept_rs->rfc_port_handle != srv_rs->rfc_port_handle);
    254 
    255   // now swap the slot id
    256   uint32_t new_listen_id = accept_rs->id;
    257   accept_rs->id = srv_rs->id;
    258   srv_rs->id = new_listen_id;
    259 
    260   return accept_rs;
    261 }
    262 
    263 bt_status_t btsock_rfc_listen(const char *service_name, const uint8_t *service_uuid, int channel, int *sock_fd, int flags, int app_uid) {
    264   assert(sock_fd != NULL);
    265   assert((service_uuid != NULL)
    266     || (channel >= 1 && channel <= MAX_RFC_CHANNEL)
    267     || ((flags & BTSOCK_FLAG_NO_SDP) != 0));
    268 
    269   *sock_fd = INVALID_FD;
    270 
    271   // TODO(sharvil): not sure that this check makes sense; seems like a logic error to call
    272   // functions on RFCOMM sockets before initializing the module. Probably should be an assert.
    273   if (!is_init_done())
    274     return BT_STATUS_NOT_READY;
    275 
    276   if((flags & BTSOCK_FLAG_NO_SDP) == 0) {
    277     if(is_uuid_empty(service_uuid)) {
    278       APPL_TRACE_DEBUG("BTA_JvGetChannelId: service_uuid not set AND "
    279               "BTSOCK_FLAG_NO_SDP is not set - changing to SPP");
    280       service_uuid = UUID_SPP;  // Use serial port profile to listen to specified channel
    281     } else {
    282       //Check the service_uuid. overwrite the channel # if reserved
    283       int reserved_channel = get_reserved_rfc_channel(service_uuid);
    284       if (reserved_channel > 0) {
    285             channel = reserved_channel;
    286       }
    287     }
    288   }
    289 
    290   int status = BT_STATUS_FAIL;
    291   pthread_mutex_lock(&slot_lock);
    292 
    293   rfc_slot_t *slot = alloc_rfc_slot(NULL, service_name, service_uuid, channel, flags, true);
    294   if (!slot) {
    295     LOG_ERROR(LOG_TAG, "%s unable to allocate RFCOMM slot.", __func__);
    296     goto out;
    297   }
    298   APPL_TRACE_DEBUG("BTA_JvGetChannelId: service_name: %s - channel: %d", service_name, channel);
    299   BTA_JvGetChannelId(BTA_JV_CONN_TYPE_RFCOMM, UINT_TO_PTR(slot->id), channel);
    300   *sock_fd = slot->app_fd;    // Transfer ownership of fd to caller.
    301   /*TODO:
    302    * We are leaking one of the app_fd's - either the listen socket, or the connection socket.
    303    * WE need to close this in native, as the FD might belong to another process
    304     - This is the server socket FD
    305     - For accepted connections, we close the FD after passing it to JAVA.
    306     - Try to simply remove the = -1 to free the FD at rs cleanup.*/
    307 //        close(rs->app_fd);
    308   slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
    309   slot->app_uid = app_uid;
    310   btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, slot->id);
    311 
    312   status = BT_STATUS_SUCCESS;
    313 
    314 out:;
    315   pthread_mutex_unlock(&slot_lock);
    316   return status;
    317 }
    318 
    319 bt_status_t btsock_rfc_connect(const bt_bdaddr_t *bd_addr, const uint8_t *service_uuid, int channel, int *sock_fd, int flags, int app_uid) {
    320   assert(sock_fd != NULL);
    321   assert(service_uuid != NULL || (channel >= 1 && channel <= MAX_RFC_CHANNEL));
    322 
    323   *sock_fd = INVALID_FD;
    324 
    325   // TODO(sharvil): not sure that this check makes sense; seems like a logic error to call
    326   // functions on RFCOMM sockets before initializing the module. Probably should be an assert.
    327   if (!is_init_done())
    328     return BT_STATUS_NOT_READY;
    329 
    330   int status = BT_STATUS_FAIL;
    331   pthread_mutex_lock(&slot_lock);
    332 
    333   rfc_slot_t *slot = alloc_rfc_slot(bd_addr, NULL, service_uuid, channel, flags, false);
    334   if (!slot) {
    335     LOG_ERROR(LOG_TAG, "%s unable to allocate RFCOMM slot.", __func__);
    336     goto out;
    337   }
    338 
    339   if (is_uuid_empty(service_uuid)) {
    340     tBTA_JV_STATUS ret = BTA_JvRfcommConnect(slot->security, slot->role, slot->scn, slot->addr.address, rfcomm_cback, (void *)(uintptr_t)slot->id);
    341     if (ret != BTA_JV_SUCCESS) {
    342       LOG_ERROR(LOG_TAG, "%s unable to initiate RFCOMM connection: %d", __func__, ret);
    343       cleanup_rfc_slot(slot);
    344       goto out;
    345     }
    346 
    347     if (!send_app_scn(slot)) {
    348       LOG_ERROR(LOG_TAG, "%s unable to send channel number.", __func__);
    349       cleanup_rfc_slot(slot);
    350       goto out;
    351     }
    352   } else {
    353     tSDP_UUID sdp_uuid;
    354     sdp_uuid.len = 16;
    355     memcpy(sdp_uuid.uu.uuid128, service_uuid, sizeof(sdp_uuid.uu.uuid128));
    356 
    357     if (!is_requesting_sdp()) {
    358       BTA_JvStartDiscovery((uint8_t *)bd_addr->address, 1, &sdp_uuid, (void *)(uintptr_t)slot->id);
    359       slot->f.pending_sdp_request = false;
    360       slot->f.doing_sdp_request = true;
    361     } else {
    362       slot->f.pending_sdp_request = true;
    363       slot->f.doing_sdp_request = false;
    364     }
    365   }
    366 
    367   *sock_fd = slot->app_fd;    // Transfer ownership of fd to caller.
    368   slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
    369   slot->app_uid = app_uid;
    370   btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
    371   status = BT_STATUS_SUCCESS;
    372 
    373 out:;
    374   pthread_mutex_unlock(&slot_lock);
    375   return status;
    376 }
    377 
    378 static int create_server_sdp_record(rfc_slot_t *slot) {
    379     if(slot->scn == 0) {
    380         return false;
    381     }
    382   slot->sdp_handle = add_rfc_sdp_rec(slot->service_name, slot->service_uuid, slot->scn);
    383   return (slot->sdp_handle > 0);
    384 }
    385 
    386 static void free_rfc_slot_scn(rfc_slot_t *slot) {
    387   if (slot->scn <= 0)
    388     return;
    389 
    390   if(slot->f.server && !slot->f.closing && slot->rfc_handle) {
    391     BTA_JvRfcommStopServer(slot->rfc_handle, (void *)(uintptr_t)slot->id);
    392     slot->rfc_handle = 0;
    393   }
    394 
    395   if (slot->f.server)
    396     BTM_FreeSCN(slot->scn);
    397   slot->scn = 0;
    398 }
    399 
    400 static void cleanup_rfc_slot(rfc_slot_t *slot) {
    401   if (slot->fd != INVALID_FD) {
    402     shutdown(slot->fd, SHUT_RDWR);
    403     close(slot->fd);
    404     slot->fd = INVALID_FD;
    405   }
    406 
    407   if (slot->app_fd != INVALID_FD) {
    408     close(slot->app_fd);
    409     slot->app_fd = INVALID_FD;
    410   }
    411 
    412   if (slot->sdp_handle > 0) {
    413     del_rfc_sdp_rec(slot->sdp_handle);
    414     slot->sdp_handle = 0;
    415   }
    416 
    417   if (slot->rfc_handle && !slot->f.closing && !slot->f.server) {
    418     BTA_JvRfcommClose(slot->rfc_handle, (void *)(uintptr_t)slot->id);
    419     slot->rfc_handle = 0;
    420   }
    421 
    422   free_rfc_slot_scn(slot);
    423   list_clear(slot->incoming_queue);
    424 
    425   slot->rfc_port_handle = 0;
    426   memset(&slot->f, 0, sizeof(slot->f));
    427   slot->id = 0;
    428   slot->scn_notified = false;
    429 }
    430 
    431 static bool send_app_scn(rfc_slot_t *slot) {
    432   if(slot->scn_notified == true) {
    433     //already send, just return success.
    434     return true;
    435   }
    436   slot->scn_notified = true;
    437   return sock_send_all(slot->fd, (const uint8_t*)&slot->scn, sizeof(slot->scn)) == sizeof(slot->scn);
    438 }
    439 
    440 static bool send_app_connect_signal(int fd, const bt_bdaddr_t* addr, int channel, int status, int send_fd) {
    441   sock_connect_signal_t cs;
    442   cs.size = sizeof(cs);
    443   cs.bd_addr = *addr;
    444   cs.channel = channel;
    445   cs.status = status;
    446   cs.max_rx_packet_size = 0; // not used for RFCOMM
    447   cs.max_tx_packet_size = 0; // not used for RFCOMM
    448   if (send_fd == INVALID_FD)
    449     return sock_send_all(fd, (const uint8_t *)&cs, sizeof(cs)) == sizeof(cs);
    450 
    451   return sock_send_fd(fd, (const uint8_t *)&cs, sizeof(cs), send_fd) == sizeof(cs);
    452 }
    453 
    454 static void on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT *p_init, uint32_t id) {
    455   pthread_mutex_lock(&slot_lock);
    456 
    457   rfc_slot_t *slot = find_rfc_slot_by_id(id);
    458   if (!slot)
    459     goto out;
    460 
    461   if (p_init->status == BTA_JV_SUCCESS)
    462     slot->rfc_handle = p_init->handle;
    463   else
    464     cleanup_rfc_slot(slot);
    465 
    466 out:;
    467   pthread_mutex_unlock(&slot_lock);
    468 }
    469 
    470 static void on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START *p_start, uint32_t id) {
    471   pthread_mutex_lock(&slot_lock);
    472 
    473   rfc_slot_t *slot = find_rfc_slot_by_id(id);
    474   if (!slot)
    475     goto out;
    476 
    477   if (p_start->status == BTA_JV_SUCCESS) {
    478     slot->rfc_handle = p_start->handle;
    479   } else
    480     cleanup_rfc_slot(slot);
    481 
    482 out:;
    483   pthread_mutex_unlock(&slot_lock);
    484 }
    485 
    486 static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN *p_open, uint32_t id) {
    487   uint32_t new_listen_slot_id = 0;
    488   pthread_mutex_lock(&slot_lock);
    489 
    490   rfc_slot_t *srv_rs = find_rfc_slot_by_id(id);
    491   if (!srv_rs)
    492     goto out;
    493 
    494   rfc_slot_t *accept_rs = create_srv_accept_rfc_slot(srv_rs, (const bt_bdaddr_t *)p_open->rem_bda, p_open->handle, p_open->new_listen_handle);
    495   if (!accept_rs)
    496     goto out;
    497 
    498   // Start monitoring the socket.
    499   btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, srv_rs->id);
    500   btsock_thread_add_fd(pth, accept_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, accept_rs->id);
    501   send_app_connect_signal(srv_rs->fd, &accept_rs->addr, srv_rs->scn, 0, accept_rs->app_fd);
    502   accept_rs->app_fd = INVALID_FD;  // Ownership of the application fd has been transferred.
    503   new_listen_slot_id = srv_rs->id;
    504 
    505 out:;
    506   pthread_mutex_unlock(&slot_lock);
    507   return new_listen_slot_id;
    508 }
    509 
    510 static void on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN *p_open, uint32_t id) {
    511   pthread_mutex_lock(&slot_lock);
    512 
    513   rfc_slot_t *slot = find_rfc_slot_by_id(id);
    514   if (!slot)
    515     goto out;
    516 
    517   if (p_open->status != BTA_JV_SUCCESS) {
    518     cleanup_rfc_slot(slot);
    519     goto out;
    520   }
    521 
    522   slot->rfc_port_handle = BTA_JvRfcommGetPortHdl(p_open->handle);
    523   memcpy(slot->addr.address, p_open->rem_bda, 6);
    524 
    525   if (send_app_connect_signal(slot->fd, &slot->addr, slot->scn, 0, -1))
    526     slot->f.connected = true;
    527   else
    528     LOG_ERROR(LOG_TAG, "%s unable to send connect completion signal to caller.", __func__);
    529 
    530 out:;
    531   pthread_mutex_unlock(&slot_lock);
    532 }
    533 
    534 static void on_rfc_close(UNUSED_ATTR tBTA_JV_RFCOMM_CLOSE *p_close, uint32_t id) {
    535   pthread_mutex_lock(&slot_lock);
    536 
    537   // rfc_handle already closed when receiving rfcomm close event from stack.
    538   rfc_slot_t *slot = find_rfc_slot_by_id(id);
    539   if (slot)
    540     cleanup_rfc_slot(slot);
    541 
    542   pthread_mutex_unlock(&slot_lock);
    543 }
    544 
    545 static void on_rfc_write_done(UNUSED_ATTR tBTA_JV_RFCOMM_WRITE *p, uint32_t id) {
    546   int app_uid = -1;
    547   pthread_mutex_lock(&slot_lock);
    548 
    549   rfc_slot_t *slot = find_rfc_slot_by_id(id);
    550   if (slot) {
    551     app_uid = slot->app_uid;
    552     if (!slot->f.outgoing_congest) {
    553       btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
    554     }
    555   }
    556 
    557   pthread_mutex_unlock(&slot_lock);
    558 
    559   uid_set_add_tx(uid_set, app_uid, p->len);
    560 }
    561 
    562 static void on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG *p, uint32_t id) {
    563   pthread_mutex_lock(&slot_lock);
    564 
    565   rfc_slot_t *slot = find_rfc_slot_by_id(id);
    566   if (slot) {
    567     slot->f.outgoing_congest = p->cong ? 1 : 0;
    568     if (!slot->f.outgoing_congest)
    569       btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
    570   }
    571 
    572   pthread_mutex_unlock(&slot_lock);
    573 }
    574 
    575 static void *rfcomm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data) {
    576   void *new_user_data = NULL;
    577 
    578   switch (event) {
    579     case BTA_JV_RFCOMM_START_EVT:
    580       on_srv_rfc_listen_started(&p_data->rfc_start, (uintptr_t)user_data);
    581       break;
    582 
    583     case BTA_JV_RFCOMM_CL_INIT_EVT:
    584       on_cl_rfc_init(&p_data->rfc_cl_init, (uintptr_t)user_data);
    585       break;
    586 
    587     case BTA_JV_RFCOMM_OPEN_EVT:
    588       BTA_JvSetPmProfile(p_data->rfc_open.handle,BTA_JV_PM_ID_1,BTA_JV_CONN_OPEN);
    589       on_cli_rfc_connect(&p_data->rfc_open, (uintptr_t)user_data);
    590       break;
    591 
    592     case BTA_JV_RFCOMM_SRV_OPEN_EVT:
    593       BTA_JvSetPmProfile(p_data->rfc_srv_open.handle,BTA_JV_PM_ALL,BTA_JV_CONN_OPEN);
    594       new_user_data = (void *)(uintptr_t)on_srv_rfc_connect(&p_data->rfc_srv_open, (uintptr_t)user_data);
    595       break;
    596 
    597     case BTA_JV_RFCOMM_CLOSE_EVT:
    598       APPL_TRACE_DEBUG("BTA_JV_RFCOMM_CLOSE_EVT: user_data:%d", (uintptr_t)user_data);
    599       on_rfc_close(&p_data->rfc_close, (uintptr_t)user_data);
    600       break;
    601 
    602     case BTA_JV_RFCOMM_WRITE_EVT:
    603       on_rfc_write_done(&p_data->rfc_write, (uintptr_t)user_data);
    604       break;
    605 
    606     case BTA_JV_RFCOMM_CONG_EVT:
    607       on_rfc_outgoing_congest(&p_data->rfc_cong, (uintptr_t)user_data);
    608       break;
    609 
    610     case BTA_JV_RFCOMM_DATA_IND_EVT:
    611       // Unused.
    612       break;
    613 
    614     default:
    615       LOG_ERROR(LOG_TAG, "%s unhandled event %d, slot id: %zi", __func__, event, (uintptr_t)user_data);
    616       break;
    617   }
    618   return new_user_data;
    619 }
    620 
    621 static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data) {
    622   uint32_t id = PTR_TO_UINT(user_data);
    623   switch(event) {
    624     case BTA_JV_GET_SCN_EVT:
    625     {
    626       pthread_mutex_lock(&slot_lock);
    627       rfc_slot_t* rs = find_rfc_slot_by_id(id);
    628       int new_scn = p_data->scn;
    629 
    630       if(rs && (new_scn != 0))
    631       {
    632         rs->scn = new_scn;
    633         /* BTA_JvCreateRecordByUser will only create a record if a UUID is specified,
    634          * else it just allocate a RFC channel and start the RFCOMM thread - needed
    635          * for the java
    636          * layer to get a RFCOMM channel.
    637          * If uuid is null the create_sdp_record() will be called from Java when it
    638          * has received the RFCOMM and L2CAP channel numbers through the sockets.*/
    639 
    640         // Send channel ID to java layer
    641         if(!send_app_scn(rs)){
    642           //closed
    643           APPL_TRACE_DEBUG("send_app_scn() failed, close rs->id:%d", rs->id);
    644           cleanup_rfc_slot(rs);
    645         } else {
    646           if(rs->is_service_uuid_valid == true) {
    647             // We already have data for SDP record, create it (RFC-only profiles)
    648             BTA_JvCreateRecordByUser(UINT_TO_PTR(rs->id));
    649           } else {
    650             APPL_TRACE_DEBUG("is_service_uuid_valid==false - don't set SDP-record, "
    651                     "just start the RFCOMM server", rs->id);
    652             //now start the rfcomm server after sdp & channel # assigned
    653             BTA_JvRfcommStartServer(rs->security, rs->role, rs->scn, MAX_RFC_SESSION,
    654                     rfcomm_cback, UINT_TO_PTR(rs->id));
    655           }
    656         }
    657       } else if(rs) {
    658         APPL_TRACE_ERROR("jv_dm_cback: Error: allocate channel %d, slot found:%p", rs->scn, rs);
    659         cleanup_rfc_slot(rs);
    660       }
    661       pthread_mutex_unlock(&slot_lock);
    662       break;
    663     }
    664     case BTA_JV_GET_PSM_EVT:
    665     {
    666       APPL_TRACE_DEBUG("Received PSM: 0x%04x", p_data->psm);
    667       on_l2cap_psm_assigned(id, p_data->psm);
    668       break;
    669     }
    670     case BTA_JV_CREATE_RECORD_EVT: {
    671       pthread_mutex_lock(&slot_lock);
    672 
    673       rfc_slot_t *slot = find_rfc_slot_by_id(id);
    674       if (slot && create_server_sdp_record(slot)) {
    675         // Start the rfcomm server after sdp & channel # assigned.
    676         BTA_JvRfcommStartServer(slot->security, slot->role, slot->scn, MAX_RFC_SESSION, rfcomm_cback, (void *)(uintptr_t)slot->id);
    677       } else if(slot) {
    678         APPL_TRACE_ERROR("jv_dm_cback: cannot start server, slot found:%p", slot);
    679         cleanup_rfc_slot(slot);
    680       }
    681 
    682       pthread_mutex_unlock(&slot_lock);
    683       break;
    684     }
    685 
    686     case BTA_JV_DISCOVERY_COMP_EVT: {
    687       pthread_mutex_lock(&slot_lock);
    688       rfc_slot_t *slot = find_rfc_slot_by_id(id);
    689       if (p_data->disc_comp.status == BTA_JV_SUCCESS && p_data->disc_comp.scn) {
    690         if (slot && slot->f.doing_sdp_request) {
    691           // Establish the connection if we successfully looked up a channel number to connect to.
    692           if (BTA_JvRfcommConnect(slot->security, slot->role, p_data->disc_comp.scn, slot->addr.address, rfcomm_cback, (void *)(uintptr_t)slot->id) == BTA_JV_SUCCESS) {
    693             slot->scn = p_data->disc_comp.scn;
    694             slot->f.doing_sdp_request = false;
    695             if (!send_app_scn(slot))
    696               cleanup_rfc_slot(slot);
    697           } else {
    698             cleanup_rfc_slot(slot);
    699           }
    700         } else if (slot) {
    701           // TODO(sharvil): this is really a logic error and we should probably assert.
    702           LOG_ERROR(LOG_TAG, "%s SDP response returned but RFCOMM slot %d did not request SDP record.", __func__, id);
    703         }
    704       } else if (slot) {
    705         cleanup_rfc_slot(slot);
    706       }
    707 
    708       // Find the next slot that needs to perform an SDP request and service it.
    709       slot = find_rfc_slot_by_pending_sdp();
    710       if (slot) {
    711         tSDP_UUID sdp_uuid;
    712         sdp_uuid.len = 16;
    713         memcpy(sdp_uuid.uu.uuid128, slot->service_uuid, sizeof(sdp_uuid.uu.uuid128));
    714         BTA_JvStartDiscovery((uint8_t *)slot->addr.address, 1, &sdp_uuid, (void *)(uintptr_t)slot->id);
    715         slot->f.pending_sdp_request = false;
    716         slot->f.doing_sdp_request = true;
    717       }
    718 
    719       pthread_mutex_unlock(&slot_lock);
    720       break;
    721     }
    722 
    723     default:
    724       APPL_TRACE_DEBUG("unhandled event:%d, slot id:%d", event, id);
    725       break;
    726   }
    727 }
    728 
    729 typedef enum {
    730   SENT_FAILED,
    731   SENT_NONE,
    732   SENT_PARTIAL,
    733   SENT_ALL,
    734 } sent_status_t;
    735 
    736 static sent_status_t send_data_to_app(int fd, BT_HDR *p_buf) {
    737   if (p_buf->len == 0)
    738     return SENT_ALL;
    739 
    740   ssize_t sent;
    741   OSI_NO_INTR(sent = send(fd, p_buf->data + p_buf->offset, p_buf->len,
    742                           MSG_DONTWAIT));
    743 
    744   if (sent == -1) {
    745     if (errno == EAGAIN || errno == EWOULDBLOCK)
    746       return SENT_NONE;
    747     LOG_ERROR(LOG_TAG, "%s error writing RFCOMM data back to app: %s", __func__, strerror(errno));
    748     return SENT_FAILED;
    749   }
    750 
    751   if (sent == 0)
    752     return SENT_FAILED;
    753 
    754   if (sent == p_buf->len)
    755     return SENT_ALL;
    756 
    757   p_buf->offset += sent;
    758   p_buf->len -= sent;
    759   return SENT_PARTIAL;
    760 }
    761 
    762 static bool flush_incoming_que_on_wr_signal(rfc_slot_t *slot) {
    763   while (!list_is_empty(slot->incoming_queue)) {
    764     BT_HDR *p_buf = list_front(slot->incoming_queue);
    765     switch (send_data_to_app(slot->fd, p_buf)) {
    766       case SENT_NONE:
    767       case SENT_PARTIAL:
    768         //monitor the fd to get callback when app is ready to receive data
    769         btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, slot->id);
    770         return true;
    771 
    772       case SENT_ALL:
    773         list_remove(slot->incoming_queue, p_buf);
    774         break;
    775 
    776       case SENT_FAILED:
    777         list_remove(slot->incoming_queue, p_buf);
    778         return false;
    779     }
    780   }
    781 
    782   //app is ready to receive data, tell stack to start the data flow
    783   //fix me: need a jv flow control api to serialize the call in stack
    784   APPL_TRACE_DEBUG("enable data flow, rfc_handle:0x%x, rfc_port_handle:0x%x, user_id:%d",
    785       slot->rfc_handle, slot->rfc_port_handle, slot->id);
    786   extern int PORT_FlowControl_MaxCredit(uint16_t handle, bool enable);
    787   PORT_FlowControl_MaxCredit(slot->rfc_port_handle, true);
    788   return true;
    789 }
    790 
    791 void btsock_rfc_signaled(UNUSED_ATTR int fd, int flags, uint32_t user_id) {
    792   pthread_mutex_lock(&slot_lock);
    793 
    794   rfc_slot_t *slot = find_rfc_slot_by_id(user_id);
    795   if (!slot)
    796     goto out;
    797 
    798   bool need_close = false;
    799 
    800   // Data available from app, tell stack we have outgoing data.
    801   if (flags & SOCK_THREAD_FD_RD && !slot->f.server) {
    802     if (slot->f.connected) {
    803       // Make sure there's data pending in case the peer closed the socket.
    804       int size = 0;
    805       if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(slot->fd, FIONREAD, &size) == 0 && size)) {
    806         BTA_JvRfcommWrite(slot->rfc_handle, slot->id);
    807       }
    808     } else {
    809       LOG_ERROR(LOG_TAG, "%s socket signaled for read while disconnected, slot: %d, channel: %d", __func__, slot->id, slot->scn);
    810       need_close = true;
    811     }
    812   }
    813 
    814   if (flags & SOCK_THREAD_FD_WR) {
    815     // App is ready to receive more data, tell stack to enable data flow.
    816     if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) {
    817       LOG_ERROR(LOG_TAG, "%s socket signaled for write while disconnected (or write failure), slot: %d, channel: %d", __func__, slot->id, slot->scn);
    818       need_close = true;
    819     }
    820   }
    821 
    822   if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) {
    823     // Clean up if there's no data pending.
    824     int size = 0;
    825     if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size)
    826       cleanup_rfc_slot(slot);
    827   }
    828 
    829 out:;
    830   pthread_mutex_unlock(&slot_lock);
    831 }
    832 
    833 int bta_co_rfc_data_incoming(void *user_data, BT_HDR *p_buf) {
    834   int app_uid = -1;
    835   uint64_t bytes_rx = 0;
    836 
    837   pthread_mutex_lock(&slot_lock);
    838 
    839   int ret = 0;
    840   uint32_t id = (uintptr_t)user_data;
    841   rfc_slot_t *slot = find_rfc_slot_by_id(id);
    842   if (!slot)
    843     goto out;
    844 
    845   app_uid = slot->app_uid;
    846   bytes_rx = p_buf->len;
    847 
    848   if (list_is_empty(slot->incoming_queue)) {
    849     switch (send_data_to_app(slot->fd, p_buf)) {
    850       case SENT_NONE:
    851       case SENT_PARTIAL:
    852         list_append(slot->incoming_queue, p_buf);
    853         btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, slot->id);
    854         break;
    855 
    856       case SENT_ALL:
    857         osi_free(p_buf);
    858         ret = 1;  // Enable data flow.
    859         break;
    860 
    861       case SENT_FAILED:
    862         osi_free(p_buf);
    863         cleanup_rfc_slot(slot);
    864         break;
    865     }
    866   } else {
    867     list_append(slot->incoming_queue, p_buf);
    868   }
    869 
    870 out:;
    871   pthread_mutex_unlock(&slot_lock);
    872 
    873   uid_set_add_rx(uid_set, app_uid, bytes_rx);
    874 
    875   return ret;  // Return 0 to disable data flow.
    876 }
    877 
    878 int bta_co_rfc_data_outgoing_size(void *user_data, int *size) {
    879   pthread_mutex_lock(&slot_lock);
    880 
    881   uint32_t id = (uintptr_t)user_data;
    882   int ret = false;
    883   *size = 0;
    884   rfc_slot_t *slot = find_rfc_slot_by_id(id);
    885   if (!slot)
    886     goto out;
    887 
    888   if (ioctl(slot->fd, FIONREAD, size) == 0) {
    889     ret = true;
    890   } else {
    891     LOG_ERROR(LOG_TAG, "%s unable to determine bytes remaining to be read on fd %d: %s", __func__, slot->fd, strerror(errno));
    892     cleanup_rfc_slot(slot);
    893   }
    894 
    895 out:;
    896   pthread_mutex_unlock(&slot_lock);
    897   return ret;
    898 }
    899 
    900 int bta_co_rfc_data_outgoing(void *user_data, uint8_t *buf, uint16_t size) {
    901   pthread_mutex_lock(&slot_lock);
    902 
    903   uint32_t id = (uintptr_t)user_data;
    904   int ret = false;
    905   rfc_slot_t *slot = find_rfc_slot_by_id(id);
    906   if (!slot)
    907     goto out;
    908 
    909   ssize_t received;
    910   OSI_NO_INTR(received = recv(slot->fd, buf, size, 0));
    911 
    912   if(received == size) {
    913     ret = true;
    914   } else {
    915     LOG_ERROR(LOG_TAG, "%s error receiving RFCOMM data from app: %s", __func__, strerror(errno));
    916     cleanup_rfc_slot(slot);
    917   }
    918 
    919 out:;
    920   pthread_mutex_unlock(&slot_lock);
    921   return ret;
    922 }
    923