1 /******************************************************************************
2 *
3 * Copyright (C) 2017 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 "include/debug_nfcsnoop.h"
20
21 #include <android-base/logging.h>
22 #include <android-base/properties.h>
23 #include <android-base/stringprintf.h>
24 #include <cutils/properties.h>
25 #include <fcntl.h>
26 #include <resolv.h>
27 #include <ringbuffer.h>
28 #include <sys/stat.h>
29 #include <sys/time.h>
30 #include <zlib.h>
31
32 #include <mutex>
33
34 #include "bt_types.h"
35 #include "nfc_int.h"
36
37 #define USEC_PER_SEC 1000000ULL
38
39 #define DEFAULT_NFCSNOOP_PATH "/data/misc/nfc/logs/nfcsnoop_nci_logs"
40
41 #define NFCSNOOP_LOG_MODE_PROPERTY "persist.nfc.snoop_log_mode"
42 #define NFCSNOOP_MODE_FILTERED "filtered"
43 #define NFCSNOOP_MODE_FULL "full"
44
45 #define MICRO_SECOND_THREE_DAYS 3 * 24 * 60 * 60 * 1000 * 1000
46
47 // Total nfcsnoop memory log buffer size
48 #ifndef NFCSNOOP_MEM_BUFFER_SIZE
49 static const size_t NFCSNOOP_MEM_BUFFER_SIZE = (256 * 1024);
50 #endif
51
52 #define NFCSNOOP_MEM_BUFFER_THRESHOLD 1024
53
54 // Block size for copying buffers (for compression/encoding etc.)
55 static const size_t BLOCK_SIZE = 16384;
56
57 // Maximum line length in bugreport (should be multiple of 4 for base64 output)
58 static const uint8_t MAX_LINE_LENGTH = 128;
59
60 static const size_t BUFFER_SIZE = 2;
61 static const size_t SYSTEM_BUFFER_INDEX = 0;
62 static const size_t VENDOR_BUFFER_INDEX = 1;
63 static const char* BUFFER_NAMES[BUFFER_SIZE] = {"LOG_SUMMARY",
64 "VS_LOG_SUMMARY"};
65
66 // When the time diff larger than UINT32_MAX, fill in blank NCI in between
67 static const uint8_t EMPTY_NCI[BUFFER_SIZE][5] = {
68 {0x6F, NCI_MSG_PROP_ANDROID, 0x02, NCI_ANDROID_BLANK_NCI,
69 NCI_ANDROID_BLANK_COMMON},
70 {0x6F, NCI_MSG_PROP_ANDROID, 0x02, NCI_ANDROID_BLANK_NCI,
71 NCI_ANDROID_BLANK_VENDOR}};
72
73 // When the time diff is too large, fill in one blank NCI with error in between
74 static const uint8_t EMPTY_ERR_NCI[BUFFER_SIZE][5] = {
75 {0x6F, NCI_MSG_PROP_ANDROID, 0x02, NCI_ANDROID_BLANK_NCI,
76 NCI_ANDROID_BLANK_COMMON_ERROR},
77 {0x6F, NCI_MSG_PROP_ANDROID, 0x02, NCI_ANDROID_BLANK_NCI,
78 NCI_ANDROID_BLANK_VENDOR_ERROR}};
79
80 static std::mutex buffer_mutex;
81 static ringbuffer_t* buffers[BUFFER_SIZE] = {nullptr, nullptr};
82 static uint64_t last_timestamp_ms[BUFFER_SIZE] = {0, 0};
83 static bool isDebuggable = false;
84 static bool isFullNfcSnoop = false;
85
86 using android::base::StringPrintf;
87
nfcsnoop_cb(const uint8_t * data,const size_t length,bool is_received,const uint64_t timestamp_us,size_t buffer_index)88 static void nfcsnoop_cb(const uint8_t* data, const size_t length,
89 bool is_received, const uint64_t timestamp_us,
90 size_t buffer_index) {
91 nfcsnooz_header_t header;
92 bool err = false;
93 uint64_t delta_time_ms = 0;
94
95 if (last_timestamp_ms[buffer_index] > timestamp_us) {
96 LOG(ERROR) << StringPrintf("%s: Timestamp error!", __func__);
97 err = true;
98 } else if (last_timestamp_ms[buffer_index]) {
99 __builtin_sub_overflow(timestamp_us, last_timestamp_ms[buffer_index],
100 &delta_time_ms);
101 }
102
103 if (delta_time_ms > (uint64_t)MICRO_SECOND_THREE_DAYS || err) {
104 LOG(ERROR) << StringPrintf(
105 "%s: Reset last timestamp and add empty nci to "
106 "snoop buffer %zu with error",
107 __func__, buffer_index);
108 last_timestamp_ms[buffer_index] = timestamp_us;
109 nfcsnoop_cb(EMPTY_ERR_NCI[buffer_index],
110 EMPTY_ERR_NCI[buffer_index][2] + NCI_MSG_HDR_SIZE, true,
111 timestamp_us, buffer_index);
112 delta_time_ms = 0;
113 }
114
115 while (delta_time_ms > UINT32_MAX) {
116 uint64_t middle_time = last_timestamp_ms[buffer_index] + UINT32_MAX;
117 LOG(WARNING) << StringPrintf("%s: Add empty nci to snoop buffer %zu",
118 __func__, buffer_index);
119 nfcsnoop_cb(EMPTY_NCI[buffer_index],
120 EMPTY_NCI[buffer_index][2] + NCI_MSG_HDR_SIZE, true,
121 middle_time, buffer_index);
122 if (last_timestamp_ms[buffer_index]) {
123 __builtin_sub_overflow(timestamp_us, last_timestamp_ms[buffer_index],
124 &delta_time_ms);
125 }
126 }
127
128 // Make room in the ring buffer
129
130 while (ringbuffer_available(buffers[buffer_index]) <
131 (length + sizeof(nfcsnooz_header_t))) {
132 ringbuffer_pop(buffers[buffer_index], (uint8_t*)&header,
133 sizeof(nfcsnooz_header_t));
134 ringbuffer_delete(buffers[buffer_index], header.length);
135 }
136
137 // Insert data
138 header.length = length;
139 header.is_received = is_received ? 1 : 0;
140
141 // Note: casting uint64 to uint32
142 header.delta_time_ms = delta_time_ms;
143
144 last_timestamp_ms[buffer_index] = timestamp_us;
145
146 ringbuffer_insert(buffers[buffer_index], (uint8_t*)&header,
147 sizeof(nfcsnooz_header_t));
148 ringbuffer_insert(buffers[buffer_index], data, length);
149 }
150
nfcsnoop_cb_locked(const uint8_t * data,const size_t length,bool is_received,const uint64_t timestamp_us,size_t buffer_index)151 static void nfcsnoop_cb_locked(const uint8_t* data, const size_t length,
152 bool is_received, const uint64_t timestamp_us,
153 size_t buffer_index) {
154 std::lock_guard<std::mutex> lock(buffer_mutex);
155 nfcsnoop_cb(data, length, is_received, timestamp_us, buffer_index);
156 }
157
nfcsnoop_compress(ringbuffer_t * rb_dst,ringbuffer_t * rb_src)158 static bool nfcsnoop_compress(ringbuffer_t* rb_dst, ringbuffer_t* rb_src) {
159 CHECK(rb_dst != nullptr);
160 CHECK(rb_src != nullptr);
161
162 z_stream zs;
163 zs.zalloc = Z_NULL;
164 zs.zfree = Z_NULL;
165 zs.opaque = Z_NULL;
166
167 if (deflateInit(&zs, Z_DEFAULT_COMPRESSION) != Z_OK) return false;
168
169 bool rc = true;
170 std::unique_ptr<uint8_t> block_src(new uint8_t[BLOCK_SIZE]);
171 std::unique_ptr<uint8_t> block_dst(new uint8_t[BLOCK_SIZE]);
172
173 const size_t num_blocks =
174 (ringbuffer_size(rb_src) + BLOCK_SIZE - 1) / BLOCK_SIZE;
175 for (size_t i = 0; i < num_blocks; ++i) {
176 zs.avail_in =
177 ringbuffer_peek(rb_src, i * BLOCK_SIZE, block_src.get(), BLOCK_SIZE);
178 zs.next_in = block_src.get();
179
180 do {
181 zs.avail_out = BLOCK_SIZE;
182 zs.next_out = block_dst.get();
183
184 int err = deflate(&zs, (i == num_blocks - 1) ? Z_FINISH : Z_NO_FLUSH);
185 if (err == Z_STREAM_ERROR) {
186 rc = false;
187 break;
188 }
189 const size_t length = BLOCK_SIZE - zs.avail_out;
190 ringbuffer_insert(rb_dst, block_dst.get(), length);
191 } while (zs.avail_out == 0);
192 }
193
194 deflateEnd(&zs);
195 return rc;
196 }
197
nfcsnoop_capture(const NFC_HDR * packet,bool is_received)198 void nfcsnoop_capture(const NFC_HDR* packet, bool is_received) {
199 struct timeval tv;
200 gettimeofday(&tv, nullptr);
201 uint64_t timestamp = static_cast<uint64_t>(tv.tv_sec) * USEC_PER_SEC +
202 static_cast<uint64_t>(tv.tv_usec);
203 uint8_t* p = (uint8_t*)(packet + 1) + packet->offset;
204 uint8_t mt = (*(p)&NCI_MT_MASK) >> NCI_MT_SHIFT;
205 uint8_t gid = *(p)&NCI_GID_MASK;
206 if (isDebuggable && buffers_under_threshold()) {
207 if (storeNfcSnoopLogs(DEFAULT_NFCSNOOP_PATH, DEFAULT_NFCSNOOP_FILE_SIZE)) {
208 std::lock_guard<std::mutex> lock(buffer_mutex);
209 // Free the buffer after the content is stored in log file
210 ringbuffer_free(buffers[SYSTEM_BUFFER_INDEX]);
211 buffers[SYSTEM_BUFFER_INDEX] = nullptr;
212 ringbuffer_free(buffers[VENDOR_BUFFER_INDEX]);
213 buffers[VENDOR_BUFFER_INDEX] = nullptr;
214 // Allocate new buffer to store new NCI logs
215 debug_nfcsnoop_init();
216 }
217 }
218
219 if (mt == NCI_MT_NTF && gid == NCI_GID_PROP) {
220 nfcsnoop_cb_locked(p, p[2] + NCI_MSG_HDR_SIZE, is_received, timestamp,
221 VENDOR_BUFFER_INDEX);
222 } else if (mt == NCI_MT_DATA) {
223 nfcsnoop_cb_locked(
224 p, isFullNfcSnoop ? p[2] + NCI_DATA_HDR_SIZE : NCI_DATA_HDR_SIZE,
225 is_received, timestamp, SYSTEM_BUFFER_INDEX);
226 } else if (packet->len > 2) {
227 nfcsnoop_cb_locked(p, p[2] + NCI_MSG_HDR_SIZE, is_received, timestamp,
228 SYSTEM_BUFFER_INDEX);
229 }
230 }
231
debug_nfcsnoop_init(void)232 void debug_nfcsnoop_init(void) {
233 for (size_t buffer_index = 0; buffer_index < BUFFER_SIZE; ++buffer_index) {
234 if (buffers[buffer_index] == nullptr) {
235 buffers[buffer_index] = ringbuffer_init(NFCSNOOP_MEM_BUFFER_SIZE);
236 }
237 }
238 isDebuggable = property_get_int32("ro.debuggable", 0);
239 isFullNfcSnoop = android::base::GetProperty(NFCSNOOP_LOG_MODE_PROPERTY, "")
240 .compare(NFCSNOOP_MODE_FULL)
241 ? false
242 : true;
243 }
244
debug_nfcsnoop_dump(int fd)245 void debug_nfcsnoop_dump(int fd) {
246 for (size_t buffer_index = 0; buffer_index < BUFFER_SIZE; ++buffer_index) {
247 if (buffers[buffer_index] == nullptr) {
248 dprintf(fd, "%s Nfcsnoop is not ready (%s)\n", __func__,
249 BUFFER_NAMES[buffer_index]);
250 return;
251 }
252 }
253 ringbuffer_t* ringbuffers[BUFFER_SIZE];
254 for (size_t buffer_index = 0; buffer_index < BUFFER_SIZE; ++buffer_index) {
255 ringbuffers[buffer_index] = ringbuffer_init(NFCSNOOP_MEM_BUFFER_SIZE);
256 if (ringbuffers[buffer_index] == nullptr) {
257 dprintf(fd, "%s Unable to allocate memory for compression (%s)", __func__,
258 BUFFER_NAMES[buffer_index]);
259 for (size_t previous_index = 0; previous_index < buffer_index;
260 ++previous_index) {
261 ringbuffer_free(ringbuffers[previous_index]);
262 }
263 return;
264 }
265 }
266
267 // Compress data
268
269 for (size_t buffer_index = 0; buffer_index < BUFFER_SIZE; ++buffer_index) {
270 // Prepend preamble
271
272 nfcsnooz_preamble_t preamble;
273 preamble.version = NFCSNOOZ_CURRENT_VERSION;
274 preamble.last_timestamp_ms = last_timestamp_ms[buffer_index];
275
276 ringbuffer_insert(ringbuffers[buffer_index], (uint8_t*)&preamble,
277 sizeof(nfcsnooz_preamble_t));
278
279 uint8_t b64_in[3] = {0};
280 char b64_out[5] = {0};
281
282 size_t line_length = 0;
283
284 bool rc;
285 {
286 std::lock_guard<std::mutex> lock(buffer_mutex);
287 dprintf(fd, "--- BEGIN:NFCSNOOP_%s (%zu bytes in) ---\n",
288 BUFFER_NAMES[buffer_index],
289 ringbuffer_size(buffers[buffer_index]));
290 rc = nfcsnoop_compress(ringbuffers[buffer_index], buffers[buffer_index]);
291 }
292
293 if (rc == false) {
294 dprintf(fd, "%s Log compression failed (%s)", __func__,
295 BUFFER_NAMES[buffer_index]);
296 goto error;
297 }
298
299 // Base64 encode & output
300
301 while (ringbuffer_size(ringbuffers[buffer_index]) > 0) {
302 size_t read = ringbuffer_pop(ringbuffers[buffer_index], b64_in, 3);
303 if (line_length >= MAX_LINE_LENGTH) {
304 dprintf(fd, "\n");
305 line_length = 0;
306 }
307 line_length += b64_ntop(b64_in, read, b64_out, 5);
308 dprintf(fd, "%s", b64_out);
309 }
310
311 dprintf(fd, "\n--- END:NFCSNOOP_%s ---\n", BUFFER_NAMES[buffer_index]);
312 }
313
314 error:
315 for (size_t buffer_index = 0; buffer_index < BUFFER_SIZE; ++buffer_index) {
316 ringbuffer_free(ringbuffers[buffer_index]);
317 }
318 }
319
storeNfcSnoopLogs(std::string filepath,off_t maxFileSize)320 bool storeNfcSnoopLogs(std::string filepath, off_t maxFileSize) {
321 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
322 return true;
323 #endif
324
325 int fileStream;
326 off_t fileSize;
327 // check file size
328 struct stat st;
329 if (stat(filepath.c_str(), &st) == 0) {
330 fileSize = st.st_size;
331 } else {
332 fileSize = 0;
333 }
334
335 mode_t prevmask = umask(0);
336 if (fileSize >= maxFileSize) {
337 fileStream = open(filepath.c_str(), O_RDWR | O_CREAT | O_TRUNC,
338 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
339 } else {
340 fileStream = open(filepath.c_str(), O_RDWR | O_CREAT | O_APPEND,
341 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
342 }
343 umask(prevmask);
344
345 if (fileStream >= 0) {
346 debug_nfcsnoop_dump(fileStream);
347 close(fileStream);
348 return true;
349 } else {
350 LOG(ERROR) << StringPrintf("%s: fail to create, error = %d", __func__,
351 errno);
352 return false;
353 }
354 }
355
buffers_under_threshold()356 bool buffers_under_threshold() {
357 return (ringbuffer_available(buffers[SYSTEM_BUFFER_INDEX]) <
358 NFCSNOOP_MEM_BUFFER_THRESHOLD ||
359 ringbuffer_available(buffers[VENDOR_BUFFER_INDEX]) <
360 NFCSNOOP_MEM_BUFFER_THRESHOLD);
361 }
362