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