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