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 <base/logging.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 
92 btpan_cb_t btpan_cb;
93 
94 static bool jni_initialized;
95 static bool stack_initialized;
96 
97 static bt_status_t btpan_jni_init(const btpan_callbacks_t* callbacks);
98 static void btpan_jni_cleanup();
99 static bt_status_t btpan_connect(const bt_bdaddr_t* bd_addr, int local_role,
100                                  int remote_role);
101 static bt_status_t btpan_disconnect(const bt_bdaddr_t* bd_addr);
102 static bt_status_t btpan_enable(int local_role);
103 static int btpan_get_local_role(void);
104 
105 static void btpan_tap_fd_signaled(int fd, int type, int flags,
106                                   uint32_t user_id);
107 static void btpan_cleanup_conn(btpan_conn_t* conn);
108 static void bta_pan_callback(tBTA_PAN_EVT event, tBTA_PAN* p_data);
109 static void btu_exec_tap_fd_read(void* p_param);
110 
111 static 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 
btif_pan_get_interface()115 btpan_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  ******************************************************************************/
btif_pan_init()126 void 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 
pan_disable()144 static 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 
btif_pan_cleanup()155 void 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 
166 static btpan_callbacks_t callback;
btpan_jni_init(const btpan_callbacks_t * callbacks)167 static 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 
btpan_jni_cleanup()176 static void btpan_jni_cleanup() {
177   pan_disable();
178   jni_initialized = false;
179 }
180 
bta_role_to_btpan(int bta_pan_role)181 static 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 
btpan_role_to_bta(int btpan_role)189 static 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 
197 static volatile int btpan_dev_local_role;
198 #if (BTA_PAN_INCLUDED == TRUE)
199 static tBTA_PAN_ROLE_INFO bta_panu_info = {PANU_SERVICE_NAME, 0, PAN_SECURITY};
200 static tBTA_PAN_ROLE_INFO bta_pan_nap_info = {PAN_NAP_SERVICE_NAME, 1,
201                                               PAN_SECURITY};
202 #endif
203 
btpan_enable(int local_role)204 static 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 
btpan_get_local_role()216 static 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 
btpan_connect(const bt_bdaddr_t * bd_addr,int local_role,int remote_role)221 static 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 
btif_in_pan_generic_evt(uint16_t event,char * p_param)231 static 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 
btpan_disconnect(const bt_bdaddr_t * bd_addr)255 static 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 
268 static int pan_pth = -1;
create_tap_read_thread(int tap_fd)269 void 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 
destroy_tap_read_thread(void)275 void destroy_tap_read_thread(void) {
276   if (pan_pth >= 0) {
277     btsock_thread_exit(pan_pth);
278     pan_pth = -1;
279   }
280 }
281 
tap_if_up(const char * devname,const bt_bdaddr_t * addr)282 static 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 
tap_if_down(const char * devname)347 static 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 
btpan_set_flow_control(bool enable)366 void 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 
btpan_tap_open()376 int 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   fd = open(clonedev, O_RDWR);
384   if (fd < 0) {
385     BTIF_TRACE_DEBUG("could not open %s, err:%d", clonedev, errno);
386     return fd;
387   }
388 
389   memset(&ifr, 0, sizeof(ifr));
390   ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
391 
392   strncpy(ifr.ifr_name, TAP_IF_NAME, IFNAMSIZ);
393 
394   /* try to create the device */
395   err = ioctl(fd, TUNSETIFF, (void*)&ifr);
396   if (err < 0) {
397     BTIF_TRACE_DEBUG("ioctl error:%d, errno:%s", err, strerror(errno));
398     close(fd);
399     return err;
400   }
401   if (tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0) {
402     int flags = fcntl(fd, F_GETFL, 0);
403     fcntl(fd, F_SETFL, flags | O_NONBLOCK);
404     return fd;
405   }
406   BTIF_TRACE_ERROR("can not bring up tap interface:%s", TAP_IF_NAME);
407   close(fd);
408   return INVALID_FD;
409 }
410 
btpan_tap_send(int tap_fd,const BD_ADDR src,const BD_ADDR dst,uint16_t proto,const char * buf,uint16_t len,UNUSED_ATTR bool ext,UNUSED_ATTR bool forward)411 int btpan_tap_send(int tap_fd, const BD_ADDR src, const BD_ADDR dst,
412                    uint16_t proto, const char* buf, uint16_t len,
413                    UNUSED_ATTR bool ext, UNUSED_ATTR bool forward) {
414   if (tap_fd != INVALID_FD) {
415     tETH_HDR eth_hdr;
416     memcpy(&eth_hdr.h_dest, dst, ETH_ADDR_LEN);
417     memcpy(&eth_hdr.h_src, src, ETH_ADDR_LEN);
418     eth_hdr.h_proto = htons(proto);
419     char packet[TAP_MAX_PKT_WRITE_LEN + sizeof(tETH_HDR)];
420     memcpy(packet, &eth_hdr, sizeof(tETH_HDR));
421     if (len > TAP_MAX_PKT_WRITE_LEN) {
422       LOG_ERROR(LOG_TAG, "btpan_tap_send eth packet size:%d is exceeded limit!",
423                 len);
424       return -1;
425     }
426     memcpy(packet + sizeof(tETH_HDR), buf, len);
427 
428     /* Send data to network interface */
429     ssize_t ret;
430     OSI_NO_INTR(ret = write(tap_fd, packet, len + sizeof(tETH_HDR)));
431     BTIF_TRACE_DEBUG("ret:%d", ret);
432     return (int)ret;
433   }
434   return -1;
435 }
436 
btpan_tap_close(int fd)437 int btpan_tap_close(int fd) {
438   if (tap_if_down(TAP_IF_NAME) == 0) close(fd);
439   if (pan_pth >= 0) btsock_thread_wakeup(pan_pth);
440   return 0;
441 }
442 
btpan_find_conn_handle(uint16_t handle)443 btpan_conn_t* btpan_find_conn_handle(uint16_t handle) {
444   for (int i = 0; i < MAX_PAN_CONNS; i++) {
445     if (btpan_cb.conns[i].handle == handle) return &btpan_cb.conns[i];
446   }
447   return NULL;
448 }
449 
btpan_find_conn_addr(const BD_ADDR addr)450 btpan_conn_t* btpan_find_conn_addr(const BD_ADDR addr) {
451   for (int i = 0; i < MAX_PAN_CONNS; i++) {
452     if (memcmp(btpan_cb.conns[i].peer, addr, sizeof(BD_ADDR)) == 0)
453       return &btpan_cb.conns[i];
454   }
455   return NULL;
456 }
457 
btpan_open_conn(btpan_conn_t * conn,tBTA_PAN * p_data)458 static void btpan_open_conn(btpan_conn_t* conn, tBTA_PAN* p_data) {
459   BTIF_TRACE_API(
460       "btpan_open_conn: local_role:%d, peer_role: %d,  handle:%d, conn: %p",
461       p_data->open.local_role, p_data->open.peer_role, p_data->open.handle,
462       conn);
463 
464   if (conn == NULL)
465     conn = btpan_new_conn(p_data->open.handle, p_data->open.bd_addr,
466                           p_data->open.local_role, p_data->open.peer_role);
467   if (conn) {
468     BTIF_TRACE_DEBUG(
469         "btpan_open_conn:tap_fd:%d, open_count:%d, "
470         "conn->handle:%d should = handle:%d, local_role:%d, remote_role:%d",
471         btpan_cb.tap_fd, btpan_cb.open_count, conn->handle, p_data->open.handle,
472         conn->local_role, conn->remote_role);
473 
474     btpan_cb.open_count++;
475     conn->handle = p_data->open.handle;
476     if (btpan_cb.tap_fd < 0) {
477       btpan_cb.tap_fd = btpan_tap_open();
478       if (btpan_cb.tap_fd >= 0) create_tap_read_thread(btpan_cb.tap_fd);
479     }
480 
481     if (btpan_cb.tap_fd >= 0) {
482       btpan_cb.flow = 1;
483       conn->state = PAN_STATE_OPEN;
484     }
485   }
486 }
487 
btpan_close_conn(btpan_conn_t * conn)488 static void btpan_close_conn(btpan_conn_t* conn) {
489   BTIF_TRACE_API("btpan_close_conn: %p", conn);
490 
491   if (conn && conn->state == PAN_STATE_OPEN) {
492     BTIF_TRACE_DEBUG("btpan_close_conn: PAN_STATE_OPEN");
493 
494     conn->state = PAN_STATE_CLOSE;
495     btpan_cb.open_count--;
496 
497     if (btpan_cb.open_count == 0) {
498       destroy_tap_read_thread();
499       if (btpan_cb.tap_fd != INVALID_FD) {
500         btpan_tap_close(btpan_cb.tap_fd);
501         btpan_cb.tap_fd = INVALID_FD;
502       }
503     }
504   }
505 }
506 
btpan_cleanup_conn(btpan_conn_t * conn)507 static void btpan_cleanup_conn(btpan_conn_t* conn) {
508   if (conn) {
509     conn->handle = -1;
510     conn->state = -1;
511     memset(&conn->peer, 0, sizeof(conn->peer));
512     memset(&conn->eth_addr, 0, sizeof(conn->eth_addr));
513     conn->local_role = conn->remote_role = 0;
514   }
515 }
516 
btpan_new_conn(int handle,const BD_ADDR addr,int local_role,int remote_role)517 btpan_conn_t* btpan_new_conn(int handle, const BD_ADDR addr, int local_role,
518                              int remote_role) {
519   for (int i = 0; i < MAX_PAN_CONNS; i++) {
520     BTIF_TRACE_DEBUG("conns[%d]:%d", i, btpan_cb.conns[i].handle);
521     if (btpan_cb.conns[i].handle == -1) {
522       BTIF_TRACE_DEBUG("handle:%d, local_role:%d, remote_role:%d", handle,
523                        local_role, remote_role);
524 
525       btpan_cb.conns[i].handle = handle;
526       bdcpy(btpan_cb.conns[i].peer, addr);
527       btpan_cb.conns[i].local_role = local_role;
528       btpan_cb.conns[i].remote_role = remote_role;
529       return &btpan_cb.conns[i];
530     }
531   }
532   BTIF_TRACE_DEBUG("MAX_PAN_CONNS:%d exceeded, return NULL as failed",
533                    MAX_PAN_CONNS);
534   return NULL;
535 }
536 
btpan_close_handle(btpan_conn_t * p)537 void btpan_close_handle(btpan_conn_t* p) {
538   BTIF_TRACE_DEBUG("btpan_close_handle : close handle %d", p->handle);
539   p->handle = -1;
540   p->local_role = -1;
541   p->remote_role = -1;
542   memset(&p->peer, 0, 6);
543 }
544 
should_forward(tETH_HDR * hdr)545 static inline bool should_forward(tETH_HDR* hdr) {
546   uint16_t proto = ntohs(hdr->h_proto);
547   if (proto == ETH_P_IP || proto == ETH_P_ARP || proto == ETH_P_IPV6)
548     return true;
549   BTIF_TRACE_DEBUG("unknown proto:%x", proto);
550   return false;
551 }
552 
forward_bnep(tETH_HDR * eth_hdr,BT_HDR * hdr)553 static int forward_bnep(tETH_HDR* eth_hdr, BT_HDR* hdr) {
554   int broadcast = eth_hdr->h_dest[0] & 1;
555 
556   // Find the right connection to send this frame over.
557   for (int i = 0; i < MAX_PAN_CONNS; i++) {
558     uint16_t handle = btpan_cb.conns[i].handle;
559     if (handle != (uint16_t)-1 &&
560         (broadcast ||
561          memcmp(btpan_cb.conns[i].eth_addr, eth_hdr->h_dest, sizeof(BD_ADDR)) ==
562              0 ||
563          memcmp(btpan_cb.conns[i].peer, eth_hdr->h_dest, sizeof(BD_ADDR)) ==
564              0)) {
565       int result = PAN_WriteBuf(handle, eth_hdr->h_dest, eth_hdr->h_src,
566                                 ntohs(eth_hdr->h_proto), hdr, 0);
567       switch (result) {
568         case PAN_Q_SIZE_EXCEEDED:
569           return FORWARD_CONGEST;
570         case PAN_SUCCESS:
571           return FORWARD_SUCCESS;
572         default:
573           return FORWARD_FAILURE;
574       }
575     }
576   }
577   osi_free(hdr);
578   return FORWARD_IGNORE;
579 }
580 
bta_pan_callback_transfer(uint16_t event,char * p_param)581 static void bta_pan_callback_transfer(uint16_t event, char* p_param) {
582   tBTA_PAN* p_data = (tBTA_PAN*)p_param;
583 
584   switch (event) {
585     case BTA_PAN_ENABLE_EVT:
586       BTIF_TRACE_DEBUG("BTA_PAN_ENABLE_EVT");
587       break;
588     case BTA_PAN_SET_ROLE_EVT: {
589       int btpan_role = bta_role_to_btpan(p_data->set_role.role);
590       bt_status_t status = p_data->set_role.status == BTA_PAN_SUCCESS
591                                ? BT_STATUS_SUCCESS
592                                : BT_STATUS_FAIL;
593       btpan_control_state_t state =
594           btpan_role == 0 ? BTPAN_STATE_DISABLED : BTPAN_STATE_ENABLED;
595       callback.control_state_cb(state, btpan_role, status, TAP_IF_NAME);
596       break;
597     }
598     case BTA_PAN_OPENING_EVT: {
599       btpan_conn_t* conn;
600       bdstr_t bds;
601       bdaddr_to_string((bt_bdaddr_t*)p_data->opening.bd_addr, bds, sizeof(bds));
602       BTIF_TRACE_DEBUG("BTA_PAN_OPENING_EVT handle %d, addr: %s",
603                        p_data->opening.handle, bds);
604       conn = btpan_find_conn_addr(p_data->opening.bd_addr);
605 
606       asrt(conn != NULL);
607       if (conn) {
608         conn->handle = p_data->opening.handle;
609         int btpan_conn_local_role = bta_role_to_btpan(conn->local_role);
610         int btpan_remote_role = bta_role_to_btpan(conn->remote_role);
611         callback.connection_state_cb(
612             BTPAN_STATE_CONNECTING, BT_STATUS_SUCCESS,
613             (const bt_bdaddr_t*)p_data->opening.bd_addr, btpan_conn_local_role,
614             btpan_remote_role);
615       } else
616         BTIF_TRACE_ERROR("connection not found");
617       break;
618     }
619     case BTA_PAN_OPEN_EVT: {
620       btpan_connection_state_t state;
621       bt_status_t status;
622       btpan_conn_t* conn = btpan_find_conn_handle(p_data->open.handle);
623 
624       LOG_VERBOSE(LOG_TAG, "%s pan connection open status: %d", __func__,
625                   p_data->open.status);
626       if (p_data->open.status == BTA_PAN_SUCCESS) {
627         state = BTPAN_STATE_CONNECTED;
628         status = BT_STATUS_SUCCESS;
629         btpan_open_conn(conn, p_data);
630       } else {
631         state = BTPAN_STATE_DISCONNECTED;
632         status = BT_STATUS_FAIL;
633         btpan_cleanup_conn(conn);
634       }
635       /* debug("BTA_PAN_OPEN_EVT handle:%d, conn:%p",  p_data->open.handle,
636        * conn); */
637       /* debug("conn bta local_role:%d, bta remote role:%d", conn->local_role,
638        * conn->remote_role); */
639       int btpan_conn_local_role = bta_role_to_btpan(p_data->open.local_role);
640       int btpan_remote_role = bta_role_to_btpan(p_data->open.peer_role);
641       callback.connection_state_cb(state, status,
642                                    (const bt_bdaddr_t*)p_data->open.bd_addr,
643                                    btpan_conn_local_role, btpan_remote_role);
644       break;
645     }
646     case BTA_PAN_CLOSE_EVT: {
647       LOG_INFO(LOG_TAG, "%s: event = BTA_PAN_CLOSE_EVT handle %d", __func__,
648                p_data->close.handle);
649       btpan_conn_t* conn = btpan_find_conn_handle(p_data->close.handle);
650       btpan_close_conn(conn);
651 
652       if (conn && conn->handle >= 0) {
653         int btpan_conn_local_role = bta_role_to_btpan(conn->local_role);
654         int btpan_remote_role = bta_role_to_btpan(conn->remote_role);
655         callback.connection_state_cb(BTPAN_STATE_DISCONNECTED, (bt_status_t)0,
656                                      (const bt_bdaddr_t*)conn->peer,
657                                      btpan_conn_local_role, btpan_remote_role);
658         btpan_cleanup_conn(conn);
659       } else
660         BTIF_TRACE_ERROR("pan handle not found (%d)", p_data->close.handle);
661       break;
662     }
663     default:
664       BTIF_TRACE_WARNING("Unknown pan event %d", event);
665       break;
666   }
667 }
668 
bta_pan_callback(tBTA_PAN_EVT event,tBTA_PAN * p_data)669 static void bta_pan_callback(tBTA_PAN_EVT event, tBTA_PAN* p_data) {
670   btif_transfer_context(bta_pan_callback_transfer, event, (char*)p_data,
671                         sizeof(tBTA_PAN), NULL);
672 }
673 
674 #define IS_EXCEPTION(e) ((e) & (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL))
btu_exec_tap_fd_read(void * p_param)675 static void btu_exec_tap_fd_read(void* p_param) {
676   struct pollfd ufd;
677   int fd = PTR_TO_INT(p_param);
678 
679   if (fd == INVALID_FD || fd != btpan_cb.tap_fd) return;
680 
681   // Don't occupy BTU context too long, avoid buffer overruns and
682   // give other profiles a chance to run by limiting the amount of memory
683   // PAN can use.
684   for (int i = 0; i < PAN_BUF_MAX && btif_is_enabled() && btpan_cb.flow; i++) {
685     BT_HDR* buffer = (BT_HDR*)osi_malloc(PAN_BUF_SIZE);
686     buffer->offset = PAN_MINIMUM_OFFSET;
687     buffer->len = PAN_BUF_SIZE - sizeof(BT_HDR) - buffer->offset;
688 
689     uint8_t* packet = (uint8_t*)buffer + sizeof(BT_HDR) + buffer->offset;
690 
691     // If we don't have an undelivered packet left over, pull one from the TAP
692     // driver.
693     // We save it in the congest_packet right away in case we can't deliver it
694     // in this
695     // attempt.
696     if (!btpan_cb.congest_packet_size) {
697       ssize_t ret;
698       OSI_NO_INTR(ret = read(fd, btpan_cb.congest_packet,
699                              sizeof(btpan_cb.congest_packet)));
700       switch (ret) {
701         case -1:
702           BTIF_TRACE_ERROR("%s unable to read from driver: %s", __func__,
703                            strerror(errno));
704           osi_free(buffer);
705           // add fd back to monitor thread to try it again later
706           btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
707           return;
708         case 0:
709           BTIF_TRACE_WARNING("%s end of file reached.", __func__);
710           osi_free(buffer);
711           // add fd back to monitor thread to process the exception
712           btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
713           return;
714         default:
715           btpan_cb.congest_packet_size = ret;
716           break;
717       }
718     }
719 
720     memcpy(packet, btpan_cb.congest_packet,
721            MIN(btpan_cb.congest_packet_size, buffer->len));
722     buffer->len = MIN(btpan_cb.congest_packet_size, buffer->len);
723 
724     if (buffer->len > sizeof(tETH_HDR) && should_forward((tETH_HDR*)packet)) {
725       // Extract the ethernet header from the buffer since the PAN_WriteBuf
726       // inside
727       // forward_bnep can't handle two pointers that point inside the same GKI
728       // buffer.
729       tETH_HDR hdr;
730       memcpy(&hdr, packet, sizeof(tETH_HDR));
731 
732       // Skip the ethernet header.
733       buffer->len -= sizeof(tETH_HDR);
734       buffer->offset += sizeof(tETH_HDR);
735       if (forward_bnep(&hdr, buffer) != FORWARD_CONGEST)
736         btpan_cb.congest_packet_size = 0;
737     } else {
738       BTIF_TRACE_WARNING("%s dropping packet of length %d", __func__,
739                          buffer->len);
740       btpan_cb.congest_packet_size = 0;
741       osi_free(buffer);
742     }
743 
744     // Bail out of the loop if reading from the TAP fd would block.
745     ufd.fd = fd;
746     ufd.events = POLLIN;
747     ufd.revents = 0;
748 
749     int ret;
750     OSI_NO_INTR(ret = poll(&ufd, 1, 0));
751     if (ret <= 0 || IS_EXCEPTION(ufd.revents)) break;
752   }
753 
754   if (btpan_cb.flow) {
755     // add fd back to monitor thread when the flow is on
756     btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
757   }
758 }
759 
btif_pan_close_all_conns()760 static void btif_pan_close_all_conns() {
761   if (!stack_initialized) return;
762 
763   for (int i = 0; i < MAX_PAN_CONNS; ++i) {
764     if (btpan_cb.conns[i].handle != -1) BTA_PanClose(btpan_cb.conns[i].handle);
765   }
766 }
767 
btpan_tap_fd_signaled(int fd,int type,int flags,uint32_t user_id)768 static void btpan_tap_fd_signaled(int fd, int type, int flags,
769                                   uint32_t user_id) {
770   CHECK(btpan_cb.tap_fd == INVALID_FD || btpan_cb.tap_fd == fd);
771 
772   if (btpan_cb.tap_fd != fd) {
773     BTIF_TRACE_WARNING("%s Signaled on mismatched fds exp:%d act:%d\n",
774                        __func__, btpan_cb.tap_fd, fd);
775     return;
776   }
777 
778   if (flags & SOCK_THREAD_FD_EXCEPTION) {
779     btpan_cb.tap_fd = INVALID_FD;
780     btpan_tap_close(fd);
781     btif_pan_close_all_conns();
782   } else if (flags & SOCK_THREAD_FD_RD)
783     bta_dmexecutecallback(btu_exec_tap_fd_read, INT_TO_PTR(fd));
784 }
785