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