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