btif_sock_rfc.c revision 694988f6aadc9ff9611c595a9863661c85da2e0f
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/************************************************************************************
20 *
21 *  Filename:      btif_sock_rfc.c
22 *
23 *  Description:   Handsfree Profile Bluetooth Interface
24 *
25 ***********************************************************************************/
26#include <assert.h>
27#include <hardware/bluetooth.h>
28#include <hardware/bt_sock.h>
29#include <sys/types.h>
30#include <sys/socket.h>
31#include <errno.h>
32#include <sys/ioctl.h>
33
34#define LOG_TAG "BTIF_SOCK"
35#include "btif_common.h"
36#include "btif_util.h"
37
38#include "bd.h"
39
40#include "bta_api.h"
41#include "btif_sock_thread.h"
42#include "btif_sock_sdp.h"
43#include "btif_sock_util.h"
44
45#include "bt_target.h"
46#include "gki.h"
47#include "hcimsgs.h"
48#include "sdp_api.h"
49#include "btu.h"
50#include "btm_api.h"
51#include "btm_int.h"
52#include "bta_jv_api.h"
53#include "bta_jv_co.h"
54#include "port_api.h"
55#include "list.h"
56
57#include <cutils/log.h>
58#include <hardware/bluetooth.h>
59#define asrt(s) if(!(s)) APPL_TRACE_ERROR("## %s assert %s failed at line:%d ##",__FUNCTION__, #s, __LINE__)
60
61extern void uuid_to_string(bt_uuid_t *p_uuid, char *str);
62static inline void logu(const char* title, const uint8_t * p_uuid)
63{
64    char uuids[128];
65    uuid_to_string((bt_uuid_t*)p_uuid, uuids);
66    ALOGD("%s: %s", title, uuids);
67}
68
69
70
71#define MAX_RFC_CHANNEL 30
72#define MAX_RFC_SESSION BTA_JV_MAX_RFC_SR_SESSION //3 by default
73typedef struct {
74    int outgoing_congest : 1;
75    int pending_sdp_request : 1;
76    int doing_sdp_request : 1;
77    int server : 1;
78    int connected : 1;
79    int closing : 1;
80} flags_t;
81
82typedef struct {
83  flags_t f;
84  uint32_t id;
85  int security;
86  int scn;
87  bt_bdaddr_t addr;
88  uint8_t service_uuid[16];
89  char service_name[256];
90  int fd, app_fd;
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
100static rfc_slot_t rfc_slots[MAX_RFC_CHANNEL];
101static uint32_t rfc_slot_id;
102static volatile int pth = -1; //poll thread handle
103static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data);
104static void cleanup_rfc_slot(rfc_slot_t* rs);
105static void *rfcomm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data);
106static inline BOOLEAN send_app_scn(rfc_slot_t* rs);
107static pthread_mutex_t slot_lock;
108#define is_init_done() (pth != -1)
109static inline void clear_slot_flag(flags_t* f)
110{
111    memset(f, 0, sizeof(*f));
112}
113
114static inline void bd_copy(UINT8* dest, UINT8* src, BOOLEAN swap)
115{
116    if (swap)
117    {
118        int i;
119        for (i =0; i < 6 ;i++)
120            dest[i]= src[5-i];
121    }
122    else memcpy(dest, src, 6);
123}
124static void init_rfc_slots()
125{
126    int i;
127    memset(rfc_slots, 0, sizeof(rfc_slot_t)*MAX_RFC_CHANNEL);
128    for(i = 0; i < MAX_RFC_CHANNEL; i++)
129    {
130        rfc_slots[i].scn = -1;
131        rfc_slots[i].sdp_handle = 0;
132        rfc_slots[i].fd = rfc_slots[i].app_fd = -1;
133        rfc_slots[i].incoming_queue = list_new(GKI_freebuf);
134        assert(rfc_slots[i].incoming_queue != NULL);
135    }
136    BTA_JvEnable(jv_dm_cback);
137    init_slot_lock(&slot_lock);
138}
139bt_status_t btsock_rfc_init(int poll_thread_handle)
140{
141    pth = poll_thread_handle;
142    init_rfc_slots();
143    return BT_STATUS_SUCCESS;
144}
145void btsock_rfc_cleanup()
146{
147    int curr_pth = pth;
148    pth = -1;
149    btsock_thread_exit(curr_pth);
150    lock_slot(&slot_lock);
151    int i;
152    for(i = 0; i < MAX_RFC_CHANNEL; i++)
153    {
154        if(rfc_slots[i].id) {
155            cleanup_rfc_slot(&rfc_slots[i]);
156            list_free(rfc_slots[i].incoming_queue);
157        }
158    }
159    unlock_slot(&slot_lock);
160}
161static inline rfc_slot_t* find_free_slot()
162{
163    int i;
164    for(i = 0; i < MAX_RFC_CHANNEL; i++)
165    {
166        if(rfc_slots[i].fd == -1)
167        {
168             return &rfc_slots[i];
169        }
170    }
171    return NULL;
172}
173static inline rfc_slot_t* find_rfc_slot_by_id(uint32_t id)
174{
175    int i;
176    if(id)
177    {
178        for(i = 0; i < MAX_RFC_CHANNEL; i++)
179        {
180            if(rfc_slots[i].id == id)
181            {
182                return &rfc_slots[i];
183            }
184        }
185    }
186    APPL_TRACE_WARNING("invalid rfc slot id: %d", id);
187    return NULL;
188}
189static inline rfc_slot_t* find_rfc_slot_by_pending_sdp()
190{
191    uint32_t min_id = (uint32_t)-1;
192    int slot = -1;
193    int i;
194    for(i = 0; i < MAX_RFC_CHANNEL; i++)
195    {
196        if(rfc_slots[i].id && rfc_slots[i].f.pending_sdp_request)
197        {
198            if(rfc_slots[i].id < min_id)
199            {
200                min_id = rfc_slots[i].id;
201                slot = i;
202            }
203        }
204    }
205    if(0<= slot && slot < MAX_RFC_CHANNEL)
206        return &rfc_slots[slot];
207    return NULL;
208}
209static inline rfc_slot_t* find_rfc_slot_requesting_sdp()
210{
211    int i;
212    for(i = 0; i < MAX_RFC_CHANNEL; i++)
213    {
214        if(rfc_slots[i].id && rfc_slots[i].f.doing_sdp_request)
215                return &rfc_slots[i];
216    }
217    APPL_TRACE_DEBUG("can not find any slot is requesting sdp");
218    return NULL;
219}
220
221static inline rfc_slot_t* find_rfc_slot_by_fd(int fd)
222{
223    int i;
224    if(fd >= 0)
225    {
226        for(i = 0; i < MAX_RFC_CHANNEL; i++)
227        {
228            if(rfc_slots[i].fd == fd)
229            {
230                if(rfc_slots[i].id)
231                    return &rfc_slots[i];
232                else
233                {
234                    APPL_TRACE_ERROR("invalid rfc slot id, cannot be 0");
235                    break;
236                }
237            }
238        }
239    }
240    return NULL;
241}
242static rfc_slot_t* alloc_rfc_slot(const bt_bdaddr_t *addr, const char* name, const uint8_t* uuid, int channel, int flags, BOOLEAN server)
243{
244    int security = 0;
245    if(flags & BTSOCK_FLAG_ENCRYPT)
246        security |= server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
247    if(flags & BTSOCK_FLAG_AUTH)
248        security |= server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
249
250    rfc_slot_t* rs = find_free_slot();
251    if(rs)
252    {
253        int fds[2] = {-1, -1};
254        if(socketpair(AF_LOCAL, SOCK_STREAM, 0, fds))
255        {
256            APPL_TRACE_ERROR("socketpair failed, errno:%d", errno);
257            return NULL;
258        }
259        rs->fd = fds[0];
260        rs->app_fd = fds[1];
261        rs->security = security;
262        rs->scn = channel;
263        if(uuid)
264            memcpy(rs->service_uuid, uuid, sizeof(rs->service_uuid));
265        else memset(rs->service_uuid, 0, sizeof(rs->service_uuid));
266        if(name && *name)
267            strncpy(rs->service_name, name, sizeof(rs->service_name) -1);
268        if(addr)
269            rs->addr = *addr;
270        ++rfc_slot_id;
271        if(rfc_slot_id == 0)
272            rfc_slot_id = 1; //skip 0 when wrapped
273        rs->id = rfc_slot_id;
274        rs->f.server = server;
275    }
276    return rs;
277}
278// rfc_slot_t* accept_rs = create_srv_accept_rfc_slot(srv_rs, p_open->rem_bda,p_opne->handle,  p_open->new_listen_handle);
279static inline rfc_slot_t* create_srv_accept_rfc_slot(rfc_slot_t* srv_rs, const bt_bdaddr_t* addr,
280                                        int open_handle, int new_listen_handle)
281{
282    rfc_slot_t *accept_rs = alloc_rfc_slot(addr, srv_rs->service_name, srv_rs->service_uuid, srv_rs->scn, 0, FALSE);
283    if( accept_rs)
284    {
285        clear_slot_flag(&accept_rs->f);
286        accept_rs->f.server = FALSE;
287        accept_rs->f.connected = TRUE;
288        accept_rs->security = srv_rs->security;
289        accept_rs->mtu = srv_rs->mtu;
290        accept_rs->role = srv_rs->role;
291        accept_rs->rfc_handle = open_handle;
292        accept_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(open_handle);
293        //now update listen rfc_handle of server slot
294        srv_rs->rfc_handle = new_listen_handle;
295        srv_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(new_listen_handle);
296        BTIF_TRACE_DEBUG("create_srv_accept__rfc_slot(open_handle: 0x%x, new_listen_handle:"
297                "0x%x) accept_rs->rfc_handle:0x%x, srv_rs_listen->rfc_handle:0x%x"
298                ,open_handle, new_listen_handle, accept_rs->rfc_port_handle, srv_rs->rfc_port_handle);
299        asrt(accept_rs->rfc_port_handle != srv_rs->rfc_port_handle);
300        //now swap the slot id
301        uint32_t new_listen_id = accept_rs->id;
302        accept_rs->id = srv_rs->id;
303        srv_rs->id = new_listen_id;
304
305        return accept_rs;
306    }
307    else
308    {
309        APPL_TRACE_ERROR(" accept_rs is NULL %s", __FUNCTION__);
310        return NULL;
311    }
312}
313bt_status_t btsock_rfc_listen(const char* service_name, const uint8_t* service_uuid, int channel,
314                            int* sock_fd, int flags)
315{
316
317    APPL_TRACE_DEBUG("btsock_rfc_listen, service_name:%s", service_name);
318    if(sock_fd == NULL || (service_uuid == NULL && (channel < 1 || channel > 30)))
319    {
320        APPL_TRACE_ERROR("invalid rfc channel:%d or sock_fd:%p, uuid:%p", channel, sock_fd, service_uuid);
321        return BT_STATUS_PARM_INVALID;
322    }
323    *sock_fd = -1;
324    if(!is_init_done())
325        return BT_STATUS_NOT_READY;
326    if(is_uuid_empty(service_uuid))
327        service_uuid = UUID_SPP; //use serial port profile to listen to specified channel
328    else
329    {
330        //Check the service_uuid. overwrite the channel # if reserved
331        int reserved_channel = get_reserved_rfc_channel(service_uuid);
332        if(reserved_channel > 0)
333        {
334            channel = reserved_channel;
335        }
336    }
337    int status = BT_STATUS_FAIL;
338    lock_slot(&slot_lock);
339    rfc_slot_t* rs = alloc_rfc_slot(NULL, service_name, service_uuid, channel, flags, TRUE);
340    if(rs)
341    {
342        APPL_TRACE_DEBUG("BTA_JvCreateRecordByUser:%s", service_name);
343        BTA_JvCreateRecordByUser((void *)(intptr_t)rs->id);
344        *sock_fd = rs->app_fd;
345        rs->app_fd = -1; //the fd ownership is transferred to app
346        status = BT_STATUS_SUCCESS;
347        btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, rs->id);
348    }
349    unlock_slot(&slot_lock);
350    return status;
351}
352bt_status_t btsock_rfc_connect(const bt_bdaddr_t *bd_addr, const uint8_t* service_uuid,
353        int channel, int* sock_fd, int flags)
354{
355    if(sock_fd == NULL || (service_uuid == NULL && (channel < 1 || channel > 30)))
356    {
357        APPL_TRACE_ERROR("invalid rfc channel:%d or sock_fd:%p, uuid:%p", channel, sock_fd,
358                          service_uuid);
359        return BT_STATUS_PARM_INVALID;
360    }
361    *sock_fd = -1;
362    if(!is_init_done())
363        return BT_STATUS_NOT_READY;
364    int status = BT_STATUS_FAIL;
365    lock_slot(&slot_lock);
366    rfc_slot_t* rs = alloc_rfc_slot(bd_addr, NULL, service_uuid, channel, flags, FALSE);
367    if(rs)
368    {
369        if(is_uuid_empty(service_uuid))
370        {
371            APPL_TRACE_DEBUG("connecting to rfcomm channel:%d without service discovery", channel);
372            if(BTA_JvRfcommConnect(rs->security, rs->role, rs->scn, rs->addr.address,
373                        rfcomm_cback, (void*)(intptr_t)rs->id) == BTA_JV_SUCCESS)
374            {
375                if(send_app_scn(rs))
376                {
377                    btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM,
378                                                        SOCK_THREAD_FD_RD, rs->id);
379                    *sock_fd = rs->app_fd;
380                    rs->app_fd = -1; //the fd ownership is transferred to app
381                    status = BT_STATUS_SUCCESS;
382                }
383                else cleanup_rfc_slot(rs);
384            }
385            else cleanup_rfc_slot(rs);
386        }
387        else
388        {
389            tSDP_UUID sdp_uuid;
390            sdp_uuid.len = 16;
391            memcpy(sdp_uuid.uu.uuid128, service_uuid, sizeof(sdp_uuid.uu.uuid128));
392            logu("service_uuid", service_uuid);
393            *sock_fd = rs->app_fd;
394            rs->app_fd = -1; //the fd ownership is transferred to app
395            status = BT_STATUS_SUCCESS;
396            rfc_slot_t* rs_doing_sdp = find_rfc_slot_requesting_sdp();
397            if(rs_doing_sdp == NULL)
398            {
399                BTA_JvStartDiscovery((UINT8*)bd_addr->address, 1, &sdp_uuid, (void*)(intptr_t)rs->id);
400                rs->f.pending_sdp_request = FALSE;
401                rs->f.doing_sdp_request = TRUE;
402            }
403            else
404            {
405                rs->f.pending_sdp_request = TRUE;
406                rs->f.doing_sdp_request = FALSE;
407            }
408            btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, rs->id);
409        }
410    }
411    unlock_slot(&slot_lock);
412    return status;
413}
414
415static int create_server_sdp_record(rfc_slot_t* rs)
416{
417    int scn = rs->scn;
418    if(rs->scn > 0)
419    {
420        if(BTM_TryAllocateSCN(rs->scn) == FALSE)
421        {
422            APPL_TRACE_ERROR("rfc channel:%d already in use", scn);
423            return FALSE;
424        }
425    }
426    else if((rs->scn = BTM_AllocateSCN()) == 0)
427    {
428        APPL_TRACE_ERROR("run out of rfc channels");
429        return FALSE;
430    }
431    if((rs->sdp_handle = add_rfc_sdp_rec(rs->service_name, rs->service_uuid, rs->scn)) <= 0)
432    {
433        return FALSE;
434    }
435    return TRUE;
436}
437const char * jv_evt[] = {
438    "BTA_JV_ENABLE_EVT",
439    "BTA_JV_SET_DISCOVER_EVT",
440    "BTA_JV_LOCAL_ADDR_EVT",
441    "BTA_JV_LOCAL_NAME_EVT",
442    "BTA_JV_REMOTE_NAME_EVT",
443    "BTA_JV_SET_ENCRYPTION_EVT",
444    "BTA_JV_GET_SCN_EVT",
445    "BTA_JV_GET_PSM_EVT",
446    "BTA_JV_DISCOVERY_COMP_EVT",
447    "BTA_JV_SERVICES_LEN_EVT",
448    "BTA_JV_SERVICE_SEL_EVT",
449    "BTA_JV_CREATE_RECORD_EVT",
450    "BTA_JV_UPDATE_RECORD_EVT",
451    "BTA_JV_ADD_ATTR_EVT",
452    "BTA_JV_DELETE_ATTR_EVT",
453    "BTA_JV_CANCEL_DISCVRY_EVT",
454
455    "BTA_JV_L2CAP_OPEN_EVT",
456    "BTA_JV_L2CAP_CLOSE_EVT",
457    "BTA_JV_L2CAP_START_EVT",
458    "BTA_JV_L2CAP_CL_INIT_EVT",
459    "BTA_JV_L2CAP_DATA_IND_EVT",
460    "BTA_JV_L2CAP_CONG_EVT",
461    "BTA_JV_L2CAP_READ_EVT",
462    "BTA_JV_L2CAP_RECEIVE_EVT",
463    "BTA_JV_L2CAP_WRITE_EVT",
464
465    "BTA_JV_RFCOMM_OPEN_EVT",
466    "BTA_JV_RFCOMM_CLOSE_EVT",
467    "BTA_JV_RFCOMM_START_EVT",
468    "BTA_JV_RFCOMM_CL_INIT_EVT",
469    "BTA_JV_RFCOMM_DATA_IND_EVT",
470    "BTA_JV_RFCOMM_CONG_EVT",
471    "BTA_JV_RFCOMM_READ_EVT",
472    "BTA_JV_RFCOMM_WRITE_EVT",
473    "BTA_JV_RFCOMM_SRV_OPEN_EVT", //  33 /* open status of Server RFCOMM connection */
474    "BTA_JV_MAX_EVT"
475};
476static inline void free_rfc_slot_scn(rfc_slot_t* rs)
477{
478    if(rs->scn > 0)
479    {
480        if(rs->f.server && !rs->f.closing && rs->rfc_handle)
481        {
482            BTA_JvRfcommStopServer(rs->rfc_handle, (void*)(uintptr_t)rs->id);
483            rs->rfc_handle = 0;
484        }
485        if(rs->f.server)
486            BTM_FreeSCN(rs->scn);
487        rs->scn = 0;
488    }
489}
490static void cleanup_rfc_slot(rfc_slot_t* rs)
491{
492    APPL_TRACE_DEBUG("cleanup slot:%d, fd:%d, scn:%d, sdp_handle:0x%x", rs->id, rs->fd, rs->scn, rs->sdp_handle);
493    if(rs->fd != -1)
494    {
495        shutdown(rs->fd, 2);
496        close(rs->fd);
497        rs->fd = -1;
498    }
499    if(rs->app_fd != -1)
500    {
501        close(rs->app_fd);
502        rs->app_fd = -1;
503    }
504    if(rs->sdp_handle > 0)
505    {
506        del_rfc_sdp_rec(rs->sdp_handle);
507        rs->sdp_handle = 0;
508    }
509    if(rs->rfc_handle && !rs->f.closing && !rs->f.server)
510    {
511        APPL_TRACE_DEBUG("closing rfcomm connection, rfc_handle:0x%x", rs->rfc_handle);
512        BTA_JvRfcommClose(rs->rfc_handle, (void*)(uintptr_t)rs->id);
513        rs->rfc_handle = 0;
514    }
515    free_rfc_slot_scn(rs);
516    list_clear(rs->incoming_queue);
517
518    rs->rfc_port_handle = 0;
519    //cleanup the flag
520    memset(&rs->f, 0, sizeof(rs->f));
521    rs->id = 0;
522}
523static inline BOOLEAN send_app_scn(rfc_slot_t* rs)
524{
525    if(sock_send_all(rs->fd, (const uint8_t*)&rs->scn, sizeof(rs->scn)) == sizeof(rs->scn))
526    {
527        return TRUE;
528    }
529
530    return FALSE;
531}
532static BOOLEAN send_app_connect_signal(int fd, const bt_bdaddr_t* addr, int channel, int status, int send_fd)
533{
534/*
535    typedef struct {
536    short size;
537    bt_bdaddr_t bd_addr;
538    int channel;
539    int status;
540} __attribute__((packed)) sock_connect_signal_t;
541*/
542    sock_connect_signal_t cs;
543    cs.size = sizeof(cs);
544    cs.bd_addr = *addr;
545    cs.channel = channel;
546    cs.status = status;
547    if(send_fd != -1)
548    {
549        if(sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == sizeof(cs))
550            return TRUE;
551        else APPL_TRACE_ERROR("sock_send_fd failed, fd:%d, send_fd:%d", fd, send_fd);
552    }
553    else if(sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs))
554    {
555        return TRUE;
556    }
557    return FALSE;
558}
559static void on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT *p_init, uint32_t id)
560{
561   lock_slot(&slot_lock);
562    rfc_slot_t* rs = find_rfc_slot_by_id(id);
563    if(rs)
564    {
565        if (p_init->status != BTA_JV_SUCCESS)
566            cleanup_rfc_slot(rs);
567        else
568        {
569            rs->rfc_handle = p_init->handle;
570        }
571    }
572    unlock_slot(&slot_lock);
573}
574static void  on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START *p_start, uint32_t id)
575{
576    lock_slot(&slot_lock);
577    rfc_slot_t* rs = find_rfc_slot_by_id(id);
578    if(rs)
579    {
580        if (p_start->status != BTA_JV_SUCCESS)
581            cleanup_rfc_slot(rs);
582        else
583        {
584            rs->rfc_handle = p_start->handle;
585
586            if(!send_app_scn(rs))
587            {
588                //closed
589                APPL_TRACE_DEBUG("send_app_scn() failed, close rs->id:%d", rs->id);
590                cleanup_rfc_slot(rs);
591            }
592        }
593    }
594    unlock_slot(&slot_lock);
595}
596static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN *p_open, uint32_t id)
597{
598    uint32_t new_listen_slot_id = 0;
599    lock_slot(&slot_lock);
600    rfc_slot_t* srv_rs = find_rfc_slot_by_id(id);
601    if(srv_rs)
602    {
603        rfc_slot_t* accept_rs = create_srv_accept_rfc_slot(srv_rs, (const bt_bdaddr_t*)p_open->rem_bda,
604                                                           p_open->handle, p_open->new_listen_handle);
605        if(accept_rs)
606        {
607            //start monitor the socket
608            btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, srv_rs->id);
609            btsock_thread_add_fd(pth, accept_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, accept_rs->id);
610            APPL_TRACE_DEBUG("sending connect signal & app fd:%dto app server to accept() the connection",
611                             accept_rs->app_fd);
612            APPL_TRACE_DEBUG("server fd:%d, scn:%d", srv_rs->fd, srv_rs->scn);
613            send_app_connect_signal(srv_rs->fd, &accept_rs->addr, srv_rs->scn, 0, accept_rs->app_fd);
614            accept_rs->app_fd = -1; //the fd is closed after sent to app
615            new_listen_slot_id = srv_rs->id;
616        }
617    }
618    unlock_slot(&slot_lock);
619    return new_listen_slot_id;
620}
621static void on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN *p_open, uint32_t id)
622{
623    lock_slot(&slot_lock);
624    rfc_slot_t* rs = find_rfc_slot_by_id(id);
625    if(rs && p_open->status == BTA_JV_SUCCESS)
626    {
627        rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(p_open->handle);
628        bd_copy(rs->addr.address, p_open->rem_bda, 0);
629        //notify app rfc is connected
630        APPL_TRACE_DEBUG("call send_app_connect_signal, slot id:%d, fd:%d, rfc scn:%d, server:%d",
631                         rs->id, rs->fd, rs->scn, rs->f.server);
632        if(send_app_connect_signal(rs->fd, &rs->addr, rs->scn, 0, -1))
633        {
634            //start monitoring the socketpair to get call back when app writing data
635            APPL_TRACE_DEBUG("on_rfc_connect_ind, connect signal sent, slot id:%d, rfc scn:%d, server:%d",
636                             rs->id, rs->scn, rs->f.server);
637            rs->f.connected = TRUE;
638        }
639        else APPL_TRACE_ERROR("send_app_connect_signal failed");
640    }
641    else if(rs)
642        cleanup_rfc_slot(rs);
643    unlock_slot(&slot_lock);
644}
645static void on_rfc_close(tBTA_JV_RFCOMM_CLOSE * p_close, uint32_t id)
646{
647    UNUSED(p_close);
648    lock_slot(&slot_lock);
649    rfc_slot_t* rs = find_rfc_slot_by_id(id);
650    if(rs)
651    {
652        APPL_TRACE_DEBUG("on_rfc_close, slot id:%d, fd:%d, rfc scn:%d, server:%d",
653                         rs->id, rs->fd, rs->scn, rs->f.server);
654        free_rfc_slot_scn(rs);
655        // rfc_handle already closed when receiving rfcomm close event from stack.
656        rs->f.connected = FALSE;
657        cleanup_rfc_slot(rs);
658    }
659    unlock_slot(&slot_lock);
660}
661static void on_rfc_write_done(tBTA_JV_RFCOMM_WRITE *p, uint32_t id)
662{
663    UNUSED(p);
664
665    lock_slot(&slot_lock);
666    rfc_slot_t* rs = find_rfc_slot_by_id(id);
667    if(rs && !rs->f.outgoing_congest)
668    {
669        //mointer the fd for any outgoing data
670        btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, rs->id);
671    }
672    unlock_slot(&slot_lock);
673}
674static void on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG *p, uint32_t id)
675{
676    lock_slot(&slot_lock);
677    rfc_slot_t* rs = find_rfc_slot_by_id(id);
678    if(rs)
679    {
680        rs->f.outgoing_congest = p->cong ? 1 : 0;
681        //mointer the fd for any outgoing data
682        if(!rs->f.outgoing_congest)
683            btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, rs->id);
684    }
685    unlock_slot(&slot_lock);
686}
687
688static void *rfcomm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data)
689{
690    int rc;
691    void* new_user_data = NULL;
692    APPL_TRACE_DEBUG("event=%s", jv_evt[event]);
693
694    switch (event)
695    {
696    case BTA_JV_RFCOMM_START_EVT:
697        on_srv_rfc_listen_started(&p_data->rfc_start, (uintptr_t)user_data);
698        break;
699
700    case BTA_JV_RFCOMM_CL_INIT_EVT:
701        on_cl_rfc_init(&p_data->rfc_cl_init, (uintptr_t)user_data);
702        break;
703
704    case BTA_JV_RFCOMM_OPEN_EVT:
705        BTA_JvSetPmProfile(p_data->rfc_open.handle,BTA_JV_PM_ID_1,BTA_JV_CONN_OPEN);
706        on_cli_rfc_connect(&p_data->rfc_open, (uintptr_t)user_data);
707        break;
708    case BTA_JV_RFCOMM_SRV_OPEN_EVT:
709        BTA_JvSetPmProfile(p_data->rfc_srv_open.handle,BTA_JV_PM_ALL,BTA_JV_CONN_OPEN);
710        new_user_data = (void*)(intptr_t)on_srv_rfc_connect(&p_data->rfc_srv_open, (uintptr_t)user_data);
711        break;
712
713    case BTA_JV_RFCOMM_CLOSE_EVT:
714        APPL_TRACE_DEBUG("BTA_JV_RFCOMM_CLOSE_EVT: user_data:%d", (uintptr_t)user_data);
715        on_rfc_close(&p_data->rfc_close, (uintptr_t)user_data);
716        break;
717
718    case BTA_JV_RFCOMM_READ_EVT:
719        APPL_TRACE_DEBUG("BTA_JV_RFCOMM_READ_EVT not used");
720        break;
721
722    case BTA_JV_RFCOMM_WRITE_EVT:
723        on_rfc_write_done(&p_data->rfc_write, (uintptr_t)user_data);
724        break;
725
726    case BTA_JV_RFCOMM_DATA_IND_EVT:
727        APPL_TRACE_DEBUG("BTA_JV_RFCOMM_DATA_IND_EVT not used");
728        break;
729
730    case BTA_JV_RFCOMM_CONG_EVT:
731        //on_rfc_cong(&p_data->rfc_cong);
732        on_rfc_outgoing_congest(&p_data->rfc_cong, (uintptr_t)user_data);
733        break;
734    default:
735        APPL_TRACE_ERROR("unhandled event %d, slot id:%d", event, (uintptr_t)user_data);
736        break;
737    }
738    return new_user_data;
739}
740
741static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data)
742{
743    uint32_t id = (uintptr_t)user_data;
744    APPL_TRACE_DEBUG("jv_dm_cback: event:%d, slot id:%d", event, id);
745    switch(event)
746    {
747        case BTA_JV_CREATE_RECORD_EVT:
748            {
749                lock_slot(&slot_lock);
750                rfc_slot_t* rs = find_rfc_slot_by_id(id);
751                if(rs && create_server_sdp_record(rs))
752                {
753                    //now start the rfcomm server after sdp & channel # assigned
754                    BTA_JvRfcommStartServer(rs->security, rs->role, rs->scn, MAX_RFC_SESSION, rfcomm_cback,
755                                            (void*)(uintptr_t)rs->id);
756                }
757                else if(rs)
758                {
759                    APPL_TRACE_ERROR("jv_dm_cback: cannot start server, slot found:%p", rs);
760                    cleanup_rfc_slot(rs);
761                }
762                unlock_slot(&slot_lock);
763                break;
764            }
765        case BTA_JV_DISCOVERY_COMP_EVT:
766            {
767                rfc_slot_t* rs = NULL;
768                lock_slot(&slot_lock);
769                if(p_data->disc_comp.status == BTA_JV_SUCCESS && p_data->disc_comp.scn)
770                {
771                    APPL_TRACE_DEBUG("BTA_JV_DISCOVERY_COMP_EVT, slot id:%d, status:%d, scn:%d",
772                                      id, p_data->disc_comp.status, p_data->disc_comp.scn);
773
774                    rs = find_rfc_slot_by_id(id);
775                    if(rs && rs->f.doing_sdp_request)
776                    {
777                        if(BTA_JvRfcommConnect(rs->security, rs->role, p_data->disc_comp.scn, rs->addr.address,
778                                    rfcomm_cback, (void*)(uintptr_t)rs->id) == BTA_JV_SUCCESS)
779                        {
780                            rs->scn = p_data->disc_comp.scn;
781                            rs->f.doing_sdp_request = FALSE;
782                            if(!send_app_scn(rs))
783                                cleanup_rfc_slot(rs);
784                        }
785                        else cleanup_rfc_slot(rs);
786                    }
787                    else if(rs)
788                    {
789                        APPL_TRACE_ERROR("DISCOVERY_COMP_EVT no pending sdp request, slot id:%d, \
790                                flag sdp pending:%d, flag sdp doing:%d",
791                                id, rs->f.pending_sdp_request, rs->f.doing_sdp_request);
792                    }
793                }
794                else
795                {
796                    APPL_TRACE_ERROR("DISCOVERY_COMP_EVT slot id:%d, failed to find channle, \
797                                      status:%d, scn:%d", id, p_data->disc_comp.status,
798                                      p_data->disc_comp.scn);
799                    rs = find_rfc_slot_by_id(id);
800                    if(rs)
801                        cleanup_rfc_slot(rs);
802                }
803                rs = find_rfc_slot_by_pending_sdp();
804                if(rs)
805                {
806                    APPL_TRACE_DEBUG("BTA_JV_DISCOVERY_COMP_EVT, start another pending scn sdp request");
807                    tSDP_UUID sdp_uuid;
808                    sdp_uuid.len = 16;
809                    memcpy(sdp_uuid.uu.uuid128, rs->service_uuid, sizeof(sdp_uuid.uu.uuid128));
810                    BTA_JvStartDiscovery((UINT8*)rs->addr.address, 1, &sdp_uuid, (void*)(uintptr_t)rs->id);
811                    rs->f.pending_sdp_request = FALSE;
812                    rs->f.doing_sdp_request = TRUE;
813                }
814                unlock_slot(&slot_lock);
815                break;
816            }
817        default:
818            APPL_TRACE_DEBUG("unhandled event:%d, slot id:%d", event, id);
819            break;
820    }
821
822}
823#define SENT_ALL 2
824#define SENT_PARTIAL 1
825#define SENT_NONE 0
826#define SENT_FAILED (-1)
827static int send_data_to_app(int fd, BT_HDR *p_buf)
828{
829    if(p_buf->len == 0)
830        return SENT_ALL;
831    int sent = send(fd, (UINT8 *)(p_buf + 1) + p_buf->offset,  p_buf->len, MSG_DONTWAIT);
832    if(sent == p_buf->len)
833        return SENT_ALL;
834
835    if(sent > 0 && sent < p_buf->len)
836    {
837        //sent partial
838        APPL_TRACE_ERROR("send partial, sent:%d, p_buf->len:%d", sent, p_buf->len);
839        p_buf->offset += sent;
840        p_buf->len -= sent;
841        return SENT_PARTIAL;
842
843    }
844    if(sent < 0 &&
845        (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
846    {
847        APPL_TRACE_ERROR("send none, EAGAIN or EWOULDBLOCK, errno:%d", errno);
848        return SENT_NONE;
849    }
850    APPL_TRACE_ERROR("unknown send() error, sent:%d, p_buf->len:%d,  errno:%d", sent, p_buf->len, errno);
851    return SENT_FAILED;
852}
853static BOOLEAN flush_incoming_que_on_wr_signal(rfc_slot_t* rs)
854{
855    while(!list_is_empty(rs->incoming_queue))
856    {
857        BT_HDR *p_buf = list_front(rs->incoming_queue);
858        int sent = send_data_to_app(rs->fd, p_buf);
859        switch(sent)
860        {
861            case SENT_NONE:
862            case SENT_PARTIAL:
863                //monitor the fd to get callback when app is ready to receive data
864                btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, rs->id);
865                return TRUE;
866            case SENT_ALL:
867                list_remove(rs->incoming_queue, p_buf);
868                break;
869            case SENT_FAILED:
870                list_remove(rs->incoming_queue, p_buf);
871                return FALSE;
872        }
873    }
874
875    //app is ready to receive data, tell stack to start the data flow
876    //fix me: need a jv flow control api to serialize the call in stack
877    APPL_TRACE_DEBUG("enable data flow, rfc_handle:0x%x, rfc_port_handle:0x%x, user_id:%d",
878                        rs->rfc_handle, rs->rfc_port_handle, rs->id);
879    extern int PORT_FlowControl_MaxCredit(UINT16 handle, BOOLEAN enable);
880    PORT_FlowControl_MaxCredit(rs->rfc_port_handle, TRUE);
881    return TRUE;
882}
883void btsock_rfc_signaled(int fd, int flags, uint32_t user_id)
884{
885    lock_slot(&slot_lock);
886    rfc_slot_t* rs = find_rfc_slot_by_id(user_id);
887    if(rs)
888    {
889        APPL_TRACE_DEBUG("rfc slot id:%d, fd:%d, flags:%x", rs->id, fd, flags);
890        BOOLEAN need_close = FALSE;
891        if(flags & SOCK_THREAD_FD_RD)
892        {
893            //data available from app, tell stack we have outgoing data
894            if(!rs->f.server)
895            {
896                if(rs->f.connected)
897                {
898                    int size = 0;
899                    //make sure there's data pending in case the peer closed the socket
900                    if(!(flags & SOCK_THREAD_FD_EXCEPTION) ||
901                                (ioctl(rs->fd, FIONREAD, &size) == 0 && size))
902                    {
903                        int rfc_handle = rs->rfc_handle;
904                        UINT32 rs_id = rs->id;
905                        //unlock before BTA_JvRfcommWrite to avoid deadlock on concurrnet multi rfcomm connectoins
906                        unlock_slot(&slot_lock);
907                        BTA_JvRfcommWrite(rfc_handle, rs_id);
908                        return;
909                    }
910                }
911                else
912                {
913                    APPL_TRACE_ERROR("SOCK_THREAD_FD_RD signaled when rfc is not connected, \
914                                      slot id:%d, channel:%d", rs->id, rs->scn);
915                    need_close = TRUE;
916                }
917            }
918        }
919        if(flags & SOCK_THREAD_FD_WR)
920        {
921            //app is ready to receive more data, tell stack to enable the data flow
922            if(!rs->f.connected || !flush_incoming_que_on_wr_signal(rs))
923            {
924                need_close = TRUE;
925                APPL_TRACE_ERROR("SOCK_THREAD_FD_WR signaled when rfc is not connected \
926                                  or app closed fd, slot id:%d, channel:%d", rs->id, rs->scn);
927            }
928
929        }
930        if(need_close || (flags & SOCK_THREAD_FD_EXCEPTION))
931        {
932            int size = 0;
933            if(need_close || ioctl(rs->fd, FIONREAD, &size) != 0 || size == 0 )
934            {
935                //cleanup when no data pending
936                APPL_TRACE_DEBUG("SOCK_THREAD_FD_EXCEPTION, cleanup, flags:%x, need_close:%d, pending size:%d",
937                                flags, need_close, size);
938                cleanup_rfc_slot(rs);
939            }
940            else
941                APPL_TRACE_DEBUG("SOCK_THREAD_FD_EXCEPTION, cleanup pending, flags:%x, need_close:%d, pending size:%d",
942                                flags, need_close, size);
943        }
944    }
945    unlock_slot(&slot_lock);
946}
947
948int bta_co_rfc_data_incoming(void *user_data, BT_HDR *p_buf)
949{
950    uint32_t id = (uintptr_t)user_data;
951    int ret = 0;
952    lock_slot(&slot_lock);
953    rfc_slot_t* rs = find_rfc_slot_by_id(id);
954    if(rs)
955    {
956        if(!list_is_empty(rs->incoming_queue))
957            list_append(rs->incoming_queue, p_buf);
958        else
959        {
960            int sent = send_data_to_app(rs->fd, p_buf);
961            switch(sent)
962            {
963                case SENT_NONE:
964                case SENT_PARTIAL:
965                    //add it to the end of the queue
966                    list_append(rs->incoming_queue, p_buf);
967                    //monitor the fd to get callback when app is ready to receive data
968                    btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, rs->id);
969                    break;
970                case SENT_ALL:
971                    GKI_freebuf(p_buf);
972                    ret = 1;//enable the data flow
973                    break;
974                case SENT_FAILED:
975                    GKI_freebuf(p_buf);
976                    cleanup_rfc_slot(rs);
977                    break;
978            }
979        }
980     }
981    unlock_slot(&slot_lock);
982    return ret;//return 0 to disable data flow
983}
984int bta_co_rfc_data_outgoing_size(void *user_data, int *size)
985{
986    uint32_t id = (uintptr_t)user_data;
987    int ret = FALSE;
988    *size = 0;
989    lock_slot(&slot_lock);
990    rfc_slot_t* rs = find_rfc_slot_by_id(id);
991    if(rs)
992    {
993        if(ioctl(rs->fd, FIONREAD, size) == 0)
994        {
995            APPL_TRACE_DEBUG("ioctl read avaiable size:%d, fd:%d", *size, rs->fd);
996            ret = TRUE;
997        }
998        else
999        {
1000            APPL_TRACE_ERROR("ioctl FIONREAD error, errno:%d, fd:%d", errno, rs->fd);
1001            cleanup_rfc_slot(rs);
1002        }
1003    }
1004    else APPL_TRACE_ERROR("bta_co_rfc_data_outgoing_size, invalid slot id:%d", id);
1005    unlock_slot(&slot_lock);
1006    return ret;
1007}
1008int bta_co_rfc_data_outgoing(void *user_data, UINT8* buf, UINT16 size)
1009{
1010    uint32_t id = (uintptr_t)user_data;
1011    int ret = FALSE;
1012    lock_slot(&slot_lock);
1013    rfc_slot_t* rs = find_rfc_slot_by_id(id);
1014    if(rs)
1015    {
1016        int received = recv(rs->fd, buf, size, 0);
1017        if(received == size)
1018            ret = TRUE;
1019        else
1020        {
1021            APPL_TRACE_ERROR("recv error, errno:%d, fd:%d, size:%d, received:%d",
1022                             errno, rs->fd, size, received);
1023            cleanup_rfc_slot(rs);
1024        }
1025    }
1026    else APPL_TRACE_ERROR("bta_co_rfc_data_outgoing, invalid slot id:%d", id);
1027    unlock_slot(&slot_lock);
1028    return ret;
1029}
1030
1031