• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
110 // GetBoolProperty that defaults to true if `ro.debuggable == true && ro.config.low_rawm == false`.
GetBoolPropertyDebuggableSvelteDefault(const std::string & name)111 static bool GetBoolPropertyDebuggableSvelteDefault(const std::string& name) {
112     bool default_value =
113             GetBoolProperty("ro.debuggable", false) && !GetBoolProperty("ro.config.low_ram", false);
114 
115     return GetBoolProperty(name, default_value);
116 }
117 
118 // GetBoolProperty that defaults to true if `ro.build.type == eng && ro.config.low_rawm == false`.
GetBoolPropertyEngSvelteDefault(const std::string & name)119 static bool GetBoolPropertyEngSvelteDefault(const std::string& name) {
120     bool default_value = (GetProperty("ro.build.type", "user").compare("eng") == 0) &&
121                          !GetBoolProperty("ro.config.low_ram", false);
122 
123     return GetBoolProperty(name, default_value);
124 }
125 
readDmesg(LogAudit * al,LogKlog * kl)126 static void readDmesg(LogAudit* al, LogKlog* kl) {
127     if (!al && !kl) {
128         return;
129     }
130 
131     int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
132     if (rc <= 0) {
133         return;
134     }
135 
136     // Margin for additional input race or trailing nul
137     ssize_t len = rc + 1024;
138     std::unique_ptr<char[]> buf(new char[len]);
139 
140     rc = klogctl(KLOG_READ_ALL, buf.get(), len);
141     if (rc <= 0) {
142         return;
143     }
144 
145     if (rc < len) {
146         len = rc + 1;
147     }
148     buf[--len] = '\0';
149 
150     ssize_t sublen;
151     for (char *ptr = nullptr, *tok = buf.get();
152          (rc >= 0) && !!(tok = android::log_strntok_r(tok, len, ptr, sublen));
153          tok = nullptr) {
154         if ((sublen <= 0) || !*tok) continue;
155         if (al) {
156             rc = al->log(tok, sublen);
157         }
158         if (kl) {
159             rc = kl->log(tok, sublen);
160         }
161     }
162 }
163 
issueReinit()164 static int issueReinit() {
165     int sock = TEMP_FAILURE_RETRY(socket_local_client(
166         "logd", ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM));
167     if (sock < 0) return -errno;
168 
169     static const char reinitStr[] = "reinit";
170     ssize_t ret = TEMP_FAILURE_RETRY(write(sock, reinitStr, sizeof(reinitStr)));
171     if (ret < 0) return -errno;
172 
173     struct pollfd p = {.fd = sock, .events = POLLIN};
174     ret = TEMP_FAILURE_RETRY(poll(&p, 1, 1000));
175     if (ret < 0) return -errno;
176     if ((ret == 0) || !(p.revents & POLLIN)) return -ETIME;
177 
178     static const char success[] = "success";
179     char buffer[sizeof(success) - 1] = {};
180     ret = TEMP_FAILURE_RETRY(read(sock, buffer, sizeof(buffer)));
181     if (ret < 0) return -errno;
182 
183     return strncmp(buffer, success, sizeof(success) - 1) != 0;
184 }
185 
186 // Foreground waits for exit of the main persistent threads
187 // that are started here. The threads are created to manage
188 // UNIX domain client sockets for writing, reading and
189 // controlling the user space logger, and for any additional
190 // logging plugins like auditd and restart control. Additional
191 // transitory per-client threads are created for each reader.
main(int argc,char * argv[])192 int main(int argc, char* argv[]) {
193     // We want EPIPE when a reader disconnects, not to terminate logd.
194     signal(SIGPIPE, SIG_IGN);
195     // logd is written under the assumption that the timezone is UTC.
196     // If TZ is not set, persist.sys.timezone is looked up in some time utility
197     // libc functions, including mktime. It confuses the logd time handling,
198     // so here explicitly set TZ to UTC, which overrides the property.
199     setenv("TZ", "UTC", 1);
200     // issue reinit command. KISS argument parsing.
201     if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
202         return issueReinit();
203     }
204 
205     android::base::InitLogging(
206             argv, [](android::base::LogId log_id, android::base::LogSeverity severity,
207                      const char* tag, const char* file, unsigned int line, const char* message) {
208                 if (tag && strcmp(tag, "logd") != 0) {
209                     auto prefixed_message = android::base::StringPrintf("%s: %s", tag, message);
210                     android::base::KernelLogger(log_id, severity, "logd", file, line,
211                                                 prefixed_message.c_str());
212                 } else {
213                     android::base::KernelLogger(log_id, severity, "logd", file, line, message);
214                 }
215             });
216 
217     static const char dev_kmsg[] = "/dev/kmsg";
218     int fdDmesg = android_get_control_file(dev_kmsg);
219     if (fdDmesg < 0) {
220         fdDmesg = TEMP_FAILURE_RETRY(open(dev_kmsg, O_WRONLY | O_CLOEXEC));
221     }
222 
223     int fdPmesg = -1;
224     bool klogd = GetBoolPropertyDebuggableSvelteDefault("ro.logd.kernel");
225     if (klogd) {
226         SetProperty("ro.logd.kernel", "true");
227         static const char proc_kmsg[] = "/proc/kmsg";
228         fdPmesg = android_get_control_file(proc_kmsg);
229         if (fdPmesg < 0) {
230             fdPmesg = TEMP_FAILURE_RETRY(
231                 open(proc_kmsg, O_RDONLY | O_NDELAY | O_CLOEXEC));
232         }
233         if (fdPmesg < 0) PLOG(ERROR) << "Failed to open " << proc_kmsg;
234     }
235 
236     bool auditd = GetBoolProperty("ro.logd.auditd", true);
237     DropPrivs(klogd, auditd);
238 
239     // A cache of event log tags
240     LogTags log_tags;
241 
242     // Pruning configuration.
243     PruneList prune_list;
244 
245     std::string buffer_type = GetProperty("logd.buffer_type", "serialized");
246 
247     LogStatistics log_statistics(GetBoolPropertyEngSvelteDefault("logd.statistics"),
248                                  buffer_type == "serialized");
249 
250     // Serves the purpose of managing the last logs times read on a socket connection, and as a
251     // reader lock on a range of log entries.
252     LogReaderList reader_list;
253 
254     // LogBuffer is the object which is responsible for holding all log entries.
255     LogBuffer* log_buffer = nullptr;
256     if (buffer_type == "serialized") {
257         log_buffer = new SerializedLogBuffer(&reader_list, &log_tags, &log_statistics);
258     } else if (buffer_type == "simple") {
259         log_buffer = new SimpleLogBuffer(&reader_list, &log_tags, &log_statistics);
260     } else {
261         LOG(FATAL) << "buffer_type must be one of 'serialized' or 'simple'";
262     }
263 
264     // LogReader listens on /dev/socket/logdr. When a client
265     // connects, log entries in the LogBuffer are written to the client.
266     LogReader* reader = new LogReader(log_buffer, &reader_list);
267     if (reader->startListener()) {
268         return EXIT_FAILURE;
269     }
270 
271     // LogListener listens on /dev/socket/logdw for client
272     // initiated log messages. New log entries are added to LogBuffer
273     // and LogReader is notified to send updates to connected clients.
274     LogListener* swl = new LogListener(log_buffer);
275     if (!swl->StartListener()) {
276         return EXIT_FAILURE;
277     }
278 
279     // Command listener listens on /dev/socket/logd for incoming logd
280     // administrative commands.
281     CommandListener* cl = new CommandListener(log_buffer, &log_tags, &prune_list, &log_statistics);
282     if (cl->startListener()) {
283         return EXIT_FAILURE;
284     }
285 
286     // Notify that others can now interact with logd
287     SetProperty("logd.ready", "true");
288 
289     // LogAudit listens on NETLINK_AUDIT socket for selinux
290     // initiated log messages. New log entries are added to LogBuffer
291     // and LogReader is notified to send updates to connected clients.
292     LogAudit* al = nullptr;
293     if (auditd) {
294         int dmesg_fd = GetBoolProperty("ro.logd.auditd.dmesg", true) ? fdDmesg : -1;
295         al = new LogAudit(log_buffer, dmesg_fd, &log_statistics);
296     }
297 
298     LogKlog* kl = nullptr;
299     if (klogd) {
300         kl = new LogKlog(log_buffer, fdDmesg, fdPmesg, al != nullptr, &log_statistics);
301     }
302 
303     readDmesg(al, kl);
304 
305     // failure is an option ... messages are in dmesg (required by standard)
306     if (kl && kl->startListener()) {
307         delete kl;
308     }
309 
310     if (al && al->startListener()) {
311         delete al;
312     }
313 
314     TrustyLog::create(log_buffer);
315 
316     TEMP_FAILURE_RETRY(pause());
317 
318     return EXIT_SUCCESS;
319 }
320