1 /******************************************************************************
2  *
3  *  Copyright 2015 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 #include <mutex>
20 
21 #include <base/logging.h>
22 #include <resolv.h>
23 #include <zlib.h>
24 
25 #include "btif/include/btif_debug.h"
26 #include "btif/include/btif_debug_btsnoop.h"
27 #include "hci/include/btsnoop_mem.h"
28 #include "internal_include/bt_target.h"
29 #include "osi/include/properties.h"
30 #include "osi/include/ringbuffer.h"
31 
32 #define REDUCE_HCI_TYPE_TO_SIGNIFICANT_BITS(type) ((type) >> 8)
33 
34 // Total btsnoop memory log buffer size
35 #ifndef BTSNOOP_MEM_BUFFER_SIZE
36 static const size_t BTSNOOP_MEM_BUFFER_SIZE = (256 * 1024);
37 #endif
38 
39 static std::mutex buffer_mutex;
40 static ringbuffer_t* buffer = NULL;
41 static uint64_t last_timestamp_ms = 0;
42 static bool qualcomm_debug_log_enable = false;
43 
44 static size_t btsnoop_calculate_packet_length(uint16_t type,
45                                               const uint8_t* data,
46                                               size_t length);
47 
btsnoop_cb(const uint16_t type,const uint8_t * data,const size_t length,const uint64_t timestamp_us)48 static void btsnoop_cb(const uint16_t type, const uint8_t* data,
49                        const size_t length, const uint64_t timestamp_us) {
50   btsnooz_header_t header;
51 
52   size_t included_length = btsnoop_calculate_packet_length(type, data, length);
53   if (included_length == 0) return;
54 
55   std::lock_guard<std::mutex> lock(buffer_mutex);
56 
57   // Make room in the ring buffer
58 
59   while (ringbuffer_available(buffer) <
60          (included_length + sizeof(btsnooz_header_t))) {
61     ringbuffer_pop(buffer, (uint8_t*)&header, sizeof(btsnooz_header_t));
62     ringbuffer_delete(buffer, header.length - 1);
63   }
64 
65   // Insert data
66   header.type = REDUCE_HCI_TYPE_TO_SIGNIFICANT_BITS(type);
67   header.length = included_length + 1;  // +1 for type byte
68   header.packet_length = length + 1;    // +1 for type byte.
69   header.delta_time_ms =
70       last_timestamp_ms ? timestamp_us - last_timestamp_ms : 0;
71   last_timestamp_ms = timestamp_us;
72 
73   ringbuffer_insert(buffer, (uint8_t*)&header, sizeof(btsnooz_header_t));
74   ringbuffer_insert(buffer, data, included_length);
75 }
76 
btsnoop_calculate_packet_length(uint16_t type,const uint8_t * data,size_t length)77 static size_t btsnoop_calculate_packet_length(uint16_t type,
78                                               const uint8_t* data,
79                                               size_t length) {
80   static const size_t HCI_ACL_HEADER_SIZE = 4;
81   static const size_t L2CAP_HEADER_SIZE = 4;
82   static const size_t L2CAP_CID_OFFSET = (HCI_ACL_HEADER_SIZE + 2);
83   static const uint16_t L2CAP_SIGNALING_CID = 0x0001;
84 
85   static const size_t HCI_ACL_HANDLE_OFFSET = 0;
86   static const uint16_t QUALCOMM_DEBUG_LOG_HANDLE = 0xedc;
87 
88   // Maximum amount of ACL data to log.
89   // Enough for an RFCOMM frame up to the frame check;
90   // not enough for a HID report or audio data.
91   static const size_t MAX_HCI_ACL_LEN = 14;
92 
93   // Calculate packet length to be included
94 
95   switch (type) {
96     case BT_EVT_TO_LM_HCI_CMD:
97       return length;
98 
99     case BT_EVT_TO_BTU_HCI_EVT:
100       return length;
101 
102     case BT_EVT_TO_LM_HCI_ACL:
103     case BT_EVT_TO_BTU_HCI_ACL: {
104       size_t len_hci_acl = HCI_ACL_HEADER_SIZE + L2CAP_HEADER_SIZE;
105       // Check if we have enough data for an L2CAP header
106       if (length > len_hci_acl) {
107         uint16_t l2cap_cid =
108             data[L2CAP_CID_OFFSET] | (data[L2CAP_CID_OFFSET + 1] << 8);
109         uint16_t hci_acl_packet_handle = data[HCI_ACL_HANDLE_OFFSET] |
110                                          (data[HCI_ACL_HANDLE_OFFSET + 1] << 8);
111         hci_acl_packet_handle &= 0x0FFF;
112 
113         if (l2cap_cid == L2CAP_SIGNALING_CID) {
114           // For the signaling CID, take the full packet.
115           // That way, the PSM setup is captured, allowing decoding of PSMs down
116           // the road.
117           return length;
118         } else if (qualcomm_debug_log_enable &&
119                    hci_acl_packet_handle == QUALCOMM_DEBUG_LOG_HANDLE) {
120           // For the enhanced controller debug log, take the full packet.
121           return length;
122         } else {
123           // Otherwise, return as much as we reasonably can
124           len_hci_acl = MAX_HCI_ACL_LEN;
125         }
126       }
127       return len_hci_acl < length ? len_hci_acl : length;
128     }
129 
130     case BT_EVT_TO_LM_HCI_ISO:
131     case BT_EVT_TO_BTU_HCI_ISO:
132       return length;
133 
134     case BT_EVT_TO_LM_HCI_SCO:
135     case BT_EVT_TO_BTU_HCI_SCO:
136       // We're not logging SCO packets at this time since they are not currently
137       // used.
138       FALLTHROUGH_INTENDED; /* FALLTHROUGH */
139     default:
140       return 0;
141   }
142 }
143 
btif_debug_btsnoop_init(void)144 void btif_debug_btsnoop_init(void) {
145   if (buffer == NULL) buffer = ringbuffer_init(BTSNOOP_MEM_BUFFER_SIZE);
146   btsnoop_mem_set_callback(btsnoop_cb);
147 
148   char value[PROPERTY_VALUE_MAX] = {0};
149   int ret = osi_property_get("ro.soc.manufacturer", value, "");
150   if (ret > 0 && strncmp(value, "Qualcomm", ret) == 0) {
151     qualcomm_debug_log_enable = true;
152   }
153 }
154 
155 #ifndef OS_ANDROID
btif_debug_btsnoop_dump(int fd)156 void btif_debug_btsnoop_dump(int fd) {}
157 #else
158 
159 // Block size for copying buffers (for compression/encoding etc.)
160 static constexpr size_t BLOCK_SIZE = 16384;
161 
btsnoop_compress(ringbuffer_t * rb_dst,ringbuffer_t * rb_src)162 static bool btsnoop_compress(ringbuffer_t* rb_dst, ringbuffer_t* rb_src) {
163   CHECK(rb_dst != NULL);
164   CHECK(rb_src != NULL);
165 
166   z_stream zs;
167   zs.zalloc = Z_NULL;
168   zs.zfree = Z_NULL;
169   zs.opaque = Z_NULL;
170 
171   if (deflateInit(&zs, Z_DEFAULT_COMPRESSION) != Z_OK) return false;
172 
173   bool rc = true;
174   uint8_t block_src[BLOCK_SIZE];
175   uint8_t block_dst[BLOCK_SIZE];
176 
177   const size_t num_blocks =
178       (ringbuffer_size(rb_src) + BLOCK_SIZE - 1) / BLOCK_SIZE;
179   for (size_t i = 0; i < num_blocks; ++i) {
180     zs.avail_in =
181         ringbuffer_peek(rb_src, i * BLOCK_SIZE, block_src, BLOCK_SIZE);
182     zs.next_in = block_src;
183 
184     do {
185       zs.avail_out = BLOCK_SIZE;
186       zs.next_out = block_dst;
187 
188       int err = deflate(&zs, (i == num_blocks - 1) ? Z_FINISH : Z_NO_FLUSH);
189       if (err == Z_STREAM_ERROR) {
190         rc = false;
191         break;
192       }
193 
194       const size_t length = BLOCK_SIZE - zs.avail_out;
195       ringbuffer_insert(rb_dst, block_dst, length);
196     } while (zs.avail_out == 0);
197   }
198 
199   deflateEnd(&zs);
200   return rc;
201 }
202 
btif_debug_btsnoop_dump(int fd)203 void btif_debug_btsnoop_dump(int fd) {
204   ringbuffer_t* ringbuffer = ringbuffer_init(BTSNOOP_MEM_BUFFER_SIZE);
205   if (ringbuffer == NULL) {
206     dprintf(fd, "%s Unable to allocate memory for compression", __func__);
207     return;
208   }
209 
210   // Prepend preamble
211 
212   btsnooz_preamble_t preamble;
213   preamble.version = BTSNOOZ_CURRENT_VERSION;
214   preamble.last_timestamp_ms = last_timestamp_ms;
215   ringbuffer_insert(ringbuffer, (uint8_t*)&preamble,
216                     sizeof(btsnooz_preamble_t));
217 
218   // Compress data
219 
220   uint8_t b64_in[3] = {0};
221   char b64_out[5] = {0};
222 
223   size_t line_length = 0;
224 
225   bool rc;
226   {
227     std::lock_guard<std::mutex> lock(buffer_mutex);
228     dprintf(fd, "--- BEGIN:BTSNOOP_LOG_SUMMARY (%zu bytes in) ---\n",
229             ringbuffer_size(buffer));
230     rc = btsnoop_compress(ringbuffer, buffer);
231   }
232 
233   if (!rc) {
234     dprintf(fd, "%s Log compression failed", __func__);
235     goto error;
236   }
237 
238   // Base64 encode & output
239 
240   while (ringbuffer_size(ringbuffer) > 0) {
241     size_t read = ringbuffer_pop(ringbuffer, b64_in, 3);
242     // Maximum line length in bugreport (should be multiple of 4 for base64
243     // output)
244     constexpr uint8_t MAX_LINE_LENGTH = 128;
245     if (line_length >= MAX_LINE_LENGTH) {
246       dprintf(fd, "\n");
247       line_length = 0;
248     }
249     line_length += b64_ntop(b64_in, read, b64_out, 5);
250     dprintf(fd, "%s", b64_out);
251   }
252 
253   dprintf(fd, "\n--- END:BTSNOOP_LOG_SUMMARY ---\n");
254 
255 error:
256   ringbuffer_free(ringbuffer);
257 }
258 #endif
259