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