command_processor.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /*
  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. #include <string.h>
  17. #include <algorithm>
  18. #include <cinttypes>
  19. #include <string>
  20. #include <tuple>
  21. #include <utility>
  22. #include "android-base/logging.h"
  23. #include "android-base/stringprintf.h"
  24. #include "wifilogd/byte_buffer.h"
  25. #include "wifilogd/command_processor.h"
  26. #include "wifilogd/local_utils.h"
  27. #include "wifilogd/memory_reader.h"
  28. #include "wifilogd/protocol.h"
  29. namespace android {
  30. namespace wifilogd {
  31. using ::android::base::unique_fd;
  32. using local_utils::CopyFromBufferOrDie;
  33. using local_utils::GetMaxVal;
  34. namespace {
  35. uint32_t NsecToUsec(uint32_t nsec);
  36. class TimestampHeader {
  37. public:
  38. TimestampHeader& set_since_boot_awake_only(Os::Timestamp new_value) {
  39. since_boot_awake_only = new_value;
  40. return *this;
  41. }
  42. TimestampHeader& set_since_boot_with_sleep(Os::Timestamp new_value) {
  43. since_boot_with_sleep = new_value;
  44. return *this;
  45. }
  46. TimestampHeader& set_since_epoch(Os::Timestamp new_value) {
  47. since_epoch = new_value;
  48. return *this;
  49. }
  50. // Returns a string with a formatted representation of the timestamps
  51. // contained within this header.
  52. std::string ToString() const {
  53. const auto& awake_time = since_boot_awake_only;
  54. const auto& up_time = since_boot_with_sleep;
  55. const auto& wall_time = since_epoch;
  56. return base::StringPrintf("%" PRIu32 ".%06" PRIu32
  57. " "
  58. "%" PRIu32 ".%06" PRIu32
  59. " "
  60. "%" PRIu32 ".%06" PRIu32,
  61. awake_time.secs, NsecToUsec(awake_time.nsecs),
  62. up_time.secs, NsecToUsec(up_time.nsecs),
  63. wall_time.secs, NsecToUsec(wall_time.nsecs));
  64. }
  65. Os::Timestamp since_boot_awake_only;
  66. Os::Timestamp since_boot_with_sleep;
  67. Os::Timestamp since_epoch; // non-monotonic
  68. };
  69. constexpr char kUnprintableCharReplacement = '?';
  70. std::string MakeSanitizedString(const uint8_t* buf, size_t buf_len);
  71. std::string GetStringFromMemoryReader(NONNULL MemoryReader* buffer_reader,
  72. const size_t desired_len) {
  73. constexpr char kBufferOverrunError[] = "[buffer-overrun]";
  74. constexpr char kZeroLengthError[] = "[empty]";
  75. if (!desired_len) {
  76. // TODO(b/32098735): Increment stats counter.
  77. return kZeroLengthError;
  78. }
  79. auto effective_len = desired_len;
  80. if (buffer_reader->size() < effective_len) {
  81. // TODO(b/32098735): Increment stats counter.
  82. effective_len = buffer_reader->size();
  83. }
  84. auto out = MakeSanitizedString(buffer_reader->GetBytesOrDie(effective_len),
  85. effective_len);
  86. if (effective_len < desired_len) {
  87. out += kBufferOverrunError;
  88. }
  89. return out;
  90. }
  91. std::string MakeSanitizedString(const uint8_t* buf, size_t buf_len) {
  92. std::string out(buf_len, '\0');
  93. std::replace_copy_if(buf, buf + buf_len, &out.front(),
  94. [](auto c) { return !local_utils::IsAsciiPrintable(c); },
  95. kUnprintableCharReplacement);
  96. return out;
  97. }
  98. uint32_t NsecToUsec(uint32_t nsec) { return nsec / 1000; }
  99. } // namespace
  100. CommandProcessor::CommandProcessor(size_t buffer_size_bytes)
  101. : current_log_buffer_(buffer_size_bytes), os_(new Os()) {}
  102. CommandProcessor::CommandProcessor(size_t buffer_size_bytes,
  103. std::unique_ptr<Os> os)
  104. : current_log_buffer_(buffer_size_bytes), os_(std::move(os)) {}
  105. CommandProcessor::~CommandProcessor() {}
  106. bool CommandProcessor::ProcessCommand(const void* input_buffer,
  107. size_t n_bytes_read, int fd) {
  108. unique_fd wrapped_fd(fd);
  109. if (n_bytes_read < sizeof(protocol::Command)) {
  110. // TODO(b/32098735): Increment stats counter.
  111. return false;
  112. }
  113. const auto& command_header =
  114. CopyFromBufferOrDie<protocol::Command>(input_buffer, n_bytes_read);
  115. switch (command_header.opcode) {
  116. using protocol::Opcode;
  117. case Opcode::kWriteAsciiMessage:
  118. // Copy the entire command to the log. This defers the cost of
  119. // validating the rest of the CommandHeader until we dump the
  120. // message.
  121. //
  122. // Note that most messages will be written but never read. So, in
  123. // the common case, the validation cost is actually eliminated,
  124. // rather than just deferred.
  125. return CopyCommandToLog(input_buffer, n_bytes_read);
  126. case Opcode::kDumpBuffers:
  127. return Dump(std::move(wrapped_fd));
  128. }
  129. LOG(DEBUG) << "Received unexpected opcode "
  130. << local_utils::CastEnumToInteger(command_header.opcode);
  131. // TODO(b/32098735): Increment stats counter.
  132. return false;
  133. }
  134. // Private methods below.
  135. bool CommandProcessor::CopyCommandToLog(const void* command_buffer,
  136. size_t command_len_in) {
  137. const uint16_t command_len =
  138. SAFELY_CLAMP(command_len_in, uint16_t, 0, protocol::kMaxMessageSize);
  139. uint16_t total_size;
  140. static_assert(GetMaxVal(total_size) > sizeof(TimestampHeader) &&
  141. GetMaxVal(total_size) - sizeof(TimestampHeader) >=
  142. protocol::kMaxMessageSize,
  143. "total_size cannot represent some input messages");
  144. total_size = sizeof(TimestampHeader) + command_len;
  145. CHECK(current_log_buffer_.CanFitEver(total_size));
  146. if (!current_log_buffer_.CanFitNow(total_size)) {
  147. // TODO(b/31867689):
  148. // 1. compress current buffer
  149. // 2. move old buffer to linked list
  150. // 3. prune old buffers, if needed
  151. current_log_buffer_.Clear();
  152. }
  153. CHECK(current_log_buffer_.CanFitNow(total_size));
  154. const auto tstamp_header =
  155. TimestampHeader()
  156. .set_since_boot_awake_only(os_->GetTimestamp(CLOCK_MONOTONIC))
  157. .set_since_boot_with_sleep(os_->GetTimestamp(CLOCK_BOOTTIME))
  158. .set_since_epoch(os_->GetTimestamp(CLOCK_REALTIME));
  159. const auto message_buf =
  160. ByteBuffer<sizeof(TimestampHeader) + protocol::kMaxMessageSize>()
  161. .AppendOrDie(&tstamp_header, sizeof(tstamp_header))
  162. .AppendOrDie(command_buffer, command_len);
  163. bool did_write = current_log_buffer_.Append(
  164. message_buf.data(),
  165. SAFELY_CLAMP(message_buf.size(), uint16_t, 0, GetMaxVal<uint16_t>()));
  166. if (!did_write) {
  167. // Given that we checked for enough free space, Append() should
  168. // have succeeded. Hence, a failure here indicates a logic error,
  169. // rather than a runtime error.
  170. LOG(FATAL) << "Unexpected failure to Append()";
  171. }
  172. return true;
  173. }
  174. bool CommandProcessor::Dump(unique_fd dump_fd) {
  175. MessageBuffer::ScopedRewinder rewinder(&current_log_buffer_);
  176. while (auto buffer_reader =
  177. MemoryReader(current_log_buffer_.ConsumeNextMessage())) {
  178. const auto& tstamp_header = buffer_reader.CopyOutOrDie<TimestampHeader>();
  179. const auto& command_header =
  180. buffer_reader.CopyOutOrDie<protocol::Command>();
  181. // TOOO(b/32256098): validate |buffer_reader.size()| against payload_len,
  182. // and use a smaller size if necessary. Update a stats counter if
  183. // payload_len and
  184. // buflen do not match.
  185. std::string output_string = tstamp_header.ToString();
  186. switch (command_header.opcode) {
  187. using protocol::Opcode;
  188. case Opcode::kWriteAsciiMessage:
  189. output_string += ' ' + FormatAsciiMessage(buffer_reader);
  190. break;
  191. case Opcode::kDumpBuffers:
  192. LOG(FATAL) << "Unexpected DumpBuffers command in log";
  193. }
  194. output_string += '\n';
  195. size_t n_written;
  196. Os::Errno err;
  197. std::tie(n_written, err) =
  198. os_->Write(dump_fd, output_string.data(), output_string.size());
  199. if (err == EINTR) {
  200. // The next write will probably succeed. We dont't retry the current
  201. // message, however, because we want to guarantee forward progress.
  202. //
  203. // TODO(b/32098735): Increment a counter, and attempt to output that
  204. // counter after we've dumped all the log messages.
  205. } else if (err) {
  206. // Any error other than EINTR is considered unrecoverable.
  207. LOG(ERROR) << "Terminating log dump, due to " << strerror(err);
  208. return false;
  209. }
  210. }
  211. return true;
  212. }
  213. std::string CommandProcessor::FormatAsciiMessage(MemoryReader buffer_reader) {
  214. constexpr char kShortHeaderError[] = "[truncated-header]";
  215. if (buffer_reader.size() < sizeof(protocol::AsciiMessage)) {
  216. // TODO(b/32098735): Increment stats counter.
  217. return kShortHeaderError;
  218. }
  219. const auto& ascii_message_header =
  220. buffer_reader.CopyOutOrDie<protocol::AsciiMessage>();
  221. const std::string& formatted_tag =
  222. GetStringFromMemoryReader(&buffer_reader, ascii_message_header.tag_len);
  223. const std::string& formatted_msg =
  224. GetStringFromMemoryReader(&buffer_reader, ascii_message_header.data_len);
  225. return formatted_tag + ' ' + formatted_msg;
  226. }
  227. } // namespace wifilogd
  228. } // namespace android