blob: e96bd3d766667abd225b986367ec557564793e1b [file] [log] [blame]
mukesh agrawal63068972016-09-29 17:42:46 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
mukesh agrawalfd080642016-10-07 15:45:37 -070017#include <string.h>
18
mukesh agrawal93f78dc2016-10-13 16:07:40 -070019#include <algorithm>
mukesh agrawal63068972016-09-29 17:42:46 -070020#include <cinttypes>
mukesh agrawalfd080642016-10-07 15:45:37 -070021#include <string>
22#include <tuple>
mukesh agrawal63068972016-09-29 17:42:46 -070023#include <utility>
24
25#include "android-base/logging.h"
mukesh agrawalfd080642016-10-07 15:45:37 -070026#include "android-base/stringprintf.h"
mukesh agrawal63068972016-09-29 17:42:46 -070027
28#include "wifilogd/byte_buffer.h"
29#include "wifilogd/command_processor.h"
30#include "wifilogd/local_utils.h"
mukesh agrawal93f78dc2016-10-13 16:07:40 -070031#include "wifilogd/memory_reader.h"
mukesh agrawal63068972016-09-29 17:42:46 -070032#include "wifilogd/protocol.h"
33
34namespace android {
35namespace wifilogd {
36
mukesh agrawalcc8458a2016-10-06 15:45:35 -070037using ::android::base::unique_fd;
38
mukesh agrawal63068972016-09-29 17:42:46 -070039using local_utils::CopyFromBufferOrDie;
40using local_utils::GetMaxVal;
41
mukesh agrawalfd080642016-10-07 15:45:37 -070042namespace {
mukesh agrawal93f78dc2016-10-13 16:07:40 -070043
mukesh agrawal188f0472016-11-11 14:19:42 -080044uint32_t NsecToUsec(uint32_t nsec);
45
46class TimestampHeader {
47 public:
48 TimestampHeader& set_since_boot_awake_only(Os::Timestamp new_value) {
49 since_boot_awake_only = new_value;
50 return *this;
51 }
52
53 TimestampHeader& set_since_boot_with_sleep(Os::Timestamp new_value) {
54 since_boot_with_sleep = new_value;
55 return *this;
56 }
57
58 TimestampHeader& set_since_epoch(Os::Timestamp new_value) {
59 since_epoch = new_value;
60 return *this;
61 }
62
63 // Returns a string with a formatted representation of the timestamps
64 // contained within this header.
65 std::string ToString() const {
66 const auto& awake_time = since_boot_awake_only;
67 const auto& up_time = since_boot_with_sleep;
68 const auto& wall_time = since_epoch;
69 return base::StringPrintf("%" PRIu32 ".%06" PRIu32
70 " "
71 "%" PRIu32 ".%06" PRIu32
72 " "
73 "%" PRIu32 ".%06" PRIu32,
74 awake_time.secs, NsecToUsec(awake_time.nsecs),
75 up_time.secs, NsecToUsec(up_time.nsecs),
76 wall_time.secs, NsecToUsec(wall_time.nsecs));
77 }
78
79 Os::Timestamp since_boot_awake_only;
80 Os::Timestamp since_boot_with_sleep;
81 Os::Timestamp since_epoch; // non-monotonic
82};
83
mukesh agrawal93f78dc2016-10-13 16:07:40 -070084constexpr char kUnprintableCharReplacement = '?';
85
86std::string MakeSanitizedString(const uint8_t* buf, size_t buf_len);
87
88std::string GetStringFromMemoryReader(NONNULL MemoryReader* buffer_reader,
89 const size_t desired_len) {
90 constexpr char kBufferOverrunError[] = "[buffer-overrun]";
91 constexpr char kZeroLengthError[] = "[empty]";
92 if (!desired_len) {
mukesh agrawal82816d22016-10-27 14:18:29 -070093 // TODO(b/32098735): Increment stats counter.
mukesh agrawal93f78dc2016-10-13 16:07:40 -070094 return kZeroLengthError;
95 }
96
97 auto effective_len = desired_len;
98 if (buffer_reader->size() < effective_len) {
mukesh agrawal82816d22016-10-27 14:18:29 -070099 // TODO(b/32098735): Increment stats counter.
mukesh agrawal93f78dc2016-10-13 16:07:40 -0700100 effective_len = buffer_reader->size();
101 }
102
103 auto out = MakeSanitizedString(buffer_reader->GetBytesOrDie(effective_len),
104 effective_len);
105 if (effective_len < desired_len) {
106 out += kBufferOverrunError;
107 }
108
109 return out;
110}
111
112std::string MakeSanitizedString(const uint8_t* buf, size_t buf_len) {
113 std::string out(buf_len, '\0');
114 std::replace_copy_if(buf, buf + buf_len, &out.front(),
115 [](auto c) { return !local_utils::IsAsciiPrintable(c); },
116 kUnprintableCharReplacement);
117 return out;
118}
119
mukesh agrawalfd080642016-10-07 15:45:37 -0700120uint32_t NsecToUsec(uint32_t nsec) { return nsec / 1000; }
mukesh agrawal93f78dc2016-10-13 16:07:40 -0700121
mukesh agrawalfd080642016-10-07 15:45:37 -0700122} // namespace
123
mukesh agrawal63068972016-09-29 17:42:46 -0700124CommandProcessor::CommandProcessor(size_t buffer_size_bytes)
125 : current_log_buffer_(buffer_size_bytes), os_(new Os()) {}
126
127CommandProcessor::CommandProcessor(size_t buffer_size_bytes,
128 std::unique_ptr<Os> os)
129 : current_log_buffer_(buffer_size_bytes), os_(std::move(os)) {}
130
mukesh agrawal82816d22016-10-27 14:18:29 -0700131CommandProcessor::~CommandProcessor() {}
132
mukesh agrawalcc8458a2016-10-06 15:45:35 -0700133bool CommandProcessor::ProcessCommand(const void* input_buffer,
134 size_t n_bytes_read, int fd) {
135 unique_fd wrapped_fd(fd);
136
mukesh agrawal63068972016-09-29 17:42:46 -0700137 if (n_bytes_read < sizeof(protocol::Command)) {
mukesh agrawal82816d22016-10-27 14:18:29 -0700138 // TODO(b/32098735): Increment stats counter.
mukesh agrawal63068972016-09-29 17:42:46 -0700139 return false;
140 }
141
142 const auto& command_header =
143 CopyFromBufferOrDie<protocol::Command>(input_buffer, n_bytes_read);
144 switch (command_header.opcode) {
145 using protocol::Opcode;
146 case Opcode::kWriteAsciiMessage:
147 // Copy the entire command to the log. This defers the cost of
148 // validating the rest of the CommandHeader until we dump the
149 // message.
150 //
151 // Note that most messages will be written but never read. So, in
152 // the common case, the validation cost is actually eliminated,
153 // rather than just deferred.
154 return CopyCommandToLog(input_buffer, n_bytes_read);
mukesh agrawalfd080642016-10-07 15:45:37 -0700155 case Opcode::kDumpBuffers:
156 return Dump(std::move(wrapped_fd));
mukesh agrawal63068972016-09-29 17:42:46 -0700157 }
mukesh agrawalb0f1f442016-10-20 15:09:35 -0700158
159 LOG(DEBUG) << "Received unexpected opcode "
160 << local_utils::CastEnumToInteger(command_header.opcode);
mukesh agrawal82816d22016-10-27 14:18:29 -0700161 // TODO(b/32098735): Increment stats counter.
mukesh agrawalb0f1f442016-10-20 15:09:35 -0700162 return false;
mukesh agrawal63068972016-09-29 17:42:46 -0700163}
164
165// Private methods below.
166
167bool CommandProcessor::CopyCommandToLog(const void* command_buffer,
168 size_t command_len_in) {
169 const uint16_t command_len =
170 SAFELY_CLAMP(command_len_in, uint16_t, 0, protocol::kMaxMessageSize);
171
172 uint16_t total_size;
173 static_assert(GetMaxVal(total_size) > sizeof(TimestampHeader) &&
174 GetMaxVal(total_size) - sizeof(TimestampHeader) >=
175 protocol::kMaxMessageSize,
176 "total_size cannot represent some input messages");
177 total_size = sizeof(TimestampHeader) + command_len;
178 CHECK(current_log_buffer_.CanFitEver(total_size));
179
180 if (!current_log_buffer_.CanFitNow(total_size)) {
181 // TODO(b/31867689):
182 // 1. compress current buffer
183 // 2. move old buffer to linked list
184 // 3. prune old buffers, if needed
185 current_log_buffer_.Clear();
186 }
187 CHECK(current_log_buffer_.CanFitNow(total_size));
188
xshu31aa7aa2017-09-29 14:05:32 -0700189 const auto tstamp_header =
mukesh agrawal188f0472016-11-11 14:19:42 -0800190 TimestampHeader()
191 .set_since_boot_awake_only(os_->GetTimestamp(CLOCK_MONOTONIC))
192 .set_since_boot_with_sleep(os_->GetTimestamp(CLOCK_BOOTTIME))
193 .set_since_epoch(os_->GetTimestamp(CLOCK_REALTIME));
xshu31aa7aa2017-09-29 14:05:32 -0700194 const auto message_buf =
mukesh agrawal937164d2016-10-20 15:35:26 -0700195 ByteBuffer<sizeof(TimestampHeader) + protocol::kMaxMessageSize>()
196 .AppendOrDie(&tstamp_header, sizeof(tstamp_header))
197 .AppendOrDie(command_buffer, command_len);
mukesh agrawal63068972016-09-29 17:42:46 -0700198 bool did_write = current_log_buffer_.Append(
199 message_buf.data(),
200 SAFELY_CLAMP(message_buf.size(), uint16_t, 0, GetMaxVal<uint16_t>()));
201 if (!did_write) {
202 // Given that we checked for enough free space, Append() should
203 // have succeeded. Hence, a failure here indicates a logic error,
204 // rather than a runtime error.
205 LOG(FATAL) << "Unexpected failure to Append()";
206 }
207
208 return true;
209}
210
mukesh agrawalfd080642016-10-07 15:45:37 -0700211bool CommandProcessor::Dump(unique_fd dump_fd) {
mukesh agrawalfd080642016-10-07 15:45:37 -0700212 MessageBuffer::ScopedRewinder rewinder(&current_log_buffer_);
mukesh agrawal93f78dc2016-10-13 16:07:40 -0700213 while (auto buffer_reader =
214 MemoryReader(current_log_buffer_.ConsumeNextMessage())) {
215 const auto& tstamp_header = buffer_reader.CopyOutOrDie<TimestampHeader>();
216 const auto& command_header =
217 buffer_reader.CopyOutOrDie<protocol::Command>();
mukesh agrawalfd080642016-10-07 15:45:37 -0700218
mukesh agrawal93f78dc2016-10-13 16:07:40 -0700219 // TOOO(b/32256098): validate |buffer_reader.size()| against payload_len,
220 // and use a smaller size if necessary. Update a stats counter if
221 // payload_len and
222 // buflen do not match.
223
224 std::string output_string = tstamp_header.ToString();
225 switch (command_header.opcode) {
226 using protocol::Opcode;
227 case Opcode::kWriteAsciiMessage:
228 output_string += ' ' + FormatAsciiMessage(buffer_reader);
229 break;
230 case Opcode::kDumpBuffers:
231 LOG(FATAL) << "Unexpected DumpBuffers command in log";
mukesh agrawal93f78dc2016-10-13 16:07:40 -0700232 }
233 output_string += '\n';
234
mukesh agrawalfd080642016-10-07 15:45:37 -0700235 size_t n_written;
236 Os::Errno err;
237 std::tie(n_written, err) =
mukesh agrawal93f78dc2016-10-13 16:07:40 -0700238 os_->Write(dump_fd, output_string.data(), output_string.size());
mukesh agrawalfd080642016-10-07 15:45:37 -0700239 if (err == EINTR) {
240 // The next write will probably succeed. We dont't retry the current
241 // message, however, because we want to guarantee forward progress.
242 //
243 // TODO(b/32098735): Increment a counter, and attempt to output that
244 // counter after we've dumped all the log messages.
245 } else if (err) {
246 // Any error other than EINTR is considered unrecoverable.
247 LOG(ERROR) << "Terminating log dump, due to " << strerror(err);
248 return false;
249 }
mukesh agrawalfd080642016-10-07 15:45:37 -0700250 }
251
252 return true;
253}
254
mukesh agrawal93f78dc2016-10-13 16:07:40 -0700255std::string CommandProcessor::FormatAsciiMessage(MemoryReader buffer_reader) {
256 constexpr char kShortHeaderError[] = "[truncated-header]";
257 if (buffer_reader.size() < sizeof(protocol::AsciiMessage)) {
mukesh agrawal82816d22016-10-27 14:18:29 -0700258 // TODO(b/32098735): Increment stats counter.
mukesh agrawal93f78dc2016-10-13 16:07:40 -0700259 return kShortHeaderError;
260 }
261
262 const auto& ascii_message_header =
263 buffer_reader.CopyOutOrDie<protocol::AsciiMessage>();
264 const std::string& formatted_tag =
265 GetStringFromMemoryReader(&buffer_reader, ascii_message_header.tag_len);
266 const std::string& formatted_msg =
267 GetStringFromMemoryReader(&buffer_reader, ascii_message_header.data_len);
268 return formatted_tag + ' ' + formatted_msg;
269}
270
mukesh agrawal63068972016-09-29 17:42:46 -0700271} // namespace wifilogd
272} // namespace android