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 <android-base/logging.h>
20 #include <android-base/stringprintf.h>
21 #include <resolv.h>
22 #include <zlib.h>
23 #include <mutex>
24 
25 #include <ringbuffer.h>
26 
27 #include <cutils/properties.h>
28 #include <fcntl.h>
29 #include <sys/stat.h>
30 
31 #include "bt_types.h"
32 #include "include/debug_nfcsnoop.h"
33 #include "nfc_int.h"
34 
35 #define USEC_PER_SEC 1000000ULL
36 
37 #define DEFAULT_NFCSNOOP_PATH "/data/misc/nfc/logs/nfcsnoop_nci_logs"
38 #define DEFAULT_NFCSNOOP_FILE_SIZE 32 * 1024 * 1024
39 
40 // Total nfcsnoop memory log buffer size
41 #ifndef NFCSNOOP_MEM_BUFFER_SIZE
42 static const size_t NFCSNOOP_MEM_BUFFER_SIZE = (256 * 1024);
43 #endif
44 
45 #define NFCSNOOP_MEM_BUFFER_THRESHOLD 1024
46 
47 // Block size for copying buffers (for compression/encoding etc.)
48 static const size_t BLOCK_SIZE = 16384;
49 
50 // Maximum line length in bugreport (should be multiple of 4 for base64 output)
51 static const uint8_t MAX_LINE_LENGTH = 128;
52 
53 static std::mutex buffer_mutex;
54 static ringbuffer_t* buffer = nullptr;
55 static uint64_t last_timestamp_ms = 0;
56 static bool isDebuggable = false;
57 
58 using android::base::StringPrintf;
59 
nfcsnoop_cb(const uint8_t * data,const size_t length,bool is_received,const uint64_t timestamp_us)60 static void nfcsnoop_cb(const uint8_t* data, const size_t length,
61                         bool is_received, const uint64_t timestamp_us) {
62   nfcsnooz_header_t header;
63 
64   std::lock_guard<std::mutex> lock(buffer_mutex);
65 
66   // Make room in the ring buffer
67 
68   while (ringbuffer_available(buffer) < (length + sizeof(nfcsnooz_header_t))) {
69     ringbuffer_pop(buffer, (uint8_t*)&header, sizeof(nfcsnooz_header_t));
70     ringbuffer_delete(buffer, header.length);
71   }
72 
73   // Insert data
74   header.length = length;
75   header.is_received = is_received ? 1 : 0;
76 
77   uint64_t delta_time_ms = 0;
78   if (last_timestamp_ms) {
79     __builtin_sub_overflow(timestamp_us, last_timestamp_ms, &delta_time_ms);
80   }
81   header.delta_time_ms = delta_time_ms;
82 
83   last_timestamp_ms = timestamp_us;
84 
85   ringbuffer_insert(buffer, (uint8_t*)&header, sizeof(nfcsnooz_header_t));
86   ringbuffer_insert(buffer, data, length);
87 }
88 
nfcsnoop_compress(ringbuffer_t * rb_dst,ringbuffer_t * rb_src)89 static bool nfcsnoop_compress(ringbuffer_t* rb_dst, ringbuffer_t* rb_src) {
90   CHECK(rb_dst != nullptr);
91   CHECK(rb_src != nullptr);
92 
93   z_stream zs;
94   zs.zalloc = Z_NULL;
95   zs.zfree = Z_NULL;
96   zs.opaque = Z_NULL;
97 
98   if (deflateInit(&zs, Z_DEFAULT_COMPRESSION) != Z_OK) return false;
99 
100   bool rc = true;
101   std::unique_ptr<uint8_t> block_src(new uint8_t[BLOCK_SIZE]);
102   std::unique_ptr<uint8_t> block_dst(new uint8_t[BLOCK_SIZE]);
103 
104   const size_t num_blocks =
105       (ringbuffer_size(rb_src) + BLOCK_SIZE - 1) / BLOCK_SIZE;
106   for (size_t i = 0; i < num_blocks; ++i) {
107     zs.avail_in =
108         ringbuffer_peek(rb_src, i * BLOCK_SIZE, block_src.get(), BLOCK_SIZE);
109     zs.next_in = block_src.get();
110 
111     do {
112       zs.avail_out = BLOCK_SIZE;
113       zs.next_out = block_dst.get();
114 
115       int err = deflate(&zs, (i == num_blocks - 1) ? Z_FINISH : Z_NO_FLUSH);
116       if (err == Z_STREAM_ERROR) {
117         rc = false;
118         break;
119       }
120       const size_t length = BLOCK_SIZE - zs.avail_out;
121       ringbuffer_insert(rb_dst, block_dst.get(), length);
122     } while (zs.avail_out == 0);
123   }
124 
125   deflateEnd(&zs);
126   return rc;
127 }
128 
nfcsnoop_capture(const NFC_HDR * packet,bool is_received)129 void nfcsnoop_capture(const NFC_HDR* packet, bool is_received) {
130   struct timeval tv;
131   gettimeofday(&tv, nullptr);
132   uint64_t timestamp = static_cast<uint64_t>(tv.tv_sec) * USEC_PER_SEC +
133                        static_cast<uint64_t>(tv.tv_usec);
134   uint8_t* p = (uint8_t*)(packet + 1) + packet->offset;
135   uint8_t mt = (*(p)&NCI_MT_MASK) >> NCI_MT_SHIFT;
136   if (isDebuggable &&
137       ringbuffer_available(buffer) < NFCSNOOP_MEM_BUFFER_THRESHOLD) {
138     if (storeNfcSnoopLogs(DEFAULT_NFCSNOOP_PATH, DEFAULT_NFCSNOOP_FILE_SIZE)) {
139       std::lock_guard<std::mutex> lock(buffer_mutex);
140       // Free the buffer after the content is stored in log file
141       ringbuffer_free(buffer);
142       buffer = nullptr;
143       // Allocate new buffer to store new NCI logs
144       debug_nfcsnoop_init();
145     }
146   }
147   if (mt == NCI_MT_DATA) {
148     nfcsnoop_cb(p, NCI_DATA_HDR_SIZE, is_received, timestamp);
149   } else if (packet->len > 2) {
150     nfcsnoop_cb(p, p[2] + NCI_MSG_HDR_SIZE, is_received, timestamp);
151   }
152 }
153 
debug_nfcsnoop_init(void)154 void debug_nfcsnoop_init(void) {
155   if (buffer == nullptr) buffer = ringbuffer_init(NFCSNOOP_MEM_BUFFER_SIZE);
156   isDebuggable = property_get_int32("ro.debuggable", 0);
157 }
158 
debug_nfcsnoop_dump(int fd)159 void debug_nfcsnoop_dump(int fd) {
160   if (buffer == nullptr) {
161     dprintf(fd, "%s Nfcsnoop is not ready\n", __func__);
162     return;
163   }
164   ringbuffer_t* ringbuffer = ringbuffer_init(NFCSNOOP_MEM_BUFFER_SIZE);
165   if (ringbuffer == nullptr) {
166     dprintf(fd, "%s Unable to allocate memory for compression", __func__);
167     return;
168   }
169 
170   // Prepend preamble
171 
172   nfcsnooz_preamble_t preamble;
173   preamble.version = NFCSNOOZ_CURRENT_VERSION;
174   preamble.last_timestamp_ms = last_timestamp_ms;
175   ringbuffer_insert(ringbuffer, (uint8_t*)&preamble,
176                     sizeof(nfcsnooz_preamble_t));
177 
178   // Compress data
179 
180   uint8_t b64_in[3] = {0};
181   char b64_out[5] = {0};
182 
183   size_t line_length = 0;
184 
185   bool rc;
186   {
187     std::lock_guard<std::mutex> lock(buffer_mutex);
188     dprintf(fd, "--- BEGIN:NFCSNOOP_LOG_SUMMARY (%zu bytes in) ---\n",
189             ringbuffer_size(buffer));
190     rc = nfcsnoop_compress(ringbuffer, buffer);
191   }
192 
193   if (rc == false) {
194     dprintf(fd, "%s Log compression failed", __func__);
195     goto error;
196   }
197 
198   // Base64 encode & output
199 
200   while (ringbuffer_size(ringbuffer) > 0) {
201     size_t read = ringbuffer_pop(ringbuffer, b64_in, 3);
202     if (line_length >= MAX_LINE_LENGTH) {
203       dprintf(fd, "\n");
204       line_length = 0;
205     }
206     line_length += b64_ntop(b64_in, read, b64_out, 5);
207     dprintf(fd, "%s", b64_out);
208   }
209 
210   dprintf(fd, "\n--- END:NFCSNOOP_LOG_SUMMARY ---\n");
211 
212 error:
213   ringbuffer_free(ringbuffer);
214 }
215 
storeNfcSnoopLogs(std::string filepath,off_t maxFileSize)216 bool storeNfcSnoopLogs(std::string filepath, off_t maxFileSize) {
217   int fileStream;
218   off_t fileSize;
219   // check file size
220   struct stat st;
221   if (stat(filepath.c_str(), &st) == 0) {
222     fileSize = st.st_size;
223   } else {
224     fileSize = 0;
225   }
226 
227   mode_t prevmask = umask(0);
228   if (fileSize >= maxFileSize) {
229     fileStream = open(filepath.c_str(), O_RDWR | O_CREAT | O_TRUNC,
230                       S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
231   } else {
232     fileStream = open(filepath.c_str(), O_RDWR | O_CREAT | O_APPEND,
233                       S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
234   }
235   umask(prevmask);
236 
237   if (fileStream >= 0) {
238     debug_nfcsnoop_dump(fileStream);
239     close(fileStream);
240     return true;
241   } else {
242     LOG(ERROR) << StringPrintf("%s: fail to create, error = %d", __func__,
243                                errno);
244     return false;
245   }
246 }
247