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