1 /*
2 * Copyright (C) 2012-2013 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 <ctype.h>
18 #include <inttypes.h>
19 #include <poll.h>
20 #include <sched.h>
21 #include <sys/prctl.h>
22 #include <sys/socket.h>
23 #include <sys/types.h>
24
25 #include <chrono>
26
27 #include <android-base/logging.h>
28 #include <android-base/stringprintf.h>
29 #include <cutils/sockets.h>
30 #include <private/android_filesystem_config.h>
31 #include <private/android_logger.h>
32
33 #include "LogBuffer.h"
34 #include "LogBufferElement.h"
35 #include "LogPermissions.h"
36 #include "LogReader.h"
37 #include "LogUtils.h"
38 #include "LogWriter.h"
39
CanReadSecurityLogs(SocketClient * client)40 static bool CanReadSecurityLogs(SocketClient* client) {
41 return client->getUid() == AID_SYSTEM || client->getGid() == AID_SYSTEM;
42 }
43
SocketClientToName(SocketClient * client)44 static std::string SocketClientToName(SocketClient* client) {
45 return android::base::StringPrintf("pid %d, fd %d", client->getPid(), client->getSocket());
46 }
47
48 class SocketLogWriter : public LogWriter {
49 public:
SocketLogWriter(LogReader * reader,SocketClient * client,bool privileged)50 SocketLogWriter(LogReader* reader, SocketClient* client, bool privileged)
51 : LogWriter(client->getUid(), privileged), reader_(reader), client_(client) {}
52
Write(const logger_entry & entry,const char * msg)53 bool Write(const logger_entry& entry, const char* msg) override {
54 struct iovec iovec[2];
55 iovec[0].iov_base = const_cast<logger_entry*>(&entry);
56 iovec[0].iov_len = entry.hdr_size;
57 iovec[1].iov_base = const_cast<char*>(msg);
58 iovec[1].iov_len = entry.len;
59
60 return client_->sendDatav(iovec, 1 + (entry.len != 0)) == 0;
61 }
62
Release()63 void Release() override {
64 reader_->release(client_);
65 client_->decRef();
66 }
67
Shutdown()68 void Shutdown() override { shutdown(client_->getSocket(), SHUT_RDWR); }
69
name() const70 std::string name() const override { return SocketClientToName(client_); }
71
72 private:
73 LogReader* reader_;
74 SocketClient* client_;
75 };
76
LogReader(LogBuffer * logbuf,LogReaderList * reader_list)77 LogReader::LogReader(LogBuffer* logbuf, LogReaderList* reader_list)
78 : SocketListener(getLogSocket(), true), log_buffer_(logbuf), reader_list_(reader_list) {}
79
80 // Note returning false will release the SocketClient instance.
onDataAvailable(SocketClient * cli)81 bool LogReader::onDataAvailable(SocketClient* cli) {
82 static bool name_set;
83 if (!name_set) {
84 prctl(PR_SET_NAME, "logd.reader");
85 name_set = true;
86 }
87
88 char buffer[255];
89
90 int len = read(cli->getSocket(), buffer, sizeof(buffer) - 1);
91 if (len <= 0) {
92 DoSocketDelete(cli);
93 return false;
94 }
95 buffer[len] = '\0';
96
97 // Clients are only allowed to send one command, disconnect them if they send another.
98 if (DoSocketDelete(cli)) {
99 return false;
100 }
101
102 unsigned long tail = 0;
103 static const char _tail[] = " tail=";
104 char* cp = strstr(buffer, _tail);
105 if (cp) {
106 tail = atol(cp + sizeof(_tail) - 1);
107 }
108
109 log_time start(log_time::EPOCH);
110 static const char _start[] = " start=";
111 cp = strstr(buffer, _start);
112 if (cp) {
113 // Parse errors will result in current time
114 start.strptime(cp + sizeof(_start) - 1, "%s.%q");
115 }
116
117 std::chrono::steady_clock::time_point deadline = {};
118 static const char _timeout[] = " timeout=";
119 cp = strstr(buffer, _timeout);
120 if (cp) {
121 long timeout_seconds = atol(cp + sizeof(_timeout) - 1);
122 deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout_seconds);
123 }
124
125 unsigned int logMask = -1;
126 static const char _logIds[] = " lids=";
127 cp = strstr(buffer, _logIds);
128 if (cp) {
129 logMask = 0;
130 cp += sizeof(_logIds) - 1;
131 while (*cp != '\0') {
132 int val = 0;
133 while (isdigit(*cp)) {
134 val = val * 10 + *cp - '0';
135 ++cp;
136 }
137 logMask |= 1 << val;
138 if (*cp != ',') {
139 break;
140 }
141 ++cp;
142 }
143 }
144
145 pid_t pid = 0;
146 static const char _pid[] = " pid=";
147 cp = strstr(buffer, _pid);
148 if (cp) {
149 pid = atol(cp + sizeof(_pid) - 1);
150 }
151
152 bool nonBlock = false;
153 if (!fastcmp<strncmp>(buffer, "dumpAndClose", 12)) {
154 // Allow writer to get some cycles, and wait for pending notifications
155 sched_yield();
156 logd_lock.lock();
157 logd_lock.unlock();
158 sched_yield();
159 nonBlock = true;
160 }
161
162 bool privileged = clientHasLogCredentials(cli);
163 bool can_read_security = CanReadSecurityLogs(cli);
164 if (!can_read_security) {
165 logMask &= ~(1 << LOG_ID_SECURITY);
166 }
167
168 std::unique_ptr<LogWriter> socket_log_writer(new SocketLogWriter(this, cli, privileged));
169
170 uint64_t sequence = 1;
171 // Convert realtime to sequence number
172 if (start != log_time::EPOCH) {
173 bool start_time_set = false;
174 uint64_t last = sequence;
175 auto log_find_start = [pid, start, &sequence, &start_time_set, &last](
176 log_id_t, pid_t element_pid, uint64_t element_sequence,
177 log_time element_realtime) -> FilterResult {
178 if (pid && pid != element_pid) {
179 return FilterResult::kSkip;
180 }
181 if (start == element_realtime) {
182 sequence = element_sequence;
183 start_time_set = true;
184 return FilterResult::kStop;
185 } else {
186 if (start < element_realtime) {
187 sequence = last;
188 start_time_set = true;
189 return FilterResult::kStop;
190 }
191 last = element_sequence;
192 }
193 return FilterResult::kSkip;
194 };
195 auto lock = std::lock_guard{logd_lock};
196 auto flush_to_state = log_buffer_->CreateFlushToState(sequence, logMask);
197 log_buffer_->FlushTo(socket_log_writer.get(), *flush_to_state, log_find_start);
198
199 if (!start_time_set) {
200 if (nonBlock) {
201 return false;
202 }
203 sequence = log_buffer_->sequence();
204 }
205 }
206
207 LOG(INFO) << android::base::StringPrintf(
208 "logdr: UID=%d GID=%d PID=%d %c tail=%lu logMask=%x pid=%d "
209 "start=%" PRIu64 "ns deadline=%" PRIi64 "ns",
210 cli->getUid(), cli->getGid(), cli->getPid(), nonBlock ? 'n' : 'b', tail, logMask,
211 (int)pid, start.nsec(), static_cast<int64_t>(deadline.time_since_epoch().count()));
212
213 if (start == log_time::EPOCH) {
214 deadline = {};
215 }
216
217 auto lock = std::lock_guard{logd_lock};
218 auto entry = std::make_unique<LogReaderThread>(log_buffer_, reader_list_,
219 std::move(socket_log_writer), nonBlock, tail,
220 logMask, pid, start, sequence, deadline);
221 // release client and entry reference counts once done
222 cli->incRef();
223 reader_list_->reader_threads().emplace_front(std::move(entry));
224
225 // Set acceptable upper limit to wait for slow reader processing b/27242723
226 struct timeval t = { LOGD_SNDTIMEO, 0 };
227 setsockopt(cli->getSocket(), SOL_SOCKET, SO_SNDTIMEO, (const char*)&t,
228 sizeof(t));
229
230 return true;
231 }
232
DoSocketDelete(SocketClient * cli)233 bool LogReader::DoSocketDelete(SocketClient* cli) {
234 auto cli_name = SocketClientToName(cli);
235 auto lock = std::lock_guard{logd_lock};
236 for (const auto& reader : reader_list_->reader_threads()) {
237 if (reader->name() == cli_name) {
238 reader->Release();
239 return true;
240 }
241 }
242 return false;
243 }
244
getLogSocket()245 int LogReader::getLogSocket() {
246 static const char socketName[] = "logdr";
247 int sock = android_get_control_socket(socketName);
248
249 if (sock < 0) {
250 sock = socket_local_server(
251 socketName, ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET);
252 }
253
254 return sock;
255 }
256