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