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