btif_pan.c revision 41a842af4974a51f574872f2497794da7416d0dd
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_pan.c
22 *
23 *  Description:   PAN Profile Bluetooth Interface
24 *
25 *
26 ***********************************************************************************/
27
28#define LOG_TAG "bt_btif_pan"
29
30#include <assert.h>
31#include <ctype.h>
32#include <errno.h>
33#include <fcntl.h>
34#include <linux/if_ether.h>
35#include <linux/if_tun.h>
36#include <linux/sockios.h>
37#include <net/if.h>
38#include <netdb.h>
39#include <netinet/in.h>
40#include <signal.h>
41#include <stdio.h>
42#include <string.h>
43#include <string.h>
44#include <sys/ioctl.h>
45#include <sys/poll.h>
46#include <sys/prctl.h>
47#include <sys/select.h>
48#include <sys/socket.h>
49#include <sys/wait.h>
50#include <unistd.h>
51
52#include <hardware/bluetooth.h>
53#include <hardware/bt_pan.h>
54
55#include "bta_api.h"
56#include "bta_pan_api.h"
57#include "btcore/include/bdaddr.h"
58#include "btif_common.h"
59#include "btif_pan_internal.h"
60#include "btif_sock_thread.h"
61#include "btif_sock_util.h"
62#include "btif_util.h"
63#include "btm_api.h"
64#include "device/include/controller.h"
65#include "gki.h"
66#include "osi/include/log.h"
67#include "osi/include/osi.h"
68
69#define FORWARD_IGNORE        1
70#define FORWARD_SUCCESS       0
71#define FORWARD_FAILURE     (-1)
72#define FORWARD_CONGEST     (-2)
73//#define PANU_DISABLED TRUE
74
75#if (PAN_NAP_DISABLED == TRUE) && (PANU_DISABLED == TRUE)
76#define BTPAN_LOCAL_ROLE BTPAN_ROLE_NONE
77#elif PAN_NAP_DISABLED == TRUE
78#define BTPAN_LOCAL_ROLE BTPAN_ROLE_PANU
79#elif PANU_DISABLED == TRUE
80#define BTPAN_LOCAL_ROLE BTPAN_ROLE_PANNAP
81#else
82#define BTPAN_LOCAL_ROLE (BTPAN_ROLE_PANU | BTPAN_ROLE_PANNAP)
83#endif
84
85#define asrt(s) if (!(s)) BTIF_TRACE_ERROR("btif_pan: ## %s assert %s failed at line:%d ##",__FUNCTION__, #s, __LINE__)
86
87#define MIN(x, y) (((x) < (y)) ? (x) : (y))
88
89btpan_cb_t btpan_cb;
90
91static bool jni_initialized;
92static bool stack_initialized;
93
94static bt_status_t btpan_jni_init(const btpan_callbacks_t* callbacks);
95static void btpan_jni_cleanup();
96static bt_status_t btpan_connect(const bt_bdaddr_t *bd_addr, int local_role, int remote_role);
97static bt_status_t btpan_disconnect(const bt_bdaddr_t *bd_addr);
98static bt_status_t btpan_enable(int local_role);
99static int btpan_get_local_role(void);
100
101static void btpan_tap_fd_signaled(int fd, int type, int flags, uint32_t user_id);
102static void btpan_cleanup_conn(btpan_conn_t* conn);
103static void bta_pan_callback(tBTA_PAN_EVT event, tBTA_PAN *p_data);
104static void btu_exec_tap_fd_read(void *p_param);
105
106static btpan_interface_t pan_if = {
107    sizeof(pan_if),
108    btpan_jni_init,
109    btpan_enable,
110    btpan_get_local_role,
111    btpan_connect,
112    btpan_disconnect,
113    btpan_jni_cleanup
114};
115
116btpan_interface_t *btif_pan_get_interface()
117{
118    return &pan_if;
119}
120
121/*******************************************************************************
122 **
123 ** Function        btif_pan_init
124 **
125 ** Description     initializes the pan interface
126 **
127 ** Returns         bt_status_t
128 **
129 *******************************************************************************/
130void btif_pan_init()
131{
132    BTIF_TRACE_DEBUG("jni_initialized = %d, btpan_cb.enabled:%d", jni_initialized, btpan_cb.enabled);
133    stack_initialized = true;
134
135    if (jni_initialized && !btpan_cb.enabled)
136    {
137        BTIF_TRACE_DEBUG("Enabling PAN....");
138        memset(&btpan_cb, 0, sizeof(btpan_cb));
139        btpan_cb.tap_fd = INVALID_FD;
140        btpan_cb.flow = 1;
141        for (int i = 0; i < MAX_PAN_CONNS; i++)
142            btpan_cleanup_conn(&btpan_cb.conns[i]);
143        BTA_PanEnable(bta_pan_callback);
144        btpan_cb.enabled = 1;
145        btpan_enable(BTPAN_LOCAL_ROLE);
146    }
147}
148
149static void pan_disable()
150{
151    if (btpan_cb.enabled)
152    {
153        btpan_cb.enabled = 0;
154        BTA_PanDisable();
155        if (btpan_cb.tap_fd != INVALID_FD)
156        {
157            btpan_tap_close(btpan_cb.tap_fd);
158            btpan_cb.tap_fd = INVALID_FD;
159        }
160    }
161}
162
163void btif_pan_cleanup()
164{
165    if (!stack_initialized)
166        return;
167
168    // Bluetooth is shuting down, invalidate all BTA PAN handles
169    for (int i = 0; i < MAX_PAN_CONNS; i++)
170        btpan_cleanup_conn(&btpan_cb.conns[i]);
171
172    pan_disable();
173    stack_initialized = false;
174}
175
176static btpan_callbacks_t callback;
177static bt_status_t btpan_jni_init(const btpan_callbacks_t* callbacks)
178{
179    BTIF_TRACE_DEBUG("stack_initialized = %d, btpan_cb.enabled:%d", stack_initialized, btpan_cb.enabled);
180    callback = *callbacks;
181    jni_initialized = TRUE;
182    if (stack_initialized && !btpan_cb.enabled)
183        btif_pan_init();
184    return BT_STATUS_SUCCESS;
185}
186
187static void btpan_jni_cleanup()
188{
189    pan_disable();
190    jni_initialized = false;
191}
192
193static inline int bta_role_to_btpan(int bta_pan_role)
194{
195    int btpan_role = 0;
196    BTIF_TRACE_DEBUG("bta_pan_role:0x%x", bta_pan_role);
197    if (bta_pan_role & PAN_ROLE_NAP_SERVER)
198        btpan_role |= BTPAN_ROLE_PANNAP;
199    if (bta_pan_role & PAN_ROLE_CLIENT)
200        btpan_role |= BTPAN_ROLE_PANU;
201    return btpan_role;
202}
203
204static inline int btpan_role_to_bta(int btpan_role)
205{
206    int bta_pan_role = PAN_ROLE_INACTIVE;
207    BTIF_TRACE_DEBUG("btpan_role:0x%x", btpan_role);
208    if (btpan_role & BTPAN_ROLE_PANNAP)
209        bta_pan_role |= PAN_ROLE_NAP_SERVER;
210    if (btpan_role & BTPAN_ROLE_PANU)
211        bta_pan_role |= PAN_ROLE_CLIENT;
212    return bta_pan_role;
213}
214
215static volatile int btpan_dev_local_role;
216static tBTA_PAN_ROLE_INFO bta_panu_info = {PANU_SERVICE_NAME, 0, PAN_SECURITY};
217static tBTA_PAN_ROLE_INFO bta_pan_nap_info = {PAN_NAP_SERVICE_NAME, 1, PAN_SECURITY};
218
219static bt_status_t btpan_enable(int local_role)
220{
221#if BTA_PAN_INCLUDED == TRUE
222    BTIF_TRACE_DEBUG("%s - local_role: %d", __func__, local_role);
223    int bta_pan_role = btpan_role_to_bta(local_role);
224    BTA_PanSetRole(bta_pan_role, &bta_panu_info, NULL, &bta_pan_nap_info);
225    btpan_dev_local_role = local_role;
226    return BT_STATUS_SUCCESS;
227#else
228    return BT_STATUS_FAIL;
229#endif
230}
231
232static int btpan_get_local_role()
233{
234    BTIF_TRACE_DEBUG("btpan_dev_local_role:%d", btpan_dev_local_role);
235    return btpan_dev_local_role;
236}
237
238static bt_status_t btpan_connect(const bt_bdaddr_t *bd_addr, int local_role, int remote_role)
239{
240    BTIF_TRACE_DEBUG("local_role:%d, remote_role:%d", local_role, remote_role);
241    int bta_local_role = btpan_role_to_bta(local_role);
242    int bta_remote_role = btpan_role_to_bta(remote_role);
243    btpan_new_conn(-1, bd_addr->address, bta_local_role, bta_remote_role);
244    BTA_PanOpen((UINT8*)bd_addr->address, bta_local_role, bta_remote_role);
245    return BT_STATUS_SUCCESS;
246}
247
248static void btif_in_pan_generic_evt(UINT16 event, char *p_param)
249{
250    BTIF_TRACE_EVENT("%s: event=%d", __FUNCTION__, event);
251    switch (event) {
252        case BTIF_PAN_CB_DISCONNECTING:
253        {
254            bt_bdaddr_t *bd_addr = (bt_bdaddr_t*)p_param;
255            btpan_conn_t* conn = btpan_find_conn_addr(bd_addr->address);
256            int btpan_conn_local_role;
257            int btpan_remote_role;
258            asrt(conn != NULL);
259            if (conn) {
260                btpan_conn_local_role = bta_role_to_btpan(conn->local_role);
261                btpan_remote_role = bta_role_to_btpan(conn->remote_role);
262                callback.connection_state_cb(BTPAN_STATE_DISCONNECTING, BT_STATUS_SUCCESS,
263                        (const bt_bdaddr_t*)conn->peer, btpan_conn_local_role, btpan_remote_role);
264            }
265        } break;
266        default:
267        {
268            BTIF_TRACE_WARNING("%s : Unknown event 0x%x", __FUNCTION__, event);
269        }
270        break;
271    }
272}
273
274static bt_status_t btpan_disconnect(const bt_bdaddr_t *bd_addr)
275{
276    btpan_conn_t* conn = btpan_find_conn_addr(bd_addr->address);
277    if (conn && conn->handle >= 0)
278    {
279        /* Inform the application that the disconnect has been initiated successfully */
280        btif_transfer_context(btif_in_pan_generic_evt, BTIF_PAN_CB_DISCONNECTING,
281                              (char *)bd_addr, sizeof(bt_bdaddr_t), NULL);
282        BTA_PanClose(conn->handle);
283        return BT_STATUS_SUCCESS;
284    }
285    return BT_STATUS_FAIL;
286}
287
288static int pan_pth = -1;
289void create_tap_read_thread(int tap_fd)
290{
291    if (pan_pth < 0)
292        pan_pth = btsock_thread_create(btpan_tap_fd_signaled, NULL);
293    if (pan_pth >= 0)
294        btsock_thread_add_fd(pan_pth, tap_fd, 0, SOCK_THREAD_FD_RD, 0);
295}
296
297void destroy_tap_read_thread(void)
298{
299    if (pan_pth >= 0)
300    {
301        btsock_thread_exit(pan_pth);
302        pan_pth = -1;
303    }
304}
305
306static int tap_if_up(const char *devname, const bt_bdaddr_t *addr)
307{
308    struct ifreq ifr;
309    int sk, err;
310
311    sk = socket(AF_INET, SOCK_DGRAM, 0);
312    if (sk < 0)
313        return -1;
314
315    //set mac addr
316    memset(&ifr, 0, sizeof(ifr));
317    strncpy(ifr.ifr_name, devname, IFNAMSIZ - 1);
318    err = ioctl(sk, SIOCGIFHWADDR, &ifr);
319    if (err < 0)
320    {
321        BTIF_TRACE_ERROR("Could not get network hardware for interface:%s, errno:%s", devname, strerror(errno));
322        close(sk);
323        return -1;
324    }
325
326    strncpy(ifr.ifr_name, devname, IFNAMSIZ - 1);
327    memcpy(ifr.ifr_hwaddr.sa_data, addr->address, 6);
328
329    /* The IEEE has specified that the most significant bit of the most significant byte is used to
330     * determine a multicast address. If its a 1, that means multicast, 0 means unicast.
331     * Kernel returns an error if we try to set a multicast address for the tun-tap ethernet interface.
332     * Mask this bit to avoid any issue with auto generated address.
333     */
334    if (ifr.ifr_hwaddr.sa_data[0] & 0x01) {
335        BTIF_TRACE_WARNING("Not a unicast MAC address, force multicast bit flipping");
336        ifr.ifr_hwaddr.sa_data[0] &= ~0x01;
337    }
338
339    err = ioctl(sk, SIOCSIFHWADDR, (caddr_t)&ifr);
340
341    if (err < 0) {
342        BTIF_TRACE_ERROR("Could not set bt address for interface:%s, errno:%s", devname, strerror(errno));
343        close(sk);
344        return -1;
345    }
346
347    //bring it up
348    memset(&ifr, 0, sizeof(ifr));
349    strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1);
350
351    ifr.ifr_flags |= IFF_UP;
352    ifr.ifr_flags |= IFF_MULTICAST;
353
354    err = ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr);
355
356
357    if (err < 0) {
358        BTIF_TRACE_ERROR("Could not bring up network interface:%s, errno:%d", devname, errno);
359        close(sk);
360        return -1;
361    }
362    close(sk);
363    BTIF_TRACE_DEBUG("network interface: %s is up", devname);
364    return 0;
365}
366
367static int tap_if_down(const char *devname)
368{
369    struct ifreq ifr;
370    int sk;
371
372    sk = socket(AF_INET, SOCK_DGRAM, 0);
373    if (sk < 0)
374        return -1;
375
376    memset(&ifr, 0, sizeof(ifr));
377    strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1);
378
379    ifr.ifr_flags &= ~IFF_UP;
380
381    ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr);
382
383    close(sk);
384
385    return 0;
386}
387
388void btpan_set_flow_control(BOOLEAN enable) {
389    if (btpan_cb.tap_fd == -1)
390        return;
391
392    btpan_cb.flow = enable;
393    if (enable) {
394        btsock_thread_add_fd(pan_pth, btpan_cb.tap_fd, 0, SOCK_THREAD_FD_RD, 0);
395        bta_dmexecutecallback(btu_exec_tap_fd_read, INT_TO_PTR(btpan_cb.tap_fd));
396    }
397}
398
399int btpan_tap_open()
400{
401    struct ifreq ifr;
402    int fd, err;
403    const char *clonedev = "/dev/tun";
404
405    /* open the clone device */
406
407    if ((fd = open(clonedev, O_RDWR)) < 0)
408    {
409        BTIF_TRACE_DEBUG("could not open %s, err:%d", clonedev, errno);
410        return fd;
411    }
412
413    memset(&ifr, 0, sizeof(ifr));
414    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
415
416    strncpy(ifr.ifr_name, TAP_IF_NAME, IFNAMSIZ);
417
418    /* try to create the device */
419    if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0)
420    {
421        BTIF_TRACE_DEBUG("ioctl error:%d, errno:%s", err, strerror(errno));
422        close(fd);
423        return err;
424    }
425    if (tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0)
426    {
427        int flags = fcntl(fd, F_GETFL, 0);
428        fcntl(fd, F_SETFL, flags | O_NONBLOCK);
429        return fd;
430    }
431    BTIF_TRACE_ERROR("can not bring up tap interface:%s", TAP_IF_NAME);
432    close(fd);
433    return INVALID_FD;
434}
435
436int btpan_tap_send(int tap_fd, const BD_ADDR src, const BD_ADDR dst, UINT16 proto, const char* buf,
437                    UINT16 len, BOOLEAN ext, BOOLEAN forward)
438{
439    UNUSED(ext);
440    UNUSED(forward);
441    if (tap_fd != INVALID_FD)
442    {
443        tETH_HDR eth_hdr;
444        memcpy(&eth_hdr.h_dest, dst, ETH_ADDR_LEN);
445        memcpy(&eth_hdr.h_src, src, ETH_ADDR_LEN);
446        eth_hdr.h_proto = htons(proto);
447        char packet[TAP_MAX_PKT_WRITE_LEN + sizeof(tETH_HDR)];
448        memcpy(packet, &eth_hdr, sizeof(tETH_HDR));
449        if (len > TAP_MAX_PKT_WRITE_LEN)
450        {
451            LOG_ERROR(LOG_TAG, "btpan_tap_send eth packet size:%d is exceeded limit!", len);
452            return -1;
453        }
454        memcpy(packet + sizeof(tETH_HDR), buf, len);
455
456        /* Send data to network interface */
457        int ret = write(tap_fd, packet, len + sizeof(tETH_HDR));
458        BTIF_TRACE_DEBUG("ret:%d", ret);
459        return ret;
460    }
461    return -1;
462
463}
464
465int btpan_tap_close(int fd)
466{
467    if (tap_if_down(TAP_IF_NAME) == 0)
468        close(fd);
469    if (pan_pth >= 0)
470        btsock_thread_wakeup(pan_pth);
471    return 0;
472}
473
474btpan_conn_t * btpan_find_conn_handle(UINT16 handle)
475{
476    for (int i = 0; i < MAX_PAN_CONNS; i++)
477    {
478        if (btpan_cb.conns[i].handle == handle)
479            return &btpan_cb.conns[i];
480    }
481    return NULL;
482}
483
484btpan_conn_t* btpan_find_conn_addr(const BD_ADDR addr)
485{
486    for (int i = 0; i < MAX_PAN_CONNS; i++)
487    {
488        if (memcmp(btpan_cb.conns[i].peer, addr, sizeof(BD_ADDR)) == 0)
489            return &btpan_cb.conns[i];
490    }
491    return NULL;
492}
493
494static void btpan_open_conn(btpan_conn_t* conn, tBTA_PAN *p_data)
495{
496    BTIF_TRACE_API("btpan_open_conn: local_role:%d, peer_role: %d,  handle:%d, conn: %p",
497            p_data->open.local_role, p_data->open.peer_role, p_data->open.handle, conn);
498
499    if (conn == NULL)
500        conn = btpan_new_conn(p_data->open.handle, p_data->open.bd_addr, p_data->open.local_role,
501                p_data->open.peer_role);
502    if (conn)
503    {
504        BTIF_TRACE_DEBUG("btpan_open_conn:tap_fd:%d, open_count:%d, "
505                "conn->handle:%d should = handle:%d, local_role:%d, remote_role:%d",
506                btpan_cb.tap_fd, btpan_cb.open_count, conn->handle, p_data->open.handle,
507                conn->local_role, conn->remote_role);
508
509        btpan_cb.open_count++;
510        conn->handle = p_data->open.handle;
511        if (btpan_cb.tap_fd < 0)
512        {
513            btpan_cb.tap_fd = btpan_tap_open();
514            if(btpan_cb.tap_fd >= 0)
515                create_tap_read_thread(btpan_cb.tap_fd);
516        }
517
518        if (btpan_cb.tap_fd >= 0)
519        {
520            btpan_cb.flow = 1;
521            conn->state = PAN_STATE_OPEN;
522        }
523    }
524}
525
526static void btpan_close_conn(btpan_conn_t* conn)
527{
528    BTIF_TRACE_API("btpan_close_conn: %p",conn);
529
530    if (conn && conn->state == PAN_STATE_OPEN)
531    {
532        BTIF_TRACE_DEBUG("btpan_close_conn: PAN_STATE_OPEN");
533
534        conn->state = PAN_STATE_CLOSE;
535        btpan_cb.open_count--;
536
537        if (btpan_cb.open_count == 0)
538        {
539            destroy_tap_read_thread();
540            if (btpan_cb.tap_fd != INVALID_FD)
541            {
542                btpan_tap_close(btpan_cb.tap_fd);
543                btpan_cb.tap_fd = INVALID_FD;
544            }
545        }
546    }
547}
548
549
550static void btpan_cleanup_conn(btpan_conn_t* conn)
551{
552    if (conn)
553    {
554        conn->handle = -1;
555        conn->state = -1;
556        memset(&conn->peer, 0, sizeof(conn->peer));
557        memset(&conn->eth_addr, 0, sizeof(conn->eth_addr));
558        conn->local_role = conn->remote_role = 0;
559    }
560}
561
562btpan_conn_t* btpan_new_conn(int handle, const BD_ADDR addr, int local_role, int remote_role)
563{
564    for (int i = 0; i < MAX_PAN_CONNS; i++)
565    {
566        BTIF_TRACE_DEBUG("conns[%d]:%d", i, btpan_cb.conns[i].handle);
567        if (btpan_cb.conns[i].handle == -1)
568        {
569            BTIF_TRACE_DEBUG("handle:%d, local_role:%d, remote_role:%d", handle, local_role, remote_role);
570
571            btpan_cb.conns[i].handle = handle;
572            bdcpy(btpan_cb.conns[i].peer, addr);
573            btpan_cb.conns[i].local_role = local_role;
574            btpan_cb.conns[i].remote_role = remote_role;
575            return &btpan_cb.conns[i];
576        }
577    }
578    BTIF_TRACE_DEBUG("MAX_PAN_CONNS:%d exceeded, return NULL as failed", MAX_PAN_CONNS);
579    return NULL;
580}
581
582void btpan_close_handle(btpan_conn_t *p)
583{
584    BTIF_TRACE_DEBUG("btpan_close_handle : close handle %d", p->handle);
585    p->handle = -1;
586    p->local_role = -1;
587    p->remote_role = -1;
588    memset(&p->peer, 0, 6);
589}
590
591static inline bool should_forward(tETH_HDR* hdr)
592{
593    uint16_t proto = ntohs(hdr->h_proto);
594    if (proto == ETH_P_IP || proto == ETH_P_ARP || proto == ETH_P_IPV6)
595        return true;
596    BTIF_TRACE_DEBUG("unknown proto:%x", proto);
597    return false;
598}
599
600static int forward_bnep(tETH_HDR* eth_hdr, BT_HDR *hdr) {
601    int broadcast = eth_hdr->h_dest[0] & 1;
602
603    // Find the right connection to send this frame over.
604    for (int i = 0; i < MAX_PAN_CONNS; i++)
605    {
606        UINT16 handle = btpan_cb.conns[i].handle;
607        if (handle != (UINT16)-1 &&
608                (broadcast || memcmp(btpan_cb.conns[i].eth_addr, eth_hdr->h_dest, sizeof(BD_ADDR)) == 0
609                 || memcmp(btpan_cb.conns[i].peer, eth_hdr->h_dest, sizeof(BD_ADDR)) == 0)) {
610            int result = PAN_WriteBuf(handle, eth_hdr->h_dest, eth_hdr->h_src, ntohs(eth_hdr->h_proto), hdr, 0);
611            switch (result) {
612                case PAN_Q_SIZE_EXCEEDED:
613                    return FORWARD_CONGEST;
614                case PAN_SUCCESS:
615                    return FORWARD_SUCCESS;
616                default:
617                    return FORWARD_FAILURE;
618            }
619        }
620    }
621    GKI_freebuf(hdr);
622    return FORWARD_IGNORE;
623}
624
625static void bta_pan_callback_transfer(UINT16 event, char *p_param)
626{
627    tBTA_PAN *p_data = (tBTA_PAN *)p_param;
628
629    switch(event)
630    {
631        case BTA_PAN_ENABLE_EVT:
632            BTIF_TRACE_DEBUG("BTA_PAN_ENABLE_EVT");
633            break;
634        case BTA_PAN_SET_ROLE_EVT:
635            {
636                int btpan_role = bta_role_to_btpan(p_data->set_role.role);
637                bt_status_t status = p_data->set_role.status == BTA_PAN_SUCCESS ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
638                btpan_control_state_t state = btpan_role == 0 ? BTPAN_STATE_DISABLED : BTPAN_STATE_ENABLED;
639                callback.control_state_cb(state, btpan_role, status, TAP_IF_NAME);
640                break;
641            }
642        case BTA_PAN_OPENING_EVT:
643            {
644                btpan_conn_t* conn;
645                bdstr_t bds;
646                bdaddr_to_string((bt_bdaddr_t *)p_data->opening.bd_addr, bds, sizeof(bds));
647                BTIF_TRACE_DEBUG("BTA_PAN_OPENING_EVT handle %d, addr: %s", p_data->opening.handle, bds);
648                conn = btpan_find_conn_addr(p_data->opening.bd_addr);
649
650                asrt(conn != NULL);
651                if (conn)
652                {
653                    conn->handle = p_data->opening.handle;
654                    int btpan_conn_local_role = bta_role_to_btpan(conn->local_role);
655                    int btpan_remote_role = bta_role_to_btpan(conn->remote_role);
656                    callback.connection_state_cb(BTPAN_STATE_CONNECTING, BT_STATUS_SUCCESS,
657                            (const bt_bdaddr_t*)p_data->opening.bd_addr, btpan_conn_local_role, btpan_remote_role);
658                }
659                else
660                    BTIF_TRACE_ERROR("connection not found");
661                break;
662            }
663        case BTA_PAN_OPEN_EVT:
664            {
665                btpan_connection_state_t state;
666                bt_status_t status;
667                btpan_conn_t *conn = btpan_find_conn_handle(p_data->open.handle);
668
669                LOG_VERBOSE(LOG_TAG, "%s pan connection open status: %d", __func__, p_data->open.status);
670                if (p_data->open.status == BTA_PAN_SUCCESS)
671                {
672                    state = BTPAN_STATE_CONNECTED;
673                    status = BT_STATUS_SUCCESS;
674                    btpan_open_conn(conn, p_data);
675                }
676                else
677                {
678                    state = BTPAN_STATE_DISCONNECTED;
679                    status = BT_STATUS_FAIL;
680                    btpan_cleanup_conn(conn);
681                }
682                /* debug("BTA_PAN_OPEN_EVT handle:%d, conn:%p",  p_data->open.handle, conn); */
683                /* debug("conn bta local_role:%d, bta remote role:%d", conn->local_role, conn->remote_role); */
684                int btpan_conn_local_role = bta_role_to_btpan(p_data->open.local_role);
685                int btpan_remote_role = bta_role_to_btpan(p_data->open.peer_role);
686                callback.connection_state_cb(state, status, (const bt_bdaddr_t*)p_data->open.bd_addr,
687                        btpan_conn_local_role, btpan_remote_role);
688                break;
689            }
690        case BTA_PAN_CLOSE_EVT:
691            {
692                LOG_INFO(LOG_TAG, "%s: event = BTA_PAN_CLOSE_EVT handle %d", __FUNCTION__, p_data->close.handle);
693                btpan_conn_t* conn = btpan_find_conn_handle(p_data->close.handle);
694                btpan_close_conn(conn);
695
696                if (conn && conn->handle >= 0)
697                {
698                    int btpan_conn_local_role = bta_role_to_btpan(conn->local_role);
699                    int btpan_remote_role = bta_role_to_btpan(conn->remote_role);
700                    callback.connection_state_cb(BTPAN_STATE_DISCONNECTED, 0, (const bt_bdaddr_t*)conn->peer,
701                            btpan_conn_local_role, btpan_remote_role);
702                    btpan_cleanup_conn(conn);
703                }
704                else
705                    BTIF_TRACE_ERROR("pan handle not found (%d)", p_data->close.handle);
706                break;
707            }
708        default:
709            BTIF_TRACE_WARNING("Unknown pan event %d", event);
710            break;
711    }
712}
713
714static void bta_pan_callback(tBTA_PAN_EVT event, tBTA_PAN *p_data)
715{
716    btif_transfer_context(bta_pan_callback_transfer, event, (char*)p_data, sizeof(tBTA_PAN), NULL);
717}
718
719#define IS_EXCEPTION(e) ((e) & (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL))
720static void btu_exec_tap_fd_read(void *p_param) {
721    struct pollfd ufd;
722    int fd = PTR_TO_INT(p_param);
723
724    if (fd == INVALID_FD || fd != btpan_cb.tap_fd)
725        return;
726
727    // Don't occupy BTU context too long, avoid GKI buffer overruns and
728    // give other profiles a chance to run by limiting the amount of memory
729    // PAN can use from the shared pool buffer.
730    for (int i = 0; i < PAN_POOL_MAX && btif_is_enabled() && btpan_cb.flow; i++) {
731        BT_HDR *buffer = (BT_HDR *)GKI_getbuf(PAN_BUF_SIZE);
732        if (!buffer) {
733            BTIF_TRACE_WARNING("%s unable to allocate buffer for packet.", __func__);
734            break;
735        }
736        buffer->offset = PAN_MINIMUM_OFFSET;
737        buffer->len = GKI_get_buf_size(buffer) - sizeof(BT_HDR) - buffer->offset;
738
739        UINT8 *packet = (UINT8 *)buffer + sizeof(BT_HDR) + buffer->offset;
740
741        // If we don't have an undelivered packet left over, pull one from the TAP driver.
742        // We save it in the congest_packet right away in case we can't deliver it in this
743        // attempt.
744        if (!btpan_cb.congest_packet_size) {
745            ssize_t ret = read(fd, btpan_cb.congest_packet, sizeof(btpan_cb.congest_packet));
746            switch (ret) {
747                case -1:
748                    BTIF_TRACE_ERROR("%s unable to read from driver: %s", __func__, strerror(errno));
749                    GKI_freebuf(buffer);
750                    //add fd back to monitor thread to try it again later
751                    btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
752                    return;
753                case 0:
754                    BTIF_TRACE_WARNING("%s end of file reached.", __func__);
755                    GKI_freebuf(buffer);
756                    //add fd back to monitor thread to process the exception
757                    btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
758                    return;
759                default:
760                    btpan_cb.congest_packet_size = ret;
761                    break;
762            }
763        }
764
765        memcpy(packet, btpan_cb.congest_packet, MIN(btpan_cb.congest_packet_size, buffer->len));
766        buffer->len = MIN(btpan_cb.congest_packet_size, buffer->len);
767
768        if (buffer->len > sizeof(tETH_HDR) && should_forward((tETH_HDR *)packet)) {
769            // Extract the ethernet header from the buffer since the PAN_WriteBuf inside
770            // forward_bnep can't handle two pointers that point inside the same GKI buffer.
771            tETH_HDR hdr;
772            memcpy(&hdr, packet, sizeof(tETH_HDR));
773
774            // Skip the ethernet header.
775            buffer->len -= sizeof(tETH_HDR);
776            buffer->offset += sizeof(tETH_HDR);
777            if (forward_bnep(&hdr, buffer) != FORWARD_CONGEST)
778                btpan_cb.congest_packet_size = 0;
779        } else {
780            BTIF_TRACE_WARNING("%s dropping packet of length %d", __func__, buffer->len);
781            btpan_cb.congest_packet_size = 0;
782            GKI_freebuf(buffer);
783        }
784
785        // Bail out of the loop if reading from the TAP fd would block.
786        ufd.fd = fd;
787        ufd.events = POLLIN;
788        ufd.revents = 0;
789        if (poll(&ufd, 1, 0) <= 0 || IS_EXCEPTION(ufd.revents))
790            break;
791    }
792    //add fd back to monitor thread
793    btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
794}
795
796static void btif_pan_close_all_conns() {
797    if (!stack_initialized)
798        return;
799
800    for (int i = 0; i < MAX_PAN_CONNS; ++i)
801    {
802        if (btpan_cb.conns[i].handle != -1)
803            BTA_PanClose(btpan_cb.conns[i].handle);
804    }
805}
806
807static void btpan_tap_fd_signaled(int fd, int type, int flags, uint32_t user_id) {
808    assert(btpan_cb.tap_fd == INVALID_FD || btpan_cb.tap_fd == fd);
809
810    if (btpan_cb.tap_fd != fd) {
811        BTIF_TRACE_WARNING("%s Signaled on mismatched fds exp:%d act:%d\n",
812                __func__, btpan_cb.tap_fd, fd);
813        return;
814    }
815
816    if (flags & SOCK_THREAD_FD_EXCEPTION) {
817        btpan_cb.tap_fd = INVALID_FD;
818        btpan_tap_close(fd);
819        btif_pan_close_all_conns();
820    } else if (flags & SOCK_THREAD_FD_RD)
821        bta_dmexecutecallback(btu_exec_tap_fd_read, INT_TO_PTR(fd));
822}
823