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