OSDN Git Service

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