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 && ringbuffer_available(buffers[SYSTEM_BUFFER_INDEX]) <
156 NFCSNOOP_MEM_BUFFER_THRESHOLD) {
157 if (storeNfcSnoopLogs(DEFAULT_NFCSNOOP_PATH, DEFAULT_NFCSNOOP_FILE_SIZE)) {
158 std::lock_guard<std::mutex> lock(buffer_mutex);
159 // Free the buffer after the content is stored in log file
160 ringbuffer_free(buffers[SYSTEM_BUFFER_INDEX]);
161 buffers[SYSTEM_BUFFER_INDEX] = nullptr;
162 // Allocate new buffer to store new NCI logs
163 debug_nfcsnoop_init();
164 }
165 }
166
167 if (mt == NCI_MT_NTF && gid == NCI_GID_PROP) {
168 nfcsnoop_cb(p, p[2] + NCI_MSG_HDR_SIZE, is_received, timestamp,
169 VENDOR_BUFFER_INDEX);
170 } else if (mt == NCI_MT_DATA) {
171 nfcsnoop_cb(p,
172 isFullNfcSnoop ? p[2] + NCI_DATA_HDR_SIZE : NCI_DATA_HDR_SIZE,
173 is_received, timestamp, SYSTEM_BUFFER_INDEX);
174 } else if (packet->len > 2) {
175 nfcsnoop_cb(p, p[2] + NCI_MSG_HDR_SIZE, is_received, timestamp,
176 SYSTEM_BUFFER_INDEX);
177 }
178 }
179
debug_nfcsnoop_init(void)180 void debug_nfcsnoop_init(void) {
181 for (size_t buffer_index = 0; buffer_index < BUFFER_SIZE; ++buffer_index) {
182 if (buffers[buffer_index] == nullptr) {
183 buffers[buffer_index] = ringbuffer_init(NFCSNOOP_MEM_BUFFER_SIZE);
184 }
185 }
186 isDebuggable = property_get_int32("ro.debuggable", 0);
187 isFullNfcSnoop = android::base::GetProperty(NFCSNOOP_LOG_MODE_PROPERTY, "")
188 .compare(NFCSNOOP_MODE_FULL)
189 ? false
190 : true;
191 }
192
debug_nfcsnoop_dump(int fd)193 void debug_nfcsnoop_dump(int fd) {
194 for (size_t buffer_index = 0; buffer_index < BUFFER_SIZE; ++buffer_index) {
195 if (buffers[buffer_index] == nullptr) {
196 dprintf(fd, "%s Nfcsnoop is not ready (%s)\n", __func__,
197 BUFFER_NAMES[buffer_index]);
198 return;
199 }
200 }
201 ringbuffer_t* ringbuffers[BUFFER_SIZE];
202 for (size_t buffer_index = 0; buffer_index < BUFFER_SIZE; ++buffer_index) {
203 ringbuffers[buffer_index] = ringbuffer_init(NFCSNOOP_MEM_BUFFER_SIZE);
204 if (ringbuffers[buffer_index] == nullptr) {
205 dprintf(fd, "%s Unable to allocate memory for compression (%s)", __func__,
206 BUFFER_NAMES[buffer_index]);
207 for (size_t previous_index = 0; previous_index < buffer_index;
208 ++previous_index) {
209 ringbuffer_free(ringbuffers[previous_index]);
210 }
211 return;
212 }
213 }
214
215 // Compress data
216
217 for (size_t buffer_index = 0; buffer_index < BUFFER_SIZE; ++buffer_index) {
218 // Prepend preamble
219
220 nfcsnooz_preamble_t preamble;
221 preamble.version = NFCSNOOZ_CURRENT_VERSION;
222 preamble.last_timestamp_ms = last_timestamp_ms[buffer_index];
223
224 ringbuffer_insert(ringbuffers[buffer_index], (uint8_t*)&preamble,
225 sizeof(nfcsnooz_preamble_t));
226
227 uint8_t b64_in[3] = {0};
228 char b64_out[5] = {0};
229
230 size_t line_length = 0;
231
232 bool rc;
233 {
234 std::lock_guard<std::mutex> lock(buffer_mutex);
235 dprintf(fd, "--- BEGIN:NFCSNOOP_%s (%zu bytes in) ---\n",
236 BUFFER_NAMES[buffer_index],
237 ringbuffer_size(buffers[buffer_index]));
238 rc = nfcsnoop_compress(ringbuffers[buffer_index], buffers[buffer_index]);
239 }
240
241 if (rc == false) {
242 dprintf(fd, "%s Log compression failed (%s)", __func__,
243 BUFFER_NAMES[buffer_index]);
244 goto error;
245 }
246
247 // Base64 encode & output
248
249 while (ringbuffer_size(ringbuffers[buffer_index]) > 0) {
250 size_t read = ringbuffer_pop(ringbuffers[buffer_index], b64_in, 3);
251 if (line_length >= MAX_LINE_LENGTH) {
252 dprintf(fd, "\n");
253 line_length = 0;
254 }
255 line_length += b64_ntop(b64_in, read, b64_out, 5);
256 dprintf(fd, "%s", b64_out);
257 }
258
259 dprintf(fd, "\n--- END:NFCSNOOP_%s ---\n", BUFFER_NAMES[buffer_index]);
260 }
261
262 error:
263 for (size_t buffer_index = 0; buffer_index < BUFFER_SIZE; ++buffer_index) {
264 ringbuffer_free(ringbuffers[buffer_index]);
265 }
266 }
267
storeNfcSnoopLogs(std::string filepath,off_t maxFileSize)268 bool storeNfcSnoopLogs(std::string filepath, off_t maxFileSize) {
269 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
270 return true;
271 #endif
272
273 int fileStream;
274 off_t fileSize;
275 // check file size
276 struct stat st;
277 if (stat(filepath.c_str(), &st) == 0) {
278 fileSize = st.st_size;
279 } else {
280 fileSize = 0;
281 }
282
283 mode_t prevmask = umask(0);
284 if (fileSize >= maxFileSize) {
285 fileStream = open(filepath.c_str(), O_RDWR | O_CREAT | O_TRUNC,
286 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
287 } else {
288 fileStream = open(filepath.c_str(), O_RDWR | O_CREAT | O_APPEND,
289 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
290 }
291 umask(prevmask);
292
293 if (fileStream >= 0) {
294 debug_nfcsnoop_dump(fileStream);
295 close(fileStream);
296 return true;
297 } else {
298 LOG(ERROR) << StringPrintf("%s: fail to create, error = %d", __func__,
299 errno);
300 return false;
301 }
302 }
303