• 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_listen(const char * service_name,const Uuid * service_uuid,int channel,int * sock_fd,int flags,int app_uid)268 bt_status_t btsock_rfc_listen(const char* service_name,
269                               const Uuid* service_uuid, int channel,
270                               int* sock_fd, int flags, int app_uid) {
271   CHECK(sock_fd != NULL);
272   CHECK((service_uuid != NULL) ||
273         (channel >= 1 && channel <= MAX_RFC_CHANNEL) ||
274         ((flags & BTSOCK_FLAG_NO_SDP) != 0));
275 
276   *sock_fd = INVALID_FD;
277 
278   // TODO(sharvil): not sure that this check makes sense; seems like a logic
279   // error to call
280   // functions on RFCOMM sockets before initializing the module. Probably should
281   // be an assert.
282   if (!is_init_done()) return BT_STATUS_NOT_READY;
283 
284   if ((flags & BTSOCK_FLAG_NO_SDP) == 0) {
285     if (!service_uuid || service_uuid->IsEmpty()) {
286       // Use serial port profile to listen to specified channel
287       service_uuid = &UUID_SPP;
288     } else {
289       // Check the service_uuid. overwrite the channel # if reserved
290       int reserved_channel = get_reserved_rfc_channel(*service_uuid);
291       if (reserved_channel > 0) {
292         channel = reserved_channel;
293       }
294     }
295   }
296 
297   std::unique_lock<std::recursive_mutex> lock(slot_lock);
298 
299   rfc_slot_t* slot =
300       alloc_rfc_slot(NULL, service_name, *service_uuid, channel, flags, true);
301   if (!slot) {
302     LOG_ERROR("unable to allocate RFCOMM slot");
303     return BT_STATUS_FAIL;
304   }
305   LOG_INFO("Adding listening socket service_name: %s - channel: %d",
306            service_name, channel);
307   BTA_JvGetChannelId(BTA_JV_CONN_TYPE_RFCOMM, slot->id, channel);
308   *sock_fd = slot->app_fd;  // Transfer ownership of fd to caller.
309   /*TODO:
310    * We are leaking one of the app_fd's - either the listen socket, or the
311    connection socket.
312    * WE need to close this in native, as the FD might belong to another process
313     - This is the server socket FD
314     - For accepted connections, we close the FD after passing it to JAVA.
315     - Try to simply remove the = -1 to free the FD at rs cleanup.*/
316   //        close(rs->app_fd);
317   slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
318   slot->app_uid = app_uid;
319   btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION,
320                        slot->id);
321 
322   return BT_STATUS_SUCCESS;
323 }
324 
btsock_rfc_connect(const RawAddress * bd_addr,const Uuid * service_uuid,int channel,int * sock_fd,int flags,int app_uid)325 bt_status_t btsock_rfc_connect(const RawAddress* bd_addr,
326                                const Uuid* service_uuid, int channel,
327                                int* sock_fd, int flags, int app_uid) {
328   CHECK(sock_fd != NULL);
329   CHECK((service_uuid != NULL) || (channel >= 1 && channel <= MAX_RFC_CHANNEL));
330 
331   *sock_fd = INVALID_FD;
332 
333   // TODO(sharvil): not sure that this check makes sense; seems like a logic
334   // error to call
335   // functions on RFCOMM sockets before initializing the module. Probably should
336   // be an assert.
337   if (!is_init_done()) return BT_STATUS_NOT_READY;
338 
339   std::unique_lock<std::recursive_mutex> lock(slot_lock);
340 
341   rfc_slot_t* slot =
342       alloc_rfc_slot(bd_addr, NULL, *service_uuid, channel, flags, false);
343   if (!slot) {
344     LOG_ERROR("%s unable to allocate RFCOMM slot.", __func__);
345     return BT_STATUS_FAIL;
346   }
347 
348   if (!service_uuid || service_uuid->IsEmpty()) {
349     tBTA_JV_STATUS ret =
350         BTA_JvRfcommConnect(slot->security, slot->role, slot->scn, slot->addr,
351                             rfcomm_cback, slot->id);
352     if (ret != BTA_JV_SUCCESS) {
353       LOG_ERROR("%s unable to initiate RFCOMM connection: %d", __func__, ret);
354       cleanup_rfc_slot(slot);
355       return BT_STATUS_FAIL;
356     }
357 
358     if (!send_app_scn(slot)) {
359       LOG_ERROR("%s unable to send channel number.", __func__);
360       cleanup_rfc_slot(slot);
361       return BT_STATUS_FAIL;
362     }
363   } else {
364     if (!is_requesting_sdp()) {
365       BTA_JvStartDiscovery(*bd_addr, 1, service_uuid, slot->id);
366       slot->f.pending_sdp_request = false;
367       slot->f.doing_sdp_request = true;
368     } else {
369       slot->f.pending_sdp_request = true;
370       slot->f.doing_sdp_request = false;
371     }
372   }
373 
374   *sock_fd = slot->app_fd;    // Transfer ownership of fd to caller.
375   slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
376   slot->app_uid = app_uid;
377   btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD,
378                        slot->id);
379 
380   return BT_STATUS_SUCCESS;
381 }
382 
create_server_sdp_record(rfc_slot_t * slot)383 static int create_server_sdp_record(rfc_slot_t* slot) {
384   if (slot->scn == 0) {
385     return false;
386   }
387   slot->sdp_handle =
388       add_rfc_sdp_rec(slot->service_name, slot->service_uuid, slot->scn);
389   return (slot->sdp_handle > 0);
390 }
391 
free_rfc_slot_scn(rfc_slot_t * slot)392 static void free_rfc_slot_scn(rfc_slot_t* slot) {
393   if (slot->scn <= 0) return;
394 
395   if (slot->f.server && !slot->f.closing && slot->rfc_handle) {
396     BTA_JvRfcommStopServer(slot->rfc_handle, slot->id);
397     slot->rfc_handle = 0;
398   }
399 
400   if (slot->f.server) BTM_FreeSCN(slot->scn);
401   slot->scn = 0;
402 }
403 
cleanup_rfc_slot(rfc_slot_t * slot)404 static void cleanup_rfc_slot(rfc_slot_t* slot) {
405   if (slot->fd != INVALID_FD) {
406     shutdown(slot->fd, SHUT_RDWR);
407     close(slot->fd);
408     btif_sock_connection_logger(
409         SOCKET_CONNECTION_STATE_DISCONNECTED,
410         slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
411         slot->addr);
412     log_socket_connection_state(
413         slot->addr, slot->id, BTSOCK_RFCOMM,
414         android::bluetooth::SOCKET_CONNECTION_STATE_DISCONNECTED,
415         slot->tx_bytes, slot->rx_bytes, slot->app_uid, slot->scn,
416         slot->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN
417                        : android::bluetooth::SOCKET_ROLE_CONNECTION);
418     slot->fd = INVALID_FD;
419   }
420 
421   if (slot->app_fd != INVALID_FD) {
422     close(slot->app_fd);
423     slot->app_fd = INVALID_FD;
424   }
425 
426   if (slot->sdp_handle > 0) {
427     del_rfc_sdp_rec(slot->sdp_handle);
428     slot->sdp_handle = 0;
429   }
430 
431   if (slot->rfc_handle && !slot->f.closing && !slot->f.server) {
432     BTA_JvRfcommClose(slot->rfc_handle, slot->id);
433     slot->rfc_handle = 0;
434   }
435 
436   free_rfc_slot_scn(slot);
437   list_clear(slot->incoming_queue);
438 
439   slot->rfc_port_handle = 0;
440   memset(&slot->f, 0, sizeof(slot->f));
441   slot->id = 0;
442   slot->scn_notified = false;
443   slot->tx_bytes = 0;
444   slot->rx_bytes = 0;
445 }
446 
send_app_scn(rfc_slot_t * slot)447 static bool send_app_scn(rfc_slot_t* slot) {
448   if (slot->scn_notified) {
449     // already send, just return success.
450     return true;
451   }
452   slot->scn_notified = true;
453   return sock_send_all(slot->fd, (const uint8_t*)&slot->scn,
454                        sizeof(slot->scn)) == sizeof(slot->scn);
455 }
456 
send_app_connect_signal(int fd,const RawAddress * addr,int channel,int status,int send_fd)457 static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel,
458                                     int status, int send_fd) {
459   sock_connect_signal_t cs;
460   cs.size = sizeof(cs);
461   cs.bd_addr = *addr;
462   cs.channel = channel;
463   cs.status = status;
464   cs.max_rx_packet_size = 0;  // not used for RFCOMM
465   cs.max_tx_packet_size = 0;  // not used for RFCOMM
466   if (send_fd == INVALID_FD)
467     return sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs);
468 
469   return sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) ==
470          sizeof(cs);
471 }
472 
on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT * p_init,uint32_t id)473 static void on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT* p_init, uint32_t id) {
474   std::unique_lock<std::recursive_mutex> lock(slot_lock);
475   rfc_slot_t* slot = find_rfc_slot_by_id(id);
476   if (!slot) return;
477 
478   if (p_init->status == BTA_JV_SUCCESS) {
479     slot->rfc_handle = p_init->handle;
480   } else {
481     cleanup_rfc_slot(slot);
482   }
483 }
484 
on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START * p_start,uint32_t id)485 static void on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START* p_start,
486                                       uint32_t id) {
487   std::unique_lock<std::recursive_mutex> lock(slot_lock);
488   rfc_slot_t* slot = find_rfc_slot_by_id(id);
489   if (!slot) return;
490 
491   if (p_start->status == BTA_JV_SUCCESS) {
492     slot->rfc_handle = p_start->handle;
493     btif_sock_connection_logger(
494         SOCKET_CONNECTION_STATE_LISTENING,
495         slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
496         slot->addr);
497     log_socket_connection_state(
498         slot->addr, slot->id, BTSOCK_RFCOMM,
499         android::bluetooth::SocketConnectionstateEnum::
500             SOCKET_CONNECTION_STATE_LISTENING,
501         0, 0, slot->app_uid, slot->scn,
502         slot->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN
503                        : android::bluetooth::SOCKET_ROLE_CONNECTION);
504   } else {
505     cleanup_rfc_slot(slot);
506   }
507 }
508 
on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN * p_open,uint32_t id)509 static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN* p_open,
510                                    uint32_t id) {
511   std::unique_lock<std::recursive_mutex> lock(slot_lock);
512   rfc_slot_t* accept_rs;
513   rfc_slot_t* srv_rs = find_rfc_slot_by_id(id);
514   if (!srv_rs) return 0;
515 
516   accept_rs = create_srv_accept_rfc_slot(
517       srv_rs, &p_open->rem_bda, p_open->handle, p_open->new_listen_handle);
518   if (!accept_rs) return 0;
519 
520   btif_sock_connection_logger(
521       SOCKET_CONNECTION_STATE_CONNECTED,
522       accept_rs->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
523       accept_rs->addr);
524   log_socket_connection_state(
525       accept_rs->addr, accept_rs->id, BTSOCK_RFCOMM,
526       android::bluetooth::SOCKET_CONNECTION_STATE_CONNECTED, 0, 0,
527       accept_rs->app_uid, accept_rs->scn,
528       accept_rs->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN
529                           : android::bluetooth::SOCKET_ROLE_CONNECTION);
530 
531   // Start monitoring the socket.
532   btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION,
533                        srv_rs->id);
534   btsock_thread_add_fd(pth, accept_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD,
535                        accept_rs->id);
536   send_app_connect_signal(srv_rs->fd, &accept_rs->addr, srv_rs->scn, 0,
537                           accept_rs->app_fd);
538   accept_rs->app_fd =
539       INVALID_FD;  // Ownership of the application fd has been transferred.
540   return srv_rs->id;
541 }
542 
on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN * p_open,uint32_t id)543 static void on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN* p_open, uint32_t id) {
544   std::unique_lock<std::recursive_mutex> lock(slot_lock);
545   rfc_slot_t* slot = find_rfc_slot_by_id(id);
546   if (!slot) return;
547 
548   if (p_open->status != BTA_JV_SUCCESS) {
549     cleanup_rfc_slot(slot);
550     return;
551   }
552 
553   slot->rfc_port_handle = BTA_JvRfcommGetPortHdl(p_open->handle);
554   slot->addr = p_open->rem_bda;
555 
556   btif_sock_connection_logger(
557       SOCKET_CONNECTION_STATE_CONNECTED,
558       slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, slot->addr);
559   log_socket_connection_state(
560       slot->addr, slot->id, BTSOCK_RFCOMM,
561       android::bluetooth::SOCKET_CONNECTION_STATE_CONNECTED, 0, 0,
562       slot->app_uid, slot->scn,
563       slot->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN
564                      : android::bluetooth::SOCKET_ROLE_CONNECTION);
565 
566   if (send_app_connect_signal(slot->fd, &slot->addr, slot->scn, 0, -1)) {
567     slot->f.connected = true;
568   } else {
569     LOG_ERROR("%s unable to send connect completion signal to caller.",
570               __func__);
571   }
572 }
573 
on_rfc_close(UNUSED_ATTR tBTA_JV_RFCOMM_CLOSE * p_close,uint32_t id)574 static void on_rfc_close(UNUSED_ATTR tBTA_JV_RFCOMM_CLOSE* p_close,
575                          uint32_t id) {
576   std::unique_lock<std::recursive_mutex> lock(slot_lock);
577 
578   // rfc_handle already closed when receiving rfcomm close event from stack.
579   rfc_slot_t* slot = find_rfc_slot_by_id(id);
580   if (slot) {
581     log_socket_connection_state(
582         slot->addr, slot->id, BTSOCK_RFCOMM,
583         android::bluetooth::SOCKET_CONNECTION_STATE_DISCONNECTING, 0, 0,
584         slot->app_uid, slot->scn,
585         slot->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN
586                        : android::bluetooth::SOCKET_ROLE_CONNECTION);
587     cleanup_rfc_slot(slot);
588   }
589 }
590 
on_rfc_write_done(tBTA_JV_RFCOMM_WRITE * p,uint32_t id)591 static void on_rfc_write_done(tBTA_JV_RFCOMM_WRITE* p, uint32_t id) {
592   if (p->status != BTA_JV_SUCCESS) {
593     LOG_ERROR("%s error writing to RFCOMM socket with slot %u.", __func__,
594               p->req_id);
595     return;
596   }
597 
598   int app_uid = -1;
599   std::unique_lock<std::recursive_mutex> lock(slot_lock);
600 
601   rfc_slot_t* slot = find_rfc_slot_by_id(id);
602   if (slot) {
603     app_uid = slot->app_uid;
604     if (!slot->f.outgoing_congest) {
605       btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD,
606                            slot->id);
607     }
608     slot->tx_bytes += p->len;
609   }
610 
611   uid_set_add_tx(uid_set, app_uid, p->len);
612 }
613 
on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG * p,uint32_t id)614 static void on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG* p, uint32_t id) {
615   std::unique_lock<std::recursive_mutex> lock(slot_lock);
616 
617   rfc_slot_t* slot = find_rfc_slot_by_id(id);
618   if (slot) {
619     slot->f.outgoing_congest = p->cong ? 1 : 0;
620     if (!slot->f.outgoing_congest)
621       btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD,
622                            slot->id);
623   }
624 }
625 
rfcomm_cback(tBTA_JV_EVT event,tBTA_JV * p_data,uint32_t rfcomm_slot_id)626 static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data,
627                              uint32_t rfcomm_slot_id) {
628   uint32_t id = 0;
629 
630   switch (event) {
631     case BTA_JV_RFCOMM_START_EVT:
632       on_srv_rfc_listen_started(&p_data->rfc_start, rfcomm_slot_id);
633       break;
634 
635     case BTA_JV_RFCOMM_CL_INIT_EVT:
636       on_cl_rfc_init(&p_data->rfc_cl_init, rfcomm_slot_id);
637       break;
638 
639     case BTA_JV_RFCOMM_OPEN_EVT:
640       BTA_JvSetPmProfile(p_data->rfc_open.handle, BTA_JV_PM_ID_1,
641                          BTA_JV_CONN_OPEN);
642       on_cli_rfc_connect(&p_data->rfc_open, rfcomm_slot_id);
643       break;
644 
645     case BTA_JV_RFCOMM_SRV_OPEN_EVT:
646       BTA_JvSetPmProfile(p_data->rfc_srv_open.handle, BTA_JV_PM_ALL,
647                          BTA_JV_CONN_OPEN);
648       id = on_srv_rfc_connect(&p_data->rfc_srv_open, rfcomm_slot_id);
649       break;
650 
651     case BTA_JV_RFCOMM_CLOSE_EVT:
652       APPL_TRACE_DEBUG("BTA_JV_RFCOMM_CLOSE_EVT: rfcomm_slot_id:%d",
653                        rfcomm_slot_id);
654       on_rfc_close(&p_data->rfc_close, rfcomm_slot_id);
655       break;
656 
657     case BTA_JV_RFCOMM_WRITE_EVT:
658       on_rfc_write_done(&p_data->rfc_write, rfcomm_slot_id);
659       break;
660 
661     case BTA_JV_RFCOMM_CONG_EVT:
662       on_rfc_outgoing_congest(&p_data->rfc_cong, rfcomm_slot_id);
663       break;
664 
665     case BTA_JV_RFCOMM_DATA_IND_EVT:
666       // Unused.
667       break;
668 
669     default:
670       LOG_ERROR("%s unhandled event %d, slot id: %u", __func__, event,
671                 rfcomm_slot_id);
672       break;
673   }
674   return id;
675 }
676 
jv_dm_cback(tBTA_JV_EVT event,tBTA_JV * p_data,uint32_t id)677 static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) {
678   switch (event) {
679     case BTA_JV_GET_SCN_EVT: {
680       std::unique_lock<std::recursive_mutex> lock(slot_lock);
681       rfc_slot_t* rs = find_rfc_slot_by_id(id);
682       int new_scn = p_data->scn;
683 
684       if (rs && (new_scn != 0)) {
685         rs->scn = new_scn;
686         /* BTA_JvCreateRecordByUser will only create a record if a UUID is
687          * specified,
688          * else it just allocate a RFC channel and start the RFCOMM thread -
689          * needed
690          * for the java
691          * layer to get a RFCOMM channel.
692          * If uuid is null the create_sdp_record() will be called from Java when
693          * it
694          * has received the RFCOMM and L2CAP channel numbers through the
695          * sockets.*/
696 
697         // Send channel ID to java layer
698         if (!send_app_scn(rs)) {
699           // closed
700           APPL_TRACE_DEBUG("send_app_scn() failed, close rs->id:%d", rs->id);
701           cleanup_rfc_slot(rs);
702         } else {
703           if (rs->is_service_uuid_valid) {
704             // We already have data for SDP record, create it (RFC-only
705             // profiles)
706             BTA_JvCreateRecordByUser(rs->id);
707           } else {
708             APPL_TRACE_DEBUG(
709                 "is_service_uuid_valid==false - don't set SDP-record, "
710                 "just start the RFCOMM server",
711                 rs->id);
712             // now start the rfcomm server after sdp & channel # assigned
713             BTA_JvRfcommStartServer(rs->security, rs->role, rs->scn,
714                                     MAX_RFC_SESSION, rfcomm_cback, rs->id);
715           }
716         }
717       } else if (rs) {
718         APPL_TRACE_ERROR(
719             "jv_dm_cback: Error: allocate channel %d, slot found:%p", rs->scn,
720             rs);
721         cleanup_rfc_slot(rs);
722       }
723       break;
724     }
725     case BTA_JV_GET_PSM_EVT: {
726       APPL_TRACE_DEBUG("Received PSM: 0x%04x", p_data->psm);
727       on_l2cap_psm_assigned(id, p_data->psm);
728       break;
729     }
730     case BTA_JV_CREATE_RECORD_EVT: {
731       std::unique_lock<std::recursive_mutex> lock(slot_lock);
732       rfc_slot_t* slot = find_rfc_slot_by_id(id);
733 
734       if (slot && create_server_sdp_record(slot)) {
735         // Start the rfcomm server after sdp & channel # assigned.
736         BTA_JvRfcommStartServer(slot->security, slot->role, slot->scn,
737                                 MAX_RFC_SESSION, rfcomm_cback, slot->id);
738       } else if (slot) {
739         APPL_TRACE_ERROR("jv_dm_cback: cannot start server, slot found:%p",
740                          slot);
741         cleanup_rfc_slot(slot);
742       }
743       break;
744     }
745 
746     case BTA_JV_DISCOVERY_COMP_EVT: {
747       std::unique_lock<std::recursive_mutex> lock(slot_lock);
748       rfc_slot_t* slot = find_rfc_slot_by_id(id);
749       if (p_data->disc_comp.status == BTA_JV_SUCCESS && p_data->disc_comp.scn) {
750         if (slot && slot->f.doing_sdp_request) {
751           // Establish the connection if we successfully looked up a channel
752           // number to connect to.
753           if (BTA_JvRfcommConnect(slot->security, slot->role,
754                                   p_data->disc_comp.scn, slot->addr,
755                                   rfcomm_cback, slot->id) == BTA_JV_SUCCESS) {
756             slot->scn = p_data->disc_comp.scn;
757             slot->f.doing_sdp_request = false;
758             if (!send_app_scn(slot)) cleanup_rfc_slot(slot);
759           } else {
760             cleanup_rfc_slot(slot);
761           }
762         } else if (slot) {
763           // TODO(sharvil): this is really a logic error and we should probably
764           // assert.
765           LOG_ERROR(
766               "%s SDP response returned but RFCOMM slot %d did not "
767               "request SDP record.",
768               __func__, id);
769         }
770       } else if (slot) {
771         cleanup_rfc_slot(slot);
772       }
773 
774       // Find the next slot that needs to perform an SDP request and service it.
775       slot = find_rfc_slot_by_pending_sdp();
776       if (slot) {
777         BTA_JvStartDiscovery(slot->addr, 1, &slot->service_uuid, slot->id);
778         slot->f.pending_sdp_request = false;
779         slot->f.doing_sdp_request = true;
780       }
781       break;
782     }
783 
784     default:
785       APPL_TRACE_DEBUG("unhandled event:%d, slot id:%d", event, id);
786       break;
787   }
788 }
789 
790 typedef enum {
791   SENT_FAILED,
792   SENT_NONE,
793   SENT_PARTIAL,
794   SENT_ALL,
795 } sent_status_t;
796 
send_data_to_app(int fd,BT_HDR * p_buf)797 static sent_status_t send_data_to_app(int fd, BT_HDR* p_buf) {
798   if (p_buf->len == 0) return SENT_ALL;
799 
800   ssize_t sent;
801   OSI_NO_INTR(
802       sent = send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT));
803 
804   if (sent == -1) {
805     if (errno == EAGAIN || errno == EWOULDBLOCK) return SENT_NONE;
806     LOG_ERROR("%s error writing RFCOMM data back to app: %s", __func__,
807               strerror(errno));
808     return SENT_FAILED;
809   }
810 
811   if (sent == 0) return SENT_FAILED;
812 
813   if (sent == p_buf->len) return SENT_ALL;
814 
815   p_buf->offset += sent;
816   p_buf->len -= sent;
817   return SENT_PARTIAL;
818 }
819 
flush_incoming_que_on_wr_signal(rfc_slot_t * slot)820 static bool flush_incoming_que_on_wr_signal(rfc_slot_t* slot) {
821   while (!list_is_empty(slot->incoming_queue)) {
822     BT_HDR* p_buf = (BT_HDR*)list_front(slot->incoming_queue);
823     switch (send_data_to_app(slot->fd, p_buf)) {
824       case SENT_NONE:
825       case SENT_PARTIAL:
826         // monitor the fd to get callback when app is ready to receive data
827         btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR,
828                              slot->id);
829         return true;
830 
831       case SENT_ALL:
832         list_remove(slot->incoming_queue, p_buf);
833         break;
834 
835       case SENT_FAILED:
836         list_remove(slot->incoming_queue, p_buf);
837         return false;
838     }
839   }
840 
841   // app is ready to receive data, tell stack to start the data flow
842   // fix me: need a jv flow control api to serialize the call in stack
843   APPL_TRACE_DEBUG(
844       "enable data flow, rfc_handle:0x%x, rfc_port_handle:0x%x, user_id:%d",
845       slot->rfc_handle, slot->rfc_port_handle, slot->id);
846   PORT_FlowControl_MaxCredit(slot->rfc_port_handle, true);
847   return true;
848 }
849 
btsock_rfc_signaled(UNUSED_ATTR int fd,int flags,uint32_t user_id)850 void btsock_rfc_signaled(UNUSED_ATTR int fd, int flags, uint32_t user_id) {
851   bool need_close = false;
852   std::unique_lock<std::recursive_mutex> lock(slot_lock);
853   rfc_slot_t* slot = find_rfc_slot_by_id(user_id);
854   if (!slot) return;
855 
856   // Data available from app, tell stack we have outgoing data.
857   if (flags & SOCK_THREAD_FD_RD && !slot->f.server) {
858     if (slot->f.connected) {
859       // Make sure there's data pending in case the peer closed the socket.
860       int size = 0;
861       if (!(flags & SOCK_THREAD_FD_EXCEPTION) ||
862           (ioctl(slot->fd, FIONREAD, &size) == 0 && size)) {
863         BTA_JvRfcommWrite(slot->rfc_handle, slot->id);
864       }
865     } else {
866       LOG_ERROR(
867           "%s socket signaled for read while disconnected, slot: %d, "
868           "channel: %d",
869           __func__, slot->id, slot->scn);
870       need_close = true;
871     }
872   }
873 
874   if (flags & SOCK_THREAD_FD_WR) {
875     // App is ready to receive more data, tell stack to enable data flow.
876     if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) {
877       LOG_ERROR(
878           "%s socket signaled for write while disconnected (or write "
879           "failure), slot: %d, channel: %d",
880           __func__, slot->id, slot->scn);
881       need_close = true;
882     }
883   }
884 
885   if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) {
886     // Clean up if there's no data pending.
887     int size = 0;
888     if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size)
889       cleanup_rfc_slot(slot);
890   }
891 }
892 
bta_co_rfc_data_incoming(uint32_t id,BT_HDR * p_buf)893 int bta_co_rfc_data_incoming(uint32_t id, BT_HDR* p_buf) {
894   int app_uid = -1;
895   uint64_t bytes_rx = 0;
896   int ret = 0;
897   std::unique_lock<std::recursive_mutex> lock(slot_lock);
898   rfc_slot_t* slot = find_rfc_slot_by_id(id);
899   if (!slot) return 0;
900 
901   app_uid = slot->app_uid;
902   bytes_rx = p_buf->len;
903 
904   if (list_is_empty(slot->incoming_queue)) {
905     switch (send_data_to_app(slot->fd, p_buf)) {
906       case SENT_NONE:
907       case SENT_PARTIAL:
908         list_append(slot->incoming_queue, p_buf);
909         btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR,
910                              slot->id);
911         break;
912 
913       case SENT_ALL:
914         osi_free(p_buf);
915         ret = 1;  // Enable data flow.
916         break;
917 
918       case SENT_FAILED:
919         osi_free(p_buf);
920         cleanup_rfc_slot(slot);
921         break;
922     }
923   } else {
924     list_append(slot->incoming_queue, p_buf);
925   }
926 
927   slot->rx_bytes += bytes_rx;
928   uid_set_add_rx(uid_set, app_uid, bytes_rx);
929 
930   return ret;  // Return 0 to disable data flow.
931 }
932 
bta_co_rfc_data_outgoing_size(uint32_t id,int * size)933 int bta_co_rfc_data_outgoing_size(uint32_t id, int* size) {
934   *size = 0;
935   std::unique_lock<std::recursive_mutex> lock(slot_lock);
936   rfc_slot_t* slot = find_rfc_slot_by_id(id);
937   if (!slot) return false;
938 
939   if (ioctl(slot->fd, FIONREAD, size) != 0) {
940     LOG_ERROR("%s unable to determine bytes remaining to be read on fd %d: %s",
941               __func__, slot->fd, strerror(errno));
942     cleanup_rfc_slot(slot);
943     return false;
944   }
945 
946   return true;
947 }
948 
bta_co_rfc_data_outgoing(uint32_t id,uint8_t * buf,uint16_t size)949 int bta_co_rfc_data_outgoing(uint32_t id, uint8_t* buf, uint16_t size) {
950   std::unique_lock<std::recursive_mutex> lock(slot_lock);
951   rfc_slot_t* slot = find_rfc_slot_by_id(id);
952   if (!slot) return false;
953 
954   ssize_t received;
955   OSI_NO_INTR(received = recv(slot->fd, buf, size, 0));
956 
957   if (received != size) {
958     LOG_ERROR("%s error receiving RFCOMM data from app: %s", __func__,
959               strerror(errno));
960     cleanup_rfc_slot(slot);
961     return false;
962   }
963 
964   return true;
965 }
966