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 <dirent.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <linux/capability.h>
21 #include <poll.h>
22 #include <sched.h>
23 #include <semaphore.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/capability.h>
29 #include <sys/klog.h>
30 #include <sys/prctl.h>
31 #include <sys/resource.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <syslog.h>
35 #include <unistd.h>
36
37 #include <memory>
38
39 #include <android-base/logging.h>
40 #include <android-base/macros.h>
41 #include <android-base/properties.h>
42 #include <android-base/stringprintf.h>
43 #include <cutils/android_get_control_file.h>
44 #include <cutils/sockets.h>
45 #include <log/event_tag_map.h>
46 #include <private/android_filesystem_config.h>
47 #include <private/android_logger.h>
48 #include <processgroup/sched_policy.h>
49 #include <utils/threads.h>
50
51 #include "ChattyLogBuffer.h"
52 #include "CommandListener.h"
53 #include "LogAudit.h"
54 #include "LogBuffer.h"
55 #include "LogKlog.h"
56 #include "LogListener.h"
57 #include "LogReader.h"
58 #include "LogStatistics.h"
59 #include "LogTags.h"
60 #include "LogUtils.h"
61 #include "SerializedLogBuffer.h"
62 #include "SimpleLogBuffer.h"
63 #include "TrustyLog.h"
64
65 using android::base::GetBoolProperty;
66 using android::base::GetProperty;
67 using android::base::SetProperty;
68
69 #define KMSG_PRIORITY(PRI) \
70 '<', '0' + LOG_MAKEPRI(LOG_DAEMON, LOG_PRI(PRI)) / 10, \
71 '0' + LOG_MAKEPRI(LOG_DAEMON, LOG_PRI(PRI)) % 10, '>'
72
73 // The service is designed to be run by init, it does not respond well to starting up manually. Init
74 // has a 'sigstop' feature that sends SIGSTOP to a service immediately before calling exec(). This
75 // allows debuggers, etc to be attached to logd at the very beginning, while still having init
76 // handle the user, groups, capabilities, files, etc setup.
DropPrivs(bool klogd,bool auditd)77 static void DropPrivs(bool klogd, bool auditd) {
78 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
79 PLOG(FATAL) << "failed to set background scheduling policy";
80 }
81
82 if (!GetBoolProperty("ro.debuggable", false)) {
83 if (prctl(PR_SET_DUMPABLE, 0) == -1) {
84 PLOG(FATAL) << "failed to clear PR_SET_DUMPABLE";
85 }
86 }
87
88 std::unique_ptr<struct _cap_struct, int (*)(void*)> caps(cap_init(), cap_free);
89 if (cap_clear(caps.get()) < 0) {
90 PLOG(FATAL) << "cap_clear() failed";
91 }
92 if (klogd) {
93 cap_value_t cap_syslog = CAP_SYSLOG;
94 if (cap_set_flag(caps.get(), CAP_PERMITTED, 1, &cap_syslog, CAP_SET) < 0 ||
95 cap_set_flag(caps.get(), CAP_EFFECTIVE, 1, &cap_syslog, CAP_SET) < 0) {
96 PLOG(FATAL) << "Failed to set CAP_SYSLOG";
97 }
98 }
99 if (auditd) {
100 cap_value_t cap_audit_control = CAP_AUDIT_CONTROL;
101 if (cap_set_flag(caps.get(), CAP_PERMITTED, 1, &cap_audit_control, CAP_SET) < 0 ||
102 cap_set_flag(caps.get(), CAP_EFFECTIVE, 1, &cap_audit_control, CAP_SET) < 0) {
103 PLOG(FATAL) << "Failed to set CAP_AUDIT_CONTROL";
104 }
105 }
106 if (cap_set_proc(caps.get()) < 0) {
107 PLOG(FATAL) << "cap_set_proc() failed";
108 }
109 }
110
111 // GetBoolProperty that defaults to true if `ro.debuggable == true && ro.config.low_rawm == false`.
GetBoolPropertyEngSvelteDefault(const std::string & name)112 static bool GetBoolPropertyEngSvelteDefault(const std::string& name) {
113 bool default_value =
114 GetBoolProperty("ro.debuggable", false) && !GetBoolProperty("ro.config.low_ram", false);
115
116 return GetBoolProperty(name, default_value);
117 }
118
readDmesg(LogAudit * al,LogKlog * kl)119 static void readDmesg(LogAudit* al, LogKlog* kl) {
120 if (!al && !kl) {
121 return;
122 }
123
124 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
125 if (rc <= 0) {
126 return;
127 }
128
129 // Margin for additional input race or trailing nul
130 ssize_t len = rc + 1024;
131 std::unique_ptr<char[]> buf(new char[len]);
132
133 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
134 if (rc <= 0) {
135 return;
136 }
137
138 if (rc < len) {
139 len = rc + 1;
140 }
141 buf[--len] = '\0';
142
143 ssize_t sublen;
144 for (char *ptr = nullptr, *tok = buf.get();
145 (rc >= 0) && !!(tok = android::log_strntok_r(tok, len, ptr, sublen));
146 tok = nullptr) {
147 if ((sublen <= 0) || !*tok) continue;
148 if (al) {
149 rc = al->log(tok, sublen);
150 }
151 if (kl) {
152 rc = kl->log(tok, sublen);
153 }
154 }
155 }
156
issueReinit()157 static int issueReinit() {
158 int sock = TEMP_FAILURE_RETRY(socket_local_client(
159 "logd", ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM));
160 if (sock < 0) return -errno;
161
162 static const char reinitStr[] = "reinit";
163 ssize_t ret = TEMP_FAILURE_RETRY(write(sock, reinitStr, sizeof(reinitStr)));
164 if (ret < 0) return -errno;
165
166 struct pollfd p = {.fd = sock, .events = POLLIN};
167 ret = TEMP_FAILURE_RETRY(poll(&p, 1, 1000));
168 if (ret < 0) return -errno;
169 if ((ret == 0) || !(p.revents & POLLIN)) return -ETIME;
170
171 static const char success[] = "success";
172 char buffer[sizeof(success) - 1] = {};
173 ret = TEMP_FAILURE_RETRY(read(sock, buffer, sizeof(buffer)));
174 if (ret < 0) return -errno;
175
176 return strncmp(buffer, success, sizeof(success) - 1) != 0;
177 }
178
179 // Foreground waits for exit of the main persistent threads
180 // that are started here. The threads are created to manage
181 // UNIX domain client sockets for writing, reading and
182 // controlling the user space logger, and for any additional
183 // logging plugins like auditd and restart control. Additional
184 // transitory per-client threads are created for each reader.
main(int argc,char * argv[])185 int main(int argc, char* argv[]) {
186 // We want EPIPE when a reader disconnects, not to terminate logd.
187 signal(SIGPIPE, SIG_IGN);
188 // logd is written under the assumption that the timezone is UTC.
189 // If TZ is not set, persist.sys.timezone is looked up in some time utility
190 // libc functions, including mktime. It confuses the logd time handling,
191 // so here explicitly set TZ to UTC, which overrides the property.
192 setenv("TZ", "UTC", 1);
193 // issue reinit command. KISS argument parsing.
194 if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
195 return issueReinit();
196 }
197
198 android::base::InitLogging(
199 argv, [](android::base::LogId log_id, android::base::LogSeverity severity,
200 const char* tag, const char* file, unsigned int line, const char* message) {
201 if (tag && strcmp(tag, "logd") != 0) {
202 auto prefixed_message = android::base::StringPrintf("%s: %s", tag, message);
203 android::base::KernelLogger(log_id, severity, "logd", file, line,
204 prefixed_message.c_str());
205 } else {
206 android::base::KernelLogger(log_id, severity, "logd", file, line, message);
207 }
208 });
209
210 static const char dev_kmsg[] = "/dev/kmsg";
211 int fdDmesg = android_get_control_file(dev_kmsg);
212 if (fdDmesg < 0) {
213 fdDmesg = TEMP_FAILURE_RETRY(open(dev_kmsg, O_WRONLY | O_CLOEXEC));
214 }
215
216 int fdPmesg = -1;
217 bool klogd = GetBoolPropertyEngSvelteDefault("ro.logd.kernel");
218 if (klogd) {
219 SetProperty("ro.logd.kernel", "true");
220 static const char proc_kmsg[] = "/proc/kmsg";
221 fdPmesg = android_get_control_file(proc_kmsg);
222 if (fdPmesg < 0) {
223 fdPmesg = TEMP_FAILURE_RETRY(
224 open(proc_kmsg, O_RDONLY | O_NDELAY | O_CLOEXEC));
225 }
226 if (fdPmesg < 0) PLOG(ERROR) << "Failed to open " << proc_kmsg;
227 }
228
229 bool auditd = GetBoolProperty("ro.logd.auditd", true);
230 DropPrivs(klogd, auditd);
231
232 // A cache of event log tags
233 LogTags log_tags;
234
235 // Pruning configuration.
236 PruneList prune_list;
237
238 std::string buffer_type = GetProperty("logd.buffer_type", "serialized");
239
240 // Partial (required for chatty) or full logging statistics.
241 LogStatistics log_statistics(GetBoolPropertyEngSvelteDefault("logd.statistics"),
242 buffer_type == "serialized");
243
244 // Serves the purpose of managing the last logs times read on a socket connection, and as a
245 // reader lock on a range of log entries.
246 LogReaderList reader_list;
247
248 // LogBuffer is the object which is responsible for holding all log entries.
249 LogBuffer* log_buffer = nullptr;
250 if (buffer_type == "chatty") {
251 log_buffer = new ChattyLogBuffer(&reader_list, &log_tags, &prune_list, &log_statistics);
252 } else if (buffer_type == "serialized") {
253 log_buffer = new SerializedLogBuffer(&reader_list, &log_tags, &log_statistics);
254 } else if (buffer_type == "simple") {
255 log_buffer = new SimpleLogBuffer(&reader_list, &log_tags, &log_statistics);
256 } else {
257 LOG(FATAL) << "buffer_type must be one of 'chatty', 'serialized', or 'simple'";
258 }
259
260 // LogReader listens on /dev/socket/logdr. When a client
261 // connects, log entries in the LogBuffer are written to the client.
262 LogReader* reader = new LogReader(log_buffer, &reader_list);
263 if (reader->startListener()) {
264 return EXIT_FAILURE;
265 }
266
267 // LogListener listens on /dev/socket/logdw for client
268 // initiated log messages. New log entries are added to LogBuffer
269 // and LogReader is notified to send updates to connected clients.
270 LogListener* swl = new LogListener(log_buffer);
271 if (!swl->StartListener()) {
272 return EXIT_FAILURE;
273 }
274
275 // Command listener listens on /dev/socket/logd for incoming logd
276 // administrative commands.
277 CommandListener* cl = new CommandListener(log_buffer, &log_tags, &prune_list, &log_statistics);
278 if (cl->startListener()) {
279 return EXIT_FAILURE;
280 }
281
282 // Notify that others can now interact with logd
283 SetProperty("logd.ready", "true");
284
285 // LogAudit listens on NETLINK_AUDIT socket for selinux
286 // initiated log messages. New log entries are added to LogBuffer
287 // and LogReader is notified to send updates to connected clients.
288 LogAudit* al = nullptr;
289 if (auditd) {
290 int dmesg_fd = GetBoolProperty("ro.logd.auditd.dmesg", true) ? fdDmesg : -1;
291 al = new LogAudit(log_buffer, dmesg_fd, &log_statistics);
292 }
293
294 LogKlog* kl = nullptr;
295 if (klogd) {
296 kl = new LogKlog(log_buffer, fdDmesg, fdPmesg, al != nullptr, &log_statistics);
297 }
298
299 readDmesg(al, kl);
300
301 // failure is an option ... messages are in dmesg (required by standard)
302 if (kl && kl->startListener()) {
303 delete kl;
304 }
305
306 if (al && al->startListener()) {
307 delete al;
308 }
309
310 TrustyLog::create(log_buffer);
311
312 TEMP_FAILURE_RETRY(pause());
313
314 return EXIT_SUCCESS;
315 }
316