• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2014 Google, Inc.
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 #define LOG_TAG "bt_btif_sock"
20 
21 #include "btif/include/btif_sock.h"
22 
23 #include <base/logging.h>
24 #include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h>
25 #include <hardware/bluetooth.h>
26 #include <hardware/bt_sock.h>
27 #include <time.h>
28 
29 #include <atomic>
30 
31 #include "bta_api.h"
32 #include "btif_common.h"
33 #include "btif_config.h"
34 #include "btif_metrics_logging.h"
35 #include "btif_sock_l2cap.h"
36 #include "btif_sock_rfc.h"
37 #include "btif_sock_sco.h"
38 #include "btif_sock_sdp.h"
39 #include "btif_sock_thread.h"
40 #include "btif_uid.h"
41 #include "btif_util.h"
42 #include "osi/include/thread.h"
43 #include "types/bluetooth/uuid.h"
44 #include "types/raw_address.h"
45 
46 extern bool btif_get_address_type(const RawAddress& bda,
47                                   tBLE_ADDR_TYPE* p_addr_type);
48 extern bool btif_get_device_type(const RawAddress& bda, int* p_device_type);
49 
50 using bluetooth::Uuid;
51 
52 static bt_status_t btsock_listen(btsock_type_t type, const char* service_name,
53                                  const Uuid* uuid, int channel, int* sock_fd,
54                                  int flags, int app_uid);
55 static bt_status_t btsock_connect(const RawAddress* bd_addr, btsock_type_t type,
56                                   const Uuid* uuid, int channel, int* sock_fd,
57                                   int flags, int app_uid);
58 
59 static void btsock_request_max_tx_data_length(const RawAddress& bd_addr);
60 
61 static void btsock_signaled(int fd, int type, int flags, uint32_t user_id);
62 
63 static std::atomic_int thread_handle{-1};
64 static thread_t* thread;
65 
66 #define SOCK_LOGGER_SIZE_MAX 16
67 
68 struct SockConnectionEvent {
69   bool used;
70   RawAddress addr;
71   int state;
72   int role;
73   struct timespec timestamp;
74 
75   void dump(const int fd);
76 };
77 
78 static std::atomic<uint8_t> logger_index;
79 
80 static SockConnectionEvent connection_logger[SOCK_LOGGER_SIZE_MAX];
81 
btif_sock_get_interface(void)82 const btsock_interface_t* btif_sock_get_interface(void) {
83   static btsock_interface_t interface = {
84       sizeof(interface), btsock_listen, /* listen */
85       btsock_connect,                   /* connect */
86       btsock_request_max_tx_data_length /* request_max_tx_data_length */
87   };
88 
89   return &interface;
90 }
91 
btif_sock_init(uid_set_t * uid_set)92 bt_status_t btif_sock_init(uid_set_t* uid_set) {
93   CHECK(thread_handle == -1);
94   CHECK(thread == NULL);
95 
96   bt_status_t status;
97   btsock_thread_init();
98   thread_handle = btsock_thread_create(btsock_signaled, NULL);
99   if (thread_handle == -1) {
100     LOG_ERROR("%s unable to create btsock_thread.", __func__);
101     goto error;
102   }
103 
104   status = btsock_rfc_init(thread_handle, uid_set);
105   if (status != BT_STATUS_SUCCESS) {
106     LOG_ERROR("%s error initializing RFCOMM sockets: %d", __func__, status);
107     goto error;
108   }
109 
110   status = btsock_l2cap_init(thread_handle, uid_set);
111   if (status != BT_STATUS_SUCCESS) {
112     LOG_ERROR("%s error initializing L2CAP sockets: %d", __func__, status);
113     goto error;
114   }
115 
116   thread = thread_new("btif_sock");
117   if (!thread) {
118     LOG_ERROR("%s error creating new thread.", __func__);
119     btsock_rfc_cleanup();
120     goto error;
121   }
122 
123   status = btsock_sco_init(thread);
124   if (status != BT_STATUS_SUCCESS) {
125     LOG_ERROR("%s error initializing SCO sockets: %d", __func__, status);
126     btsock_rfc_cleanup();
127     goto error;
128   }
129 
130   return BT_STATUS_SUCCESS;
131 
132 error:;
133   thread_free(thread);
134   thread = NULL;
135   if (thread_handle != -1) btsock_thread_exit(thread_handle);
136   thread_handle = -1;
137   uid_set = NULL;
138   return BT_STATUS_FAIL;
139 }
140 
btif_sock_cleanup(void)141 void btif_sock_cleanup(void) {
142   int saved_handle = thread_handle;
143   if (std::atomic_exchange(&thread_handle, -1) == -1) return;
144 
145   btsock_thread_exit(saved_handle);
146   btsock_rfc_cleanup();
147   btsock_sco_cleanup();
148   btsock_l2cap_cleanup();
149   thread_free(thread);
150   thread = NULL;
151 }
152 
btif_sock_connection_logger(int state,int role,const RawAddress & addr)153 void btif_sock_connection_logger(int state, int role, const RawAddress& addr) {
154   LOG_INFO("address=%s, role=%d, state=%d", addr.ToString().c_str(), state,
155            role);
156 
157   uint8_t index = logger_index++ % SOCK_LOGGER_SIZE_MAX;
158 
159   connection_logger[index] = {
160       .used = true,
161       .addr = addr,
162       .state = state,
163       .role = role,
164   };
165   clock_gettime(CLOCK_REALTIME, &connection_logger[index].timestamp);
166 }
167 
btif_sock_dump(int fd)168 void btif_sock_dump(int fd) {
169   dprintf(fd, "\nSocket Events: \n");
170   dprintf(fd, "  Time        \tAddress          \tState             \tRole\n");
171 
172   const uint8_t head = logger_index.load() % SOCK_LOGGER_SIZE_MAX;
173 
174   uint8_t index = head;
175   do {
176     connection_logger[index].dump(fd);
177 
178     index++;
179     index %= SOCK_LOGGER_SIZE_MAX;
180   } while (index != head);
181   dprintf(fd, "\n");
182 }
183 
dump(const int fd)184 void SockConnectionEvent::dump(const int fd) {
185   if (!used) {
186     return;
187   }
188 
189   char eventtime[20];
190   char temptime[20];
191   struct tm* tstamp = localtime(&timestamp.tv_sec);
192   strftime(temptime, sizeof(temptime), "%H:%M:%S", tstamp);
193   snprintf(eventtime, sizeof(eventtime), "%s.%03ld", temptime,
194            timestamp.tv_nsec / 1000000);
195 
196   const char* str_state;
197   switch (state) {
198     case SOCKET_CONNECTION_STATE_LISTENING:
199       str_state = "STATE_LISTENING";
200       break;
201     case SOCKET_CONNECTION_STATE_CONNECTING:
202       str_state = "STATE_CONNECTING";
203       break;
204     case SOCKET_CONNECTION_STATE_CONNECTED:
205       str_state = "STATE_CONNECTED";
206       break;
207     case SOCKET_CONNECTION_STATE_DISCONNECTING:
208       str_state = "STATE_DISCONNECTING";
209       break;
210     case SOCKET_CONNECTION_STATE_DISCONNECTED:
211       str_state = "STATE_DISCONNECTED";
212       break;
213     default:
214       str_state = "STATE_UNKNOWN";
215       break;
216   }
217 
218   const char* str_role;
219   switch (role) {
220     case SOCKET_ROLE_LISTEN:
221       str_role = "ROLE_LISTEN";
222       break;
223     case SOCKET_ROLE_CONNECTION:
224       str_role = "ROLE_CONNECTION";
225       break;
226     default:
227       str_role = "ROLE_UNKNOWN";
228       break;
229   }
230 
231   dprintf(fd, "  %s\t%s\t%s   \t%s\n", eventtime,
232           addr.ToString().c_str(), str_state, str_role);
233 }
234 
btsock_listen(btsock_type_t type,const char * service_name,const Uuid * service_uuid,int channel,int * sock_fd,int flags,int app_uid)235 static bt_status_t btsock_listen(btsock_type_t type, const char* service_name,
236                                  const Uuid* service_uuid, int channel,
237                                  int* sock_fd, int flags, int app_uid) {
238   if ((flags & BTSOCK_FLAG_NO_SDP) == 0) {
239     CHECK(sock_fd != NULL);
240   }
241 
242   *sock_fd = INVALID_FD;
243   bt_status_t status = BT_STATUS_FAIL;
244   int original_channel = channel;
245 
246   btif_sock_connection_logger(SOCKET_CONNECTION_STATE_LISTENING,
247                               SOCKET_ROLE_LISTEN, RawAddress::kEmpty);
248   log_socket_connection_state(RawAddress::kEmpty, 0, type,
249                               android::bluetooth::SocketConnectionstateEnum::
250                                   SOCKET_CONNECTION_STATE_LISTENING,
251                               0, 0, app_uid, channel,
252                               android::bluetooth::SOCKET_ROLE_LISTEN);
253   switch (type) {
254     case BTSOCK_RFCOMM:
255       status = btsock_rfc_listen(service_name, service_uuid, channel, sock_fd,
256                                  flags, app_uid);
257       break;
258     case BTSOCK_L2CAP:
259       status =
260           btsock_l2cap_listen(service_name, channel, sock_fd, flags, app_uid);
261       break;
262     case BTSOCK_L2CAP_LE:
263       if (flags & BTSOCK_FLAG_NO_SDP) {
264         /* Set channel to zero so that it will be assigned */
265         channel = 0;
266       } else if (channel <= 0) {
267         LOG_ERROR("%s: type BTSOCK_L2CAP_LE: invalid channel=%d", __func__,
268                   channel);
269         break;
270       }
271       flags |= BTSOCK_FLAG_LE_COC;
272       LOG_INFO(
273 
274           "%s: type=BTSOCK_L2CAP_LE, channel=0x%x, original=0x%x, flags=0x%x",
275           __func__, channel, original_channel, flags);
276       status =
277           btsock_l2cap_listen(service_name, channel, sock_fd, flags, app_uid);
278       break;
279     case BTSOCK_SCO:
280       status = btsock_sco_listen(sock_fd, flags);
281       break;
282 
283     default:
284       LOG_ERROR("%s unknown/unsupported socket type: %d", __func__, type);
285       status = BT_STATUS_UNSUPPORTED;
286       break;
287   }
288   if (status != BT_STATUS_SUCCESS) {
289     btif_sock_connection_logger(SOCKET_CONNECTION_STATE_DISCONNECTED,
290                                 SOCKET_ROLE_LISTEN, RawAddress::kEmpty);
291     log_socket_connection_state(RawAddress::kEmpty, 0, type,
292                                 android::bluetooth::SocketConnectionstateEnum::
293                                     SOCKET_CONNECTION_STATE_DISCONNECTED,
294                                 0, 0, app_uid, channel,
295                                 android::bluetooth::SOCKET_ROLE_LISTEN);
296   }
297   return status;
298 }
299 
btsock_connect(const RawAddress * bd_addr,btsock_type_t type,const Uuid * uuid,int channel,int * sock_fd,int flags,int app_uid)300 static bt_status_t btsock_connect(const RawAddress* bd_addr, btsock_type_t type,
301                                   const Uuid* uuid, int channel, int* sock_fd,
302                                   int flags, int app_uid) {
303   CHECK(bd_addr != NULL);
304   CHECK(sock_fd != NULL);
305 
306   LOG_INFO("%s", __func__);
307 
308   *sock_fd = INVALID_FD;
309   bt_status_t status = BT_STATUS_FAIL;
310 
311   btif_sock_connection_logger(SOCKET_CONNECTION_STATE_CONNECTING,
312                               SOCKET_ROLE_CONNECTION, *bd_addr);
313   log_socket_connection_state(*bd_addr, 0, type,
314                               android::bluetooth::SocketConnectionstateEnum::
315                                   SOCKET_CONNECTION_STATE_CONNECTING,
316                               0, 0, app_uid, channel,
317                               android::bluetooth::SOCKET_ROLE_CONNECTION);
318   switch (type) {
319     case BTSOCK_RFCOMM:
320       status =
321           btsock_rfc_connect(bd_addr, uuid, channel, sock_fd, flags, app_uid);
322       break;
323 
324     case BTSOCK_L2CAP:
325       status = btsock_l2cap_connect(bd_addr, channel, sock_fd, flags, app_uid);
326       break;
327 
328     case BTSOCK_L2CAP_LE: {
329       flags |= BTSOCK_FLAG_LE_COC;
330 
331       // Ensure device is in inquiry database
332       tBLE_ADDR_TYPE addr_type = BLE_ADDR_PUBLIC;
333       int device_type = 0;
334 
335       if (btif_get_address_type(*bd_addr, &addr_type) &&
336           btif_get_device_type(*bd_addr, &device_type) &&
337           device_type != BT_DEVICE_TYPE_BREDR) {
338         BTA_DmAddBleDevice(*bd_addr, addr_type, device_type);
339       }
340 
341       LOG_INFO("%s: type=BTSOCK_L2CAP_LE, channel=0x%x, flags=0x%x", __func__,
342                channel, flags);
343       status = btsock_l2cap_connect(bd_addr, channel, sock_fd, flags, app_uid);
344       break;
345     }
346 
347     case BTSOCK_SCO:
348       status = btsock_sco_connect(bd_addr, sock_fd, flags);
349       break;
350 
351     default:
352       LOG_ERROR("%s unknown/unsupported socket type: %d", __func__, type);
353       status = BT_STATUS_UNSUPPORTED;
354       break;
355   }
356   if (status != BT_STATUS_SUCCESS) {
357     btif_sock_connection_logger(SOCKET_CONNECTION_STATE_DISCONNECTED,
358                                 SOCKET_ROLE_CONNECTION, *bd_addr);
359     log_socket_connection_state(*bd_addr, 0, type,
360                                 android::bluetooth::SocketConnectionstateEnum::
361                                     SOCKET_CONNECTION_STATE_DISCONNECTED,
362                                 0, 0, app_uid, channel,
363                                 android::bluetooth::SOCKET_ROLE_CONNECTION);
364   }
365   return status;
366 }
367 
btsock_request_max_tx_data_length(const RawAddress & remote_device)368 static void btsock_request_max_tx_data_length(const RawAddress& remote_device) {
369   BTA_DmBleRequestMaxTxDataLength(remote_device);
370 }
371 
btsock_signaled(int fd,int type,int flags,uint32_t user_id)372 static void btsock_signaled(int fd, int type, int flags, uint32_t user_id) {
373   switch (type) {
374     case BTSOCK_RFCOMM:
375       btsock_rfc_signaled(fd, flags, user_id);
376       break;
377     case BTSOCK_L2CAP:
378     case BTSOCK_L2CAP_LE:
379       /* Note: The caller may not distinguish between BTSOCK_L2CAP and
380        * BTSOCK_L2CAP_LE correctly */
381       btsock_l2cap_signaled(fd, flags, user_id);
382       break;
383     default:
384       LOG(FATAL) << "Invalid socket type! type=" << type << " fd=" << fd
385                  << " flags=" << flags << " user_id=" << user_id;
386       break;
387   }
388 }
389