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 <binder/IServiceManager.h>
30 #include <binder/ProcessState.h>
31 #include <cutils/sockets.h>
32 #include <private/android_filesystem_config.h>
33 #include <private/android_logger.h>
34 
35 #include "LogdNativeService.h"
36 #include "LogBuffer.h"
37 #include "LogBufferElement.h"
38 #include "LogPermissions.h"
39 #include "LogReader.h"
40 #include "LogUtils.h"
41 #include "LogWriter.h"
42 
43 using android::defaultServiceManager;
44 using android::ProcessState;
45 using android::sp;
46 using android::String16;
47 
CanReadSecurityLogs(SocketClient * client)48 static bool CanReadSecurityLogs(SocketClient* client) {
49     return client->getUid() == AID_SYSTEM || client->getGid() == AID_SYSTEM;
50 }
51 
SocketClientToName(SocketClient * client)52 static std::string SocketClientToName(SocketClient* client) {
53     return android::base::StringPrintf("pid %d, fd %d", client->getPid(), client->getSocket());
54 }
55 
InitLogdBinderServiceStatus(LogReaderList * reader_list)56 static bool InitLogdBinderServiceStatus(LogReaderList* reader_list) {
57     sp<LogdNativeService> service = new LogdNativeService(reader_list);
58     auto service_status = defaultServiceManager()->addService(String16("logd"), service);
59     if (service_status != android::OK) {
60         LOG(ERROR) << "Failed to add logd binder service.";
61         return false;
62     }
63 
64     sp<ProcessState> proc(ProcessState::self());
65     proc->startThreadPool();
66     return true;
67 }
68 
GetLogdBinderServiceStatus(LogReaderList * reader_list)69 static bool GetLogdBinderServiceStatus(LogReaderList* reader_list) {
70     static bool service_status = InitLogdBinderServiceStatus(reader_list);
71     return service_status;
72 }
73 
74 class SocketLogWriter : public LogWriter {
75   public:
SocketLogWriter(LogReader * reader,SocketClient * client,bool privileged)76     SocketLogWriter(LogReader* reader, SocketClient* client, bool privileged)
77         : LogWriter(client->getUid(), privileged), reader_(reader), client_(client) {}
78 
Write(const logger_entry & entry,const char * msg)79     bool Write(const logger_entry& entry, const char* msg) override {
80         struct iovec iovec[2];
81         iovec[0].iov_base = const_cast<logger_entry*>(&entry);
82         iovec[0].iov_len = entry.hdr_size;
83         iovec[1].iov_base = const_cast<char*>(msg);
84         iovec[1].iov_len = entry.len;
85 
86         return client_->sendDatav(iovec, 1 + (entry.len != 0)) == 0;
87     }
88 
Release()89     void Release() override {
90         reader_->release(client_);
91         client_->decRef();
92     }
93 
Shutdown()94     void Shutdown() override { shutdown(client_->getSocket(), SHUT_RDWR); }
95 
name() const96     std::string name() const override { return SocketClientToName(client_); }
97 
98   private:
99     LogReader* reader_;
100     SocketClient* client_;
101 };
102 
LogReader(LogBuffer * logbuf,LogReaderList * reader_list)103 LogReader::LogReader(LogBuffer* logbuf, LogReaderList* reader_list)
104     : SocketListener(getLogSocket(), true), log_buffer_(logbuf), reader_list_(reader_list) {}
105 
106 // Note returning false will release the SocketClient instance.
onDataAvailable(SocketClient * cli)107 bool LogReader::onDataAvailable(SocketClient* cli) {
108     static bool name_set;
109     if (!name_set) {
110         prctl(PR_SET_NAME, "logd.reader");
111         name_set = true;
112     }
113 
114     char buffer[255];
115 
116     int len = read(cli->getSocket(), buffer, sizeof(buffer) - 1);
117     if (len <= 0) {
118         DoSocketDelete(cli);
119         return false;
120     }
121     buffer[len] = '\0';
122 
123     // Clients are only allowed to send one command, disconnect them if they send another.
124     if (DoSocketDelete(cli)) {
125         return false;
126     }
127 
128     unsigned long tail = 0;
129     static const char _tail[] = " tail=";
130     char* cp = strstr(buffer, _tail);
131     if (cp) {
132         tail = atol(cp + sizeof(_tail) - 1);
133     }
134 
135     log_time start(log_time::EPOCH);
136     static const char _start[] = " start=";
137     cp = strstr(buffer, _start);
138     if (cp) {
139         // Parse errors will result in current time
140         start.strptime(cp + sizeof(_start) - 1, "%s.%q");
141     }
142 
143     std::chrono::steady_clock::time_point deadline = {};
144     static const char _timeout[] = " timeout=";
145     cp = strstr(buffer, _timeout);
146     if (cp) {
147         long timeout_seconds = atol(cp + sizeof(_timeout) - 1);
148         deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout_seconds);
149     }
150 
151     unsigned int logMask = -1;
152     static const char _logIds[] = " lids=";
153     cp = strstr(buffer, _logIds);
154     if (cp) {
155         logMask = 0;
156         cp += sizeof(_logIds) - 1;
157         while (*cp != '\0') {
158             int val = 0;
159             while (isdigit(*cp)) {
160                 val = val * 10 + *cp - '0';
161                 ++cp;
162             }
163             logMask |= 1 << val;
164             if (*cp != ',') {
165                 break;
166             }
167             ++cp;
168         }
169     }
170 
171     pid_t pid = 0;
172     static const char _pid[] = " pid=";
173     cp = strstr(buffer, _pid);
174     if (cp) {
175         pid = atol(cp + sizeof(_pid) - 1);
176     }
177 
178     bool nonBlock = false;
179     if (!fastcmp<strncmp>(buffer, "dumpAndClose", 12)) {
180         // Allow writer to get some cycles, and wait for pending notifications
181         sched_yield();
182         logd_lock.lock();
183         logd_lock.unlock();
184         sched_yield();
185         nonBlock = true;
186     }
187 
188     bool privileged = clientHasLogCredentials(cli);
189     bool can_read_security = CanReadSecurityLogs(cli);
190     if (!can_read_security) {
191         logMask &= ~(1 << LOG_ID_SECURITY);
192     }
193 
194     std::unique_ptr<LogWriter> socket_log_writer(new SocketLogWriter(this, cli, privileged));
195 
196     uint64_t sequence = 1;
197     // Convert realtime to sequence number
198     if (start != log_time::EPOCH) {
199         bool start_time_set = false;
200         uint64_t last = sequence;
201         auto log_find_start = [pid, start, &sequence, &start_time_set, &last](
202                                       log_id_t, pid_t element_pid, uint64_t element_sequence,
203                                       log_time element_realtime) -> FilterResult {
204             if (pid && pid != element_pid) {
205                 return FilterResult::kSkip;
206             }
207             if (start == element_realtime) {
208                 sequence = element_sequence;
209                 start_time_set = true;
210                 return FilterResult::kStop;
211             } else {
212                 if (start < element_realtime) {
213                     sequence = last;
214                     start_time_set = true;
215                     return FilterResult::kStop;
216                 }
217                 last = element_sequence;
218             }
219             return FilterResult::kSkip;
220         };
221         auto lock = std::lock_guard{logd_lock};
222         auto flush_to_state = log_buffer_->CreateFlushToState(sequence, logMask);
223         log_buffer_->FlushTo(socket_log_writer.get(), *flush_to_state, log_find_start);
224 
225         if (!start_time_set) {
226             if (nonBlock) {
227                 return false;
228             }
229             sequence = log_buffer_->sequence();
230         }
231     }
232 
233     LOG(INFO) << android::base::StringPrintf(
234             "logdr: UID=%d GID=%d PID=%d %c tail=%lu logMask=%x pid=%d "
235             "start=%" PRIu64 "ns deadline=%" PRIi64 "ns",
236             cli->getUid(), cli->getGid(), cli->getPid(), nonBlock ? 'n' : 'b', tail, logMask,
237             (int)pid, start.nsec(), static_cast<int64_t>(deadline.time_since_epoch().count()));
238 
239     if (start == log_time::EPOCH) {
240         deadline = {};
241     }
242 
243     auto lock = std::lock_guard{logd_lock};
244     auto entry = std::make_unique<LogReaderThread>(log_buffer_, reader_list_,
245                                                    std::move(socket_log_writer), nonBlock, tail,
246                                                    logMask, pid, start, sequence, deadline);
247     // release client and entry reference counts once done
248     cli->incRef();
249 
250     entry->set_pending_reader_thread_key(cli->getUid(), cli->getGid(), cli->getPid(),
251                                          cli->getSocket());
252 
253     bool only_read_event_logs = (logMask ^ (1 << LOG_ID_EVENTS)) == 0;
254 
255     // The logd access will be granted when any of the following three
256     // conditions is satisfied:
257     // 1. the client (native processes) is exempted from user consent check.
258     // 2. the client doesn't have log credentials and so can only access its own log data anyway
259     // 3. the client (for EventLog API) only wants to access the event log.
260     if (clientIsExemptedFromUserConsent(cli) || !clientHasLogCredentials(cli) ||
261         only_read_event_logs) {
262         reader_list_->AddAndRunThread(std::move(entry));
263     } else {
264         if (GetLogdBinderServiceStatus(reader_list_)) {
265             reader_list_->AddPendingThread(std::move(entry));
266         } else {
267             // The logd binder service is not available, we are not able to
268             // check user consent. So we revoke the privileges.
269             entry->Revoke();
270             reader_list_->AddAndRunThread(std::move(entry));
271         }
272     }
273 
274     // Set acceptable upper limit to wait for slow reader processing b/27242723
275     struct timeval t = { LOGD_SNDTIMEO, 0 };
276     setsockopt(cli->getSocket(), SOL_SOCKET, SO_SNDTIMEO, (const char*)&t,
277                sizeof(t));
278 
279     return true;
280 }
281 
DoSocketDelete(SocketClient * cli)282 bool LogReader::DoSocketDelete(SocketClient* cli) {
283     auto cli_name = SocketClientToName(cli);
284     auto lock = std::lock_guard{logd_lock};
285     return reader_list_->ReleaseThreadByName(cli_name);
286 }
287 
getLogSocket()288 int LogReader::getLogSocket() {
289     static const char socketName[] = "logdr";
290     int sock = android_get_control_socket(socketName);
291 
292     if (sock < 0) {
293         sock = socket_local_server(
294             socketName, ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET);
295     }
296 
297     return sock;
298 }
299