• 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/macros.h>
40 #include <cutils/android_get_control_file.h>
41 #include <cutils/properties.h>
42 #include <cutils/sockets.h>
43 #include <log/event_tag_map.h>
44 #include <packagelistparser/packagelistparser.h>
45 #include <private/android_filesystem_config.h>
46 #include <private/android_logger.h>
47 #include <processgroup/sched_policy.h>
48 #include <utils/threads.h>
49 
50 #include "CommandListener.h"
51 #include "LogAudit.h"
52 #include "LogBuffer.h"
53 #include "LogKlog.h"
54 #include "LogListener.h"
55 #include "LogUtils.h"
56 
57 #define KMSG_PRIORITY(PRI)                                 \
58     '<', '0' + LOG_MAKEPRI(LOG_DAEMON, LOG_PRI(PRI)) / 10, \
59         '0' + LOG_MAKEPRI(LOG_DAEMON, LOG_PRI(PRI)) % 10, '>'
60 
61 // The service is designed to be run by init, it does not respond well to starting up manually. Init
62 // has a 'sigstop' feature that sends SIGSTOP to a service immediately before calling exec().  This
63 // allows debuggers, etc to be attached to logd at the very beginning, while still having init
64 // handle the user, groups, capabilities, files, etc setup.
DropPrivs(bool klogd,bool auditd)65 static int DropPrivs(bool klogd, bool auditd) {
66     if (set_sched_policy(0, SP_BACKGROUND) < 0) {
67         android::prdebug("failed to set background scheduling policy");
68         return -1;
69     }
70 
71     sched_param param = {};
72     if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
73         android::prdebug("failed to set batch scheduler");
74         return -1;
75     }
76 
77     if (!__android_logger_property_get_bool("ro.debuggable",
78                                             BOOL_DEFAULT_FALSE) &&
79         prctl(PR_SET_DUMPABLE, 0) == -1) {
80         android::prdebug("failed to clear PR_SET_DUMPABLE");
81         return -1;
82     }
83 
84     std::unique_ptr<struct _cap_struct, int (*)(void*)> caps(cap_init(), cap_free);
85     if (cap_clear(caps.get()) < 0) {
86         android::prdebug("cap_clear() failed");
87         return -1;
88     }
89     if (klogd) {
90         cap_value_t cap_syslog = CAP_SYSLOG;
91         if (cap_set_flag(caps.get(), CAP_PERMITTED, 1, &cap_syslog, CAP_SET) < 0 ||
92             cap_set_flag(caps.get(), CAP_EFFECTIVE, 1, &cap_syslog, CAP_SET) < 0) {
93             android::prdebug("Failed to set CAP_SYSLOG");
94             return -1;
95         }
96     }
97     if (auditd) {
98         cap_value_t cap_audit_control = CAP_AUDIT_CONTROL;
99         if (cap_set_flag(caps.get(), CAP_PERMITTED, 1, &cap_audit_control, CAP_SET) < 0 ||
100             cap_set_flag(caps.get(), CAP_EFFECTIVE, 1, &cap_audit_control, CAP_SET) < 0) {
101             android::prdebug("Failed to set CAP_AUDIT_CONTROL");
102             return -1;
103         }
104     }
105     if (cap_set_proc(caps.get()) < 0) {
106         android::prdebug("failed to set CAP_SYSLOG or CAP_AUDIT_CONTROL (%d)", errno);
107         return -1;
108     }
109 
110     return 0;
111 }
112 
113 // Property helper
check_flag(const char * prop,const char * flag)114 static bool check_flag(const char* prop, const char* flag) {
115     const char* cp = strcasestr(prop, flag);
116     if (!cp) {
117         return false;
118     }
119     // We only will document comma (,)
120     static const char sep[] = ",:;|+ \t\f";
121     if ((cp != prop) && !strchr(sep, cp[-1])) {
122         return false;
123     }
124     cp += strlen(flag);
125     return !*cp || !!strchr(sep, *cp);
126 }
127 
128 static int fdDmesg = -1;
prdebug(const char * fmt,...)129 void android::prdebug(const char* fmt, ...) {
130     if (fdDmesg < 0) {
131         return;
132     }
133 
134     static const char message[] = {
135         KMSG_PRIORITY(LOG_DEBUG), 'l', 'o', 'g', 'd', ':', ' '
136     };
137     char buffer[256];
138     memcpy(buffer, message, sizeof(message));
139 
140     va_list ap;
141     va_start(ap, fmt);
142     int n = vsnprintf(buffer + sizeof(message),
143                       sizeof(buffer) - sizeof(message), fmt, ap);
144     va_end(ap);
145     if (n > 0) {
146         buffer[sizeof(buffer) - 1] = '\0';
147         if (!strchr(buffer, '\n')) {
148             buffer[sizeof(buffer) - 2] = '\0';
149             strlcat(buffer, "\n", sizeof(buffer));
150         }
151         write(fdDmesg, buffer, strlen(buffer));
152     }
153 }
154 
155 static sem_t reinit;
156 static bool reinit_running = false;
157 static LogBuffer* logBuf = nullptr;
158 
reinit_thread_start(void *)159 static void* reinit_thread_start(void* /*obj*/) {
160     prctl(PR_SET_NAME, "logd.daemon");
161 
162     while (reinit_running && !sem_wait(&reinit) && reinit_running) {
163         if (fdDmesg >= 0) {
164             static const char reinit_message[] = { KMSG_PRIORITY(LOG_INFO),
165                                                    'l',
166                                                    'o',
167                                                    'g',
168                                                    'd',
169                                                    '.',
170                                                    'd',
171                                                    'a',
172                                                    'e',
173                                                    'm',
174                                                    'o',
175                                                    'n',
176                                                    ':',
177                                                    ' ',
178                                                    'r',
179                                                    'e',
180                                                    'i',
181                                                    'n',
182                                                    'i',
183                                                    't',
184                                                    '\n' };
185             write(fdDmesg, reinit_message, sizeof(reinit_message));
186         }
187 
188         // Anything that reads persist.<property>
189         if (logBuf) {
190             logBuf->init();
191             logBuf->initPrune(nullptr);
192         }
193         android::ReReadEventLogTags();
194     }
195 
196     return nullptr;
197 }
198 
uidToName(uid_t u)199 char* android::uidToName(uid_t u) {
200     struct Userdata {
201         uid_t uid;
202         char* name;
203     } userdata = {
204             .uid = u,
205             .name = nullptr,
206     };
207 
208     packagelist_parse(
209             [](pkg_info* info, void* callback_parameter) {
210                 auto userdata = reinterpret_cast<Userdata*>(callback_parameter);
211                 bool result = true;
212                 if (info->uid == userdata->uid) {
213                     userdata->name = strdup(info->name);
214                     // false to stop processing
215                     result = false;
216                 }
217                 packagelist_free(info);
218                 return result;
219             },
220             &userdata);
221 
222     return userdata.name;
223 }
224 
225 // Serves as a global method to trigger reinitialization
226 // and as a function that can be provided to signal().
reinit_signal_handler(int)227 void reinit_signal_handler(int /*signal*/) {
228     sem_post(&reinit);
229 }
230 
readDmesg(LogAudit * al,LogKlog * kl)231 static void readDmesg(LogAudit* al, LogKlog* kl) {
232     if (!al && !kl) {
233         return;
234     }
235 
236     int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
237     if (rc <= 0) {
238         return;
239     }
240 
241     // Margin for additional input race or trailing nul
242     ssize_t len = rc + 1024;
243     std::unique_ptr<char[]> buf(new char[len]);
244 
245     rc = klogctl(KLOG_READ_ALL, buf.get(), len);
246     if (rc <= 0) {
247         return;
248     }
249 
250     if (rc < len) {
251         len = rc + 1;
252     }
253     buf[--len] = '\0';
254 
255     if (kl && kl->isMonotonic()) {
256         kl->synchronize(buf.get(), len);
257     }
258 
259     ssize_t sublen;
260     for (char *ptr = nullptr, *tok = buf.get();
261          (rc >= 0) && !!(tok = android::log_strntok_r(tok, len, ptr, sublen));
262          tok = nullptr) {
263         if ((sublen <= 0) || !*tok) continue;
264         if (al) {
265             rc = al->log(tok, sublen);
266         }
267         if (kl) {
268             rc = kl->log(tok, sublen);
269         }
270     }
271 }
272 
issueReinit()273 static int issueReinit() {
274     int sock = TEMP_FAILURE_RETRY(socket_local_client(
275         "logd", ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM));
276     if (sock < 0) return -errno;
277 
278     static const char reinitStr[] = "reinit";
279     ssize_t ret = TEMP_FAILURE_RETRY(write(sock, reinitStr, sizeof(reinitStr)));
280     if (ret < 0) return -errno;
281 
282     struct pollfd p;
283     memset(&p, 0, sizeof(p));
284     p.fd = sock;
285     p.events = POLLIN;
286     ret = TEMP_FAILURE_RETRY(poll(&p, 1, 1000));
287     if (ret < 0) return -errno;
288     if ((ret == 0) || !(p.revents & POLLIN)) return -ETIME;
289 
290     static const char success[] = "success";
291     char buffer[sizeof(success) - 1];
292     memset(buffer, 0, sizeof(buffer));
293     ret = TEMP_FAILURE_RETRY(read(sock, buffer, sizeof(buffer)));
294     if (ret < 0) return -errno;
295 
296     return strncmp(buffer, success, sizeof(success) - 1) != 0;
297 }
298 
299 // Foreground waits for exit of the main persistent threads
300 // that are started here. The threads are created to manage
301 // UNIX domain client sockets for writing, reading and
302 // controlling the user space logger, and for any additional
303 // logging plugins like auditd and restart control. Additional
304 // transitory per-client threads are created for each reader.
main(int argc,char * argv[])305 int main(int argc, char* argv[]) {
306     // logd is written under the assumption that the timezone is UTC.
307     // If TZ is not set, persist.sys.timezone is looked up in some time utility
308     // libc functions, including mktime. It confuses the logd time handling,
309     // so here explicitly set TZ to UTC, which overrides the property.
310     setenv("TZ", "UTC", 1);
311     // issue reinit command. KISS argument parsing.
312     if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
313         return issueReinit();
314     }
315 
316     static const char dev_kmsg[] = "/dev/kmsg";
317     fdDmesg = android_get_control_file(dev_kmsg);
318     if (fdDmesg < 0) {
319         fdDmesg = TEMP_FAILURE_RETRY(open(dev_kmsg, O_WRONLY | O_CLOEXEC));
320     }
321 
322     int fdPmesg = -1;
323     bool klogd = __android_logger_property_get_bool(
324         "ro.logd.kernel",
325         BOOL_DEFAULT_TRUE | BOOL_DEFAULT_FLAG_ENG | BOOL_DEFAULT_FLAG_SVELTE);
326     if (klogd) {
327         static const char proc_kmsg[] = "/proc/kmsg";
328         fdPmesg = android_get_control_file(proc_kmsg);
329         if (fdPmesg < 0) {
330             fdPmesg = TEMP_FAILURE_RETRY(
331                 open(proc_kmsg, O_RDONLY | O_NDELAY | O_CLOEXEC));
332         }
333         if (fdPmesg < 0) android::prdebug("Failed to open %s\n", proc_kmsg);
334     }
335 
336     bool auditd = __android_logger_property_get_bool("ro.logd.auditd", BOOL_DEFAULT_TRUE);
337     if (DropPrivs(klogd, auditd) != 0) {
338         return EXIT_FAILURE;
339     }
340 
341     // Reinit Thread
342     sem_init(&reinit, 0, 0);
343     pthread_attr_t attr;
344     if (!pthread_attr_init(&attr)) {
345         struct sched_param param;
346 
347         memset(&param, 0, sizeof(param));
348         pthread_attr_setschedparam(&attr, &param);
349         pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
350         if (!pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
351             pthread_t thread;
352             reinit_running = true;
353             if (pthread_create(&thread, &attr, reinit_thread_start, nullptr)) {
354                 reinit_running = false;
355             }
356         }
357         pthread_attr_destroy(&attr);
358     }
359 
360     // Serves the purpose of managing the last logs times read on a
361     // socket connection, and as a reader lock on a range of log
362     // entries.
363 
364     LastLogTimes* times = new LastLogTimes();
365 
366     // LogBuffer is the object which is responsible for holding all
367     // log entries.
368 
369     logBuf = new LogBuffer(times);
370 
371     signal(SIGHUP, reinit_signal_handler);
372 
373     if (__android_logger_property_get_bool(
374             "logd.statistics", BOOL_DEFAULT_TRUE | BOOL_DEFAULT_FLAG_PERSIST |
375                                    BOOL_DEFAULT_FLAG_ENG |
376                                    BOOL_DEFAULT_FLAG_SVELTE)) {
377         logBuf->enableStatistics();
378     }
379 
380     // LogReader listens on /dev/socket/logdr. When a client
381     // connects, log entries in the LogBuffer are written to the client.
382 
383     LogReader* reader = new LogReader(logBuf);
384     if (reader->startListener()) {
385         return EXIT_FAILURE;
386     }
387 
388     // LogListener listens on /dev/socket/logdw for client
389     // initiated log messages. New log entries are added to LogBuffer
390     // and LogReader is notified to send updates to connected clients.
391 
392     LogListener* swl = new LogListener(logBuf, reader);
393     // Backlog and /proc/sys/net/unix/max_dgram_qlen set to large value
394     if (swl->startListener(600)) {
395         return EXIT_FAILURE;
396     }
397 
398     // Command listener listens on /dev/socket/logd for incoming logd
399     // administrative commands.
400 
401     CommandListener* cl = new CommandListener(logBuf, reader, swl);
402     if (cl->startListener()) {
403         return EXIT_FAILURE;
404     }
405 
406     // LogAudit listens on NETLINK_AUDIT socket for selinux
407     // initiated log messages. New log entries are added to LogBuffer
408     // and LogReader is notified to send updates to connected clients.
409 
410     LogAudit* al = nullptr;
411     if (auditd) {
412         al = new LogAudit(logBuf, reader,
413                           __android_logger_property_get_bool(
414                               "ro.logd.auditd.dmesg", BOOL_DEFAULT_TRUE)
415                               ? fdDmesg
416                               : -1);
417     }
418 
419     LogKlog* kl = nullptr;
420     if (klogd) {
421         kl = new LogKlog(logBuf, reader, fdDmesg, fdPmesg, al != nullptr);
422     }
423 
424     readDmesg(al, kl);
425 
426     // failure is an option ... messages are in dmesg (required by standard)
427 
428     if (kl && kl->startListener()) {
429         delete kl;
430     }
431 
432     if (al && al->startListener()) {
433         delete al;
434     }
435 
436     TEMP_FAILURE_RETRY(pause());
437 
438     return EXIT_SUCCESS;
439 }
440