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