1 /*
2  * Copyright (C) 2020 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 
17 #include "SimpleLogBuffer.h"
18 
19 #include <android-base/logging.h>
20 
21 #include "LogBufferElement.h"
22 
SimpleLogBuffer(LogReaderList * reader_list,LogTags * tags,LogStatistics * stats)23 SimpleLogBuffer::SimpleLogBuffer(LogReaderList* reader_list, LogTags* tags, LogStatistics* stats)
24     : reader_list_(reader_list), tags_(tags), stats_(stats) {
25     Init();
26 }
27 
~SimpleLogBuffer()28 SimpleLogBuffer::~SimpleLogBuffer() {}
29 
Init()30 void SimpleLogBuffer::Init() {
31     log_id_for_each(i) {
32         if (SetSize(i, __android_logger_get_buffer_size(i))) {
33             SetSize(i, LOG_BUFFER_MIN_SIZE);
34         }
35     }
36 
37     // Release any sleeping reader threads to dump their current content.
38     auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
39     for (const auto& reader_thread : reader_list_->reader_threads()) {
40         reader_thread->triggerReader_Locked();
41     }
42 }
43 
GetOldest(log_id_t log_id)44 std::list<LogBufferElement>::iterator SimpleLogBuffer::GetOldest(log_id_t log_id) {
45     auto it = logs().begin();
46     if (oldest_[log_id]) {
47         it = *oldest_[log_id];
48     }
49     while (it != logs().end() && it->log_id() != log_id) {
50         it++;
51     }
52     if (it != logs().end()) {
53         oldest_[log_id] = it;
54     }
55     return it;
56 }
57 
ShouldLog(log_id_t log_id,const char * msg,uint16_t len)58 bool SimpleLogBuffer::ShouldLog(log_id_t log_id, const char* msg, uint16_t len) {
59     if (log_id == LOG_ID_SECURITY) {
60         return true;
61     }
62 
63     int prio = ANDROID_LOG_INFO;
64     const char* tag = nullptr;
65     size_t tag_len = 0;
66     if (IsBinary(log_id)) {
67         int32_t numeric_tag = MsgToTag(msg, len);
68         tag = tags_->tagToName(numeric_tag);
69         if (tag) {
70             tag_len = strlen(tag);
71         }
72     } else {
73         prio = *msg;
74         tag = msg + 1;
75         tag_len = strnlen(tag, len - 1);
76     }
77     return __android_log_is_loggable_len(prio, tag, tag_len, ANDROID_LOG_VERBOSE);
78 }
79 
Log(log_id_t log_id,log_time realtime,uid_t uid,pid_t pid,pid_t tid,const char * msg,uint16_t len)80 int SimpleLogBuffer::Log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid,
81                          const char* msg, uint16_t len) {
82     if (log_id >= LOG_ID_MAX) {
83         return -EINVAL;
84     }
85 
86     if (!ShouldLog(log_id, msg, len)) {
87         // Log traffic received to total
88         stats_->AddTotal(log_id, len);
89         return -EACCES;
90     }
91 
92     // Slip the time by 1 nsec if the incoming lands on xxxxxx000 ns.
93     // This prevents any chance that an outside source can request an
94     // exact entry with time specified in ms or us precision.
95     if ((realtime.tv_nsec % 1000) == 0) ++realtime.tv_nsec;
96 
97     auto lock = std::lock_guard{lock_};
98     auto sequence = sequence_.fetch_add(1, std::memory_order_relaxed);
99     LogInternal(LogBufferElement(log_id, realtime, uid, pid, tid, sequence, msg, len));
100     return len;
101 }
102 
LogInternal(LogBufferElement && elem)103 void SimpleLogBuffer::LogInternal(LogBufferElement&& elem) {
104     log_id_t log_id = elem.log_id();
105 
106     logs_.emplace_back(std::move(elem));
107     stats_->Add(logs_.back().ToLogStatisticsElement());
108     MaybePrune(log_id);
109     reader_list_->NotifyNewLog(1 << log_id);
110 }
111 
112 // These extra parameters are only required for chatty, but since they're a no-op for
113 // SimpleLogBuffer, it's easier to include them here, then to duplicate FlushTo() for
114 // ChattyLogBuffer.
115 class ChattyFlushToState : public FlushToState {
116   public:
ChattyFlushToState(uint64_t start,LogMask log_mask)117     ChattyFlushToState(uint64_t start, LogMask log_mask) : FlushToState(start, log_mask) {}
118 
last_tid()119     pid_t* last_tid() { return last_tid_; }
120 
drop_chatty_messages() const121     bool drop_chatty_messages() const { return drop_chatty_messages_; }
set_drop_chatty_messages(bool value)122     void set_drop_chatty_messages(bool value) { drop_chatty_messages_ = value; }
123 
124   private:
125     pid_t last_tid_[LOG_ID_MAX] = {};
126     bool drop_chatty_messages_ = true;
127 };
128 
CreateFlushToState(uint64_t start,LogMask log_mask)129 std::unique_ptr<FlushToState> SimpleLogBuffer::CreateFlushToState(uint64_t start,
130                                                                   LogMask log_mask) {
131     return std::make_unique<ChattyFlushToState>(start, log_mask);
132 }
133 
FlushTo(LogWriter * writer,FlushToState & abstract_state,const std::function<FilterResult (log_id_t log_id,pid_t pid,uint64_t sequence,log_time realtime)> & filter)134 bool SimpleLogBuffer::FlushTo(
135         LogWriter* writer, FlushToState& abstract_state,
136         const std::function<FilterResult(log_id_t log_id, pid_t pid, uint64_t sequence,
137                                          log_time realtime)>& filter) {
138     auto shared_lock = SharedLock{lock_};
139 
140     auto& state = reinterpret_cast<ChattyFlushToState&>(abstract_state);
141 
142     std::list<LogBufferElement>::iterator it;
143     if (state.start() <= 1) {
144         // client wants to start from the beginning
145         it = logs_.begin();
146     } else {
147         // Client wants to start from some specified time. Chances are
148         // we are better off starting from the end of the time sorted list.
149         for (it = logs_.end(); it != logs_.begin();
150              /* do nothing */) {
151             --it;
152             if (it->sequence() == state.start()) {
153                 break;
154             } else if (it->sequence() < state.start()) {
155                 it++;
156                 break;
157             }
158         }
159     }
160 
161     for (; it != logs_.end(); ++it) {
162         LogBufferElement& element = *it;
163 
164         state.set_start(element.sequence());
165 
166         if (!writer->privileged() && element.uid() != writer->uid()) {
167             continue;
168         }
169 
170         if (((1 << element.log_id()) & state.log_mask()) == 0) {
171             continue;
172         }
173 
174         if (filter) {
175             FilterResult ret =
176                     filter(element.log_id(), element.pid(), element.sequence(), element.realtime());
177             if (ret == FilterResult::kSkip) {
178                 continue;
179             }
180             if (ret == FilterResult::kStop) {
181                 break;
182             }
183         }
184 
185         // drop_chatty_messages is initialized to true, so if the first message that we attempt to
186         // flush is a chatty message, we drop it.  Once we see a non-chatty message it gets set to
187         // false to let further chatty messages be printed.
188         if (state.drop_chatty_messages()) {
189             if (element.dropped_count() != 0) {
190                 continue;
191             }
192             state.set_drop_chatty_messages(false);
193         }
194 
195         bool same_tid = state.last_tid()[element.log_id()] == element.tid();
196         // Dropped (chatty) immediately following a valid log from the same source in the same log
197         // buffer indicates we have a multiple identical squash.  chatty that differs source is due
198         // to spam filter.  chatty to chatty of different source is also due to spam filter.
199         state.last_tid()[element.log_id()] =
200                 (element.dropped_count() && !same_tid) ? 0 : element.tid();
201 
202         shared_lock.unlock();
203         // We never prune logs equal to or newer than any LogReaderThreads' `start` value, so the
204         // `element` pointer is safe here without the lock
205         if (!element.FlushTo(writer, stats_, same_tid)) {
206             return false;
207         }
208         shared_lock.lock_shared();
209     }
210 
211     state.set_start(state.start() + 1);
212     return true;
213 }
214 
Clear(log_id_t id,uid_t uid)215 bool SimpleLogBuffer::Clear(log_id_t id, uid_t uid) {
216     // Try three times to clear, then disconnect the readers and try one final time.
217     for (int retry = 0; retry < 3; ++retry) {
218         {
219             auto lock = std::lock_guard{lock_};
220             if (Prune(id, ULONG_MAX, uid)) {
221                 return true;
222             }
223         }
224         sleep(1);
225     }
226     // Check if it is still busy after the sleep, we try to prune one entry, not another clear run,
227     // so we are looking for the quick side effect of the return value to tell us if we have a
228     // _blocked_ reader.
229     bool busy = false;
230     {
231         auto lock = std::lock_guard{lock_};
232         busy = !Prune(id, 1, uid);
233     }
234     // It is still busy, disconnect all readers.
235     if (busy) {
236         auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
237         for (const auto& reader_thread : reader_list_->reader_threads()) {
238             if (reader_thread->IsWatching(id)) {
239                 LOG(WARNING) << "Kicking blocked reader, " << reader_thread->name()
240                              << ", from LogBuffer::clear()";
241                 reader_thread->release_Locked();
242             }
243         }
244     }
245     auto lock = std::lock_guard{lock_};
246     return Prune(id, ULONG_MAX, uid);
247 }
248 
249 // get the total space allocated to "id"
GetSize(log_id_t id)250 unsigned long SimpleLogBuffer::GetSize(log_id_t id) {
251     auto lock = SharedLock{lock_};
252     size_t retval = max_size_[id];
253     return retval;
254 }
255 
256 // set the total space allocated to "id"
SetSize(log_id_t id,unsigned long size)257 int SimpleLogBuffer::SetSize(log_id_t id, unsigned long size) {
258     // Reasonable limits ...
259     if (!__android_logger_valid_buffer_size(size)) {
260         return -1;
261     }
262 
263     auto lock = std::lock_guard{lock_};
264     max_size_[id] = size;
265     return 0;
266 }
267 
MaybePrune(log_id_t id)268 void SimpleLogBuffer::MaybePrune(log_id_t id) {
269     unsigned long prune_rows;
270     if (stats_->ShouldPrune(id, max_size_[id], &prune_rows)) {
271         Prune(id, prune_rows, 0);
272     }
273 }
274 
Prune(log_id_t id,unsigned long prune_rows,uid_t caller_uid)275 bool SimpleLogBuffer::Prune(log_id_t id, unsigned long prune_rows, uid_t caller_uid) {
276     auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
277 
278     // Don't prune logs that are newer than the point at which any reader threads are reading from.
279     LogReaderThread* oldest = nullptr;
280     for (const auto& reader_thread : reader_list_->reader_threads()) {
281         if (!reader_thread->IsWatching(id)) {
282             continue;
283         }
284         if (!oldest || oldest->start() > reader_thread->start() ||
285             (oldest->start() == reader_thread->start() &&
286              reader_thread->deadline().time_since_epoch().count() != 0)) {
287             oldest = reader_thread.get();
288         }
289     }
290 
291     auto it = GetOldest(id);
292 
293     while (it != logs_.end()) {
294         LogBufferElement& element = *it;
295 
296         if (element.log_id() != id) {
297             ++it;
298             continue;
299         }
300 
301         if (caller_uid != 0 && element.uid() != caller_uid) {
302             ++it;
303             continue;
304         }
305 
306         if (oldest && oldest->start() <= element.sequence()) {
307             KickReader(oldest, id, prune_rows);
308             return false;
309         }
310 
311         stats_->Subtract(element.ToLogStatisticsElement());
312         it = Erase(it);
313         if (--prune_rows == 0) {
314             return true;
315         }
316     }
317     return true;
318 }
319 
Erase(std::list<LogBufferElement>::iterator it)320 std::list<LogBufferElement>::iterator SimpleLogBuffer::Erase(
321         std::list<LogBufferElement>::iterator it) {
322     bool oldest_is_it[LOG_ID_MAX];
323     log_id_for_each(i) { oldest_is_it[i] = oldest_[i] && it == *oldest_[i]; }
324 
325     it = logs_.erase(it);
326 
327     log_id_for_each(i) {
328         if (oldest_is_it[i]) {
329             if (__predict_false(it == logs().end())) {
330                 oldest_[i] = std::nullopt;
331             } else {
332                 oldest_[i] = it;  // Store the next iterator even if it does not correspond to
333                                   // the same log_id, as a starting point for GetOldest().
334             }
335         }
336     }
337 
338     return it;
339 }
340 
341 // If the selected reader is blocking our pruning progress, decide on
342 // what kind of mitigation is necessary to unblock the situation.
KickReader(LogReaderThread * reader,log_id_t id,unsigned long prune_rows)343 void SimpleLogBuffer::KickReader(LogReaderThread* reader, log_id_t id, unsigned long prune_rows) {
344     if (stats_->Sizes(id) > (2 * max_size_[id])) {  // +100%
345         // A misbehaving or slow reader has its connection
346         // dropped if we hit too much memory pressure.
347         LOG(WARNING) << "Kicking blocked reader, " << reader->name()
348                      << ", from LogBuffer::kickMe()";
349         reader->release_Locked();
350     } else if (reader->deadline().time_since_epoch().count() != 0) {
351         // Allow a blocked WRAP deadline reader to trigger and start reporting the log data.
352         reader->triggerReader_Locked();
353     } else {
354         // tell slow reader to skip entries to catch up
355         LOG(WARNING) << "Skipping " << prune_rows << " entries from slow reader, " << reader->name()
356                      << ", from LogBuffer::kickMe()";
357         reader->triggerSkip_Locked(id, prune_rows);
358     }
359 }
360