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