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