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 <packagelistparser/packagelistparser.h>
47 #include <private/android_filesystem_config.h>
48 #include <private/android_logger.h>
49 #include <processgroup/sched_policy.h>
50 #include <utils/threads.h>
51
52 #include "ChattyLogBuffer.h"
53 #include "CommandListener.h"
54 #include "LogAudit.h"
55 #include "LogBuffer.h"
56 #include "LogKlog.h"
57 #include "LogListener.h"
58 #include "LogReader.h"
59 #include "LogStatistics.h"
60 #include "LogTags.h"
61 #include "LogUtils.h"
62 #include "SerializedLogBuffer.h"
63 #include "SimpleLogBuffer.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 sched_param param = {};
83 if (sched_setscheduler((pid_t)0, SCHED_BATCH, ¶m) < 0) {
84 PLOG(FATAL) << "failed to set batch scheduler";
85 }
86
87 if (!GetBoolProperty("ro.debuggable", false)) {
88 if (prctl(PR_SET_DUMPABLE, 0) == -1) {
89 PLOG(FATAL) << "failed to clear PR_SET_DUMPABLE";
90 }
91 }
92
93 std::unique_ptr<struct _cap_struct, int (*)(void*)> caps(cap_init(), cap_free);
94 if (cap_clear(caps.get()) < 0) {
95 PLOG(FATAL) << "cap_clear() failed";
96 }
97 if (klogd) {
98 cap_value_t cap_syslog = CAP_SYSLOG;
99 if (cap_set_flag(caps.get(), CAP_PERMITTED, 1, &cap_syslog, CAP_SET) < 0 ||
100 cap_set_flag(caps.get(), CAP_EFFECTIVE, 1, &cap_syslog, CAP_SET) < 0) {
101 PLOG(FATAL) << "Failed to set CAP_SYSLOG";
102 }
103 }
104 if (auditd) {
105 cap_value_t cap_audit_control = CAP_AUDIT_CONTROL;
106 if (cap_set_flag(caps.get(), CAP_PERMITTED, 1, &cap_audit_control, CAP_SET) < 0 ||
107 cap_set_flag(caps.get(), CAP_EFFECTIVE, 1, &cap_audit_control, CAP_SET) < 0) {
108 PLOG(FATAL) << "Failed to set CAP_AUDIT_CONTROL";
109 }
110 }
111 if (cap_set_proc(caps.get()) < 0) {
112 PLOG(FATAL) << "cap_set_proc() failed";
113 }
114 }
115
116 // GetBoolProperty that defaults to true if `ro.debuggable == true && ro.config.low_rawm == false`.
GetBoolPropertyEngSvelteDefault(const std::string & name)117 static bool GetBoolPropertyEngSvelteDefault(const std::string& name) {
118 bool default_value =
119 GetBoolProperty("ro.debuggable", false) && !GetBoolProperty("ro.config.low_ram", false);
120
121 return GetBoolProperty(name, default_value);
122 }
123
uidToName(uid_t u)124 char* android::uidToName(uid_t u) {
125 struct Userdata {
126 uid_t uid;
127 char* name;
128 } userdata = {
129 .uid = u,
130 .name = nullptr,
131 };
132
133 packagelist_parse(
134 [](pkg_info* info, void* callback_parameter) {
135 auto userdata = reinterpret_cast<Userdata*>(callback_parameter);
136 bool result = true;
137 if (info->uid == userdata->uid) {
138 userdata->name = strdup(info->name);
139 // false to stop processing
140 result = false;
141 }
142 packagelist_free(info);
143 return result;
144 },
145 &userdata);
146
147 return userdata.name;
148 }
149
readDmesg(LogAudit * al,LogKlog * kl)150 static void readDmesg(LogAudit* al, LogKlog* kl) {
151 if (!al && !kl) {
152 return;
153 }
154
155 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
156 if (rc <= 0) {
157 return;
158 }
159
160 // Margin for additional input race or trailing nul
161 ssize_t len = rc + 1024;
162 std::unique_ptr<char[]> buf(new char[len]);
163
164 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
165 if (rc <= 0) {
166 return;
167 }
168
169 if (rc < len) {
170 len = rc + 1;
171 }
172 buf[--len] = '\0';
173
174 ssize_t sublen;
175 for (char *ptr = nullptr, *tok = buf.get();
176 (rc >= 0) && !!(tok = android::log_strntok_r(tok, len, ptr, sublen));
177 tok = nullptr) {
178 if ((sublen <= 0) || !*tok) continue;
179 if (al) {
180 rc = al->log(tok, sublen);
181 }
182 if (kl) {
183 rc = kl->log(tok, sublen);
184 }
185 }
186 }
187
issueReinit()188 static int issueReinit() {
189 int sock = TEMP_FAILURE_RETRY(socket_local_client(
190 "logd", ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM));
191 if (sock < 0) return -errno;
192
193 static const char reinitStr[] = "reinit";
194 ssize_t ret = TEMP_FAILURE_RETRY(write(sock, reinitStr, sizeof(reinitStr)));
195 if (ret < 0) return -errno;
196
197 struct pollfd p;
198 memset(&p, 0, sizeof(p));
199 p.fd = sock;
200 p.events = POLLIN;
201 ret = TEMP_FAILURE_RETRY(poll(&p, 1, 1000));
202 if (ret < 0) return -errno;
203 if ((ret == 0) || !(p.revents & POLLIN)) return -ETIME;
204
205 static const char success[] = "success";
206 char buffer[sizeof(success) - 1];
207 memset(buffer, 0, sizeof(buffer));
208 ret = TEMP_FAILURE_RETRY(read(sock, buffer, sizeof(buffer)));
209 if (ret < 0) return -errno;
210
211 return strncmp(buffer, success, sizeof(success) - 1) != 0;
212 }
213
214 // Foreground waits for exit of the main persistent threads
215 // that are started here. The threads are created to manage
216 // UNIX domain client sockets for writing, reading and
217 // controlling the user space logger, and for any additional
218 // logging plugins like auditd and restart control. Additional
219 // transitory per-client threads are created for each reader.
main(int argc,char * argv[])220 int main(int argc, char* argv[]) {
221 // logd is written under the assumption that the timezone is UTC.
222 // If TZ is not set, persist.sys.timezone is looked up in some time utility
223 // libc functions, including mktime. It confuses the logd time handling,
224 // so here explicitly set TZ to UTC, which overrides the property.
225 setenv("TZ", "UTC", 1);
226 // issue reinit command. KISS argument parsing.
227 if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
228 return issueReinit();
229 }
230
231 android::base::InitLogging(
232 argv, [](android::base::LogId log_id, android::base::LogSeverity severity,
233 const char* tag, const char* file, unsigned int line, const char* message) {
234 if (tag && strcmp(tag, "logd") != 0) {
235 auto prefixed_message = android::base::StringPrintf("%s: %s", tag, message);
236 android::base::KernelLogger(log_id, severity, "logd", file, line,
237 prefixed_message.c_str());
238 } else {
239 android::base::KernelLogger(log_id, severity, "logd", file, line, message);
240 }
241 });
242
243 static const char dev_kmsg[] = "/dev/kmsg";
244 int fdDmesg = android_get_control_file(dev_kmsg);
245 if (fdDmesg < 0) {
246 fdDmesg = TEMP_FAILURE_RETRY(open(dev_kmsg, O_WRONLY | O_CLOEXEC));
247 }
248
249 int fdPmesg = -1;
250 bool klogd = GetBoolPropertyEngSvelteDefault("ro.logd.kernel");
251 if (klogd) {
252 SetProperty("ro.logd.kernel", "true");
253 static const char proc_kmsg[] = "/proc/kmsg";
254 fdPmesg = android_get_control_file(proc_kmsg);
255 if (fdPmesg < 0) {
256 fdPmesg = TEMP_FAILURE_RETRY(
257 open(proc_kmsg, O_RDONLY | O_NDELAY | O_CLOEXEC));
258 }
259 if (fdPmesg < 0) PLOG(ERROR) << "Failed to open " << proc_kmsg;
260 }
261
262 bool auditd = GetBoolProperty("ro.logd.auditd", true);
263 DropPrivs(klogd, auditd);
264
265 // A cache of event log tags
266 LogTags log_tags;
267
268 // Pruning configuration.
269 PruneList prune_list;
270
271 std::string buffer_type = GetProperty("logd.buffer_type", "serialized");
272
273 // Partial (required for chatty) or full logging statistics.
274 LogStatistics log_statistics(GetBoolPropertyEngSvelteDefault("logd.statistics"),
275 buffer_type == "serialized");
276
277 // Serves the purpose of managing the last logs times read on a socket connection, and as a
278 // reader lock on a range of log entries.
279 LogReaderList reader_list;
280
281 // LogBuffer is the object which is responsible for holding all log entries.
282 LogBuffer* log_buffer = nullptr;
283 if (buffer_type == "chatty") {
284 log_buffer = new ChattyLogBuffer(&reader_list, &log_tags, &prune_list, &log_statistics);
285 } else if (buffer_type == "serialized") {
286 log_buffer = new SerializedLogBuffer(&reader_list, &log_tags, &log_statistics);
287 } else if (buffer_type == "simple") {
288 log_buffer = new SimpleLogBuffer(&reader_list, &log_tags, &log_statistics);
289 } else {
290 LOG(FATAL) << "buffer_type must be one of 'chatty', 'serialized', or 'simple'";
291 }
292
293 // LogReader listens on /dev/socket/logdr. When a client
294 // connects, log entries in the LogBuffer are written to the client.
295 LogReader* reader = new LogReader(log_buffer, &reader_list);
296 if (reader->startListener()) {
297 return EXIT_FAILURE;
298 }
299
300 // LogListener listens on /dev/socket/logdw for client
301 // initiated log messages. New log entries are added to LogBuffer
302 // and LogReader is notified to send updates to connected clients.
303 LogListener* swl = new LogListener(log_buffer);
304 if (!swl->StartListener()) {
305 return EXIT_FAILURE;
306 }
307
308 // Command listener listens on /dev/socket/logd for incoming logd
309 // administrative commands.
310 CommandListener* cl = new CommandListener(log_buffer, &log_tags, &prune_list, &log_statistics);
311 if (cl->startListener()) {
312 return EXIT_FAILURE;
313 }
314
315 // LogAudit listens on NETLINK_AUDIT socket for selinux
316 // initiated log messages. New log entries are added to LogBuffer
317 // and LogReader is notified to send updates to connected clients.
318 LogAudit* al = nullptr;
319 if (auditd) {
320 int dmesg_fd = GetBoolProperty("ro.logd.auditd.dmesg", true) ? fdDmesg : -1;
321 al = new LogAudit(log_buffer, dmesg_fd, &log_statistics);
322 }
323
324 LogKlog* kl = nullptr;
325 if (klogd) {
326 kl = new LogKlog(log_buffer, fdDmesg, fdPmesg, al != nullptr, &log_statistics);
327 }
328
329 readDmesg(al, kl);
330
331 // failure is an option ... messages are in dmesg (required by standard)
332 if (kl && kl->startListener()) {
333 delete kl;
334 }
335
336 if (al && al->startListener()) {
337 delete al;
338 }
339
340 TEMP_FAILURE_RETRY(pause());
341
342 return EXIT_SUCCESS;
343 }
344