blob: c69bd8a0aa3cf2b4a1cff3571c210cfc00ac647d [file] [log] [blame]
Elly Jones03cd6d72012-06-11 13:04:28 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Alex Vakulenko262be3f2014-07-30 15:25:50 -07005#include "debugd/src/log_tool.h"
Elly Jones03cd6d72012-06-11 13:04:28 -04006
Mike Frysinger020c2402020-12-16 05:40:53 -05007#include <glob.h>
Fletcher Woodruff07c28532019-01-24 11:08:53 -07008#include <grp.h>
9#include <inttypes.h>
Chinglin Yuaeb4ec72018-12-10 18:53:30 +080010#include <lzma.h>
Fletcher Woodruff07c28532019-01-24 11:08:53 -070011#include <pwd.h>
12#include <stdint.h>
13#include <sys/types.h>
14#include <unistd.h>
Ben Chan8e9f6d02017-09-26 23:04:21 -070015#include <memory>
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -070016#include <string>
Fletcher Woodruff07c28532019-01-24 11:08:53 -070017#include <utility>
Ben Chana0011d82014-05-13 00:19:29 -070018#include <vector>
19
Ben Chanab93abf2017-01-24 13:32:51 -080020#include <base/base64.h>
Fletcher Woodruff07c28532019-01-24 11:08:53 -070021#include <base/files/file.h>
22#include <base/files/file_path.h>
Ben Chancd8fda42014-09-05 08:21:06 -070023#include <base/files/file_util.h>
Ahmed Fakhry21140cf2016-03-04 17:15:19 -080024#include <base/json/json_writer.h>
Elly Jones03cd6d72012-06-11 13:04:28 -040025#include <base/logging.h>
Ben Chan9953a592014-02-05 23:32:00 -080026#include <base/strings/string_split.h>
27#include <base/strings/string_util.h>
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -070028#include <base/strings/stringprintf.h>
29#include <base/strings/utf_string_conversion_utils.h>
Ahmed Fakhry21140cf2016-03-04 17:15:19 -080030#include <base/values.h>
Elly Jones03cd6d72012-06-11 13:04:28 -040031
Rebecca Silbersteine78af402014-10-02 10:55:04 -070032#include <chromeos/dbus/service_constants.h>
Eric Carusocc7106c2017-04-27 14:22:42 -070033#include <shill/dbus-proxies.h>
Rebecca Silbersteine78af402014-10-02 10:55:04 -070034
Ben Chanaf125862017-02-08 23:11:18 -080035#include "debugd/src/constants.h"
Chinglin Yuaeb4ec72018-12-10 18:53:30 +080036#include "debugd/src/perf_tool.h"
Alex Vakulenko262be3f2014-07-30 15:25:50 -070037#include "debugd/src/process_with_output.h"
Elly Jones03cd6d72012-06-11 13:04:28 -040038
Kartik Hegde1c4b97b2018-09-09 19:09:34 -060039#include "brillo/key_value_store.h"
40#include <brillo/osrelease_reader.h>
mhasank86c46c72020-08-13 15:36:29 -070041#include <brillo/cryptohome.h>
Kartik Hegde1c4b97b2018-09-09 19:09:34 -060042
Elly Jones03cd6d72012-06-11 13:04:28 -040043namespace debugd {
44
Elly Jones03cd6d72012-06-11 13:04:28 -040045using std::string;
Elly Jones03cd6d72012-06-11 13:04:28 -040046
Eric Caruso96d03d32017-04-25 18:01:17 -070047using Strings = std::vector<string>;
Elly Jones03cd6d72012-06-11 13:04:28 -040048
Ahmed Fakhry21140cf2016-03-04 17:15:19 -080049namespace {
50
Ben Chanaf125862017-02-08 23:11:18 -080051const char kRoot[] = "root";
52const char kShell[] = "/bin/sh";
Kartik Hegde1c4b97b2018-09-09 19:09:34 -060053constexpr char kLsbReleasePath[] = "/etc/lsb-release";
mhasank80cbe4d2020-04-02 22:46:08 -070054constexpr char kArcBugReportBackupFileName[] = "arc-bugreport.log";
mhasankd2b84882020-05-04 17:02:19 -070055constexpr char kArcBugReportBackupKey[] = "arc-bugreport-backup";
mhasank80cbe4d2020-04-02 22:46:08 -070056constexpr char kDaemonStoreBaseDir[] = "/run/daemon-store/debugd/";
Ahmed Fakhry21140cf2016-03-04 17:15:19 -080057
58// Minimum time in seconds needed to allow shill to test active connections.
59const int kConnectionTesterTimeoutSeconds = 5;
Ben Chanf6cd93a2012-10-14 19:37:00 -070060
Chinglin Yuaeb4ec72018-12-10 18:53:30 +080061// Default running perf for 2 seconds.
62constexpr const int kPerfDurationSecs = 2;
Chinglin Yu3c8d0a22019-02-20 11:32:52 +080063// TODO(chinglinyu) Remove after crbug/934702 is fixed.
64// The following description is added to 'perf-data' as a temporary solution
65// before the update of feedback disclosure to users is done in crbug/934702.
66constexpr const char kPerfDataDescription[] =
67 "perf-data contains performance profiling information about how much time "
68 "the system spends on various activities (program execution stack traces). "
69 "This might reveal some information about what system features and "
70 "resources are being used. The full detail of perf-data can be found in "
71 "the PerfDataProto protocol buffer message type in the chromium source "
72 "repository.\n";
Chinglin Yuaeb4ec72018-12-10 18:53:30 +080073
Eric Carusoa879fd92017-10-11 12:57:10 -070074#define CMD_KERNEL_MODULE_PARAMS(module_name) \
Tom Hughesd6c2d392020-08-24 18:12:11 -070075 "cd /sys/module/" #module_name "/parameters 2>/dev/null && grep -sH ^ *"
Eric Carusoa879fd92017-10-11 12:57:10 -070076
Fletcher Woodruff07c28532019-01-24 11:08:53 -070077using Log = LogTool::Log;
78constexpr Log::LogType kCommand = Log::kCommand;
79constexpr Log::LogType kFile = Log::kFile;
Mike Frysinger020c2402020-12-16 05:40:53 -050080constexpr Log::LogType kGlob = Log::kGlob;
mhasankaf5251d2020-04-29 18:53:03 -070081
82class ArcBugReportLog : public LogTool::Log {
83 public:
84 ArcBugReportLog()
85 : Log(kCommand,
86 "arc-bugreport",
87 "/usr/bin/nsenter -t1 -m /usr/sbin/android-sh -c "
88 "/system/bin/arc-bugreport",
89 kRoot,
90 kRoot,
91 10 * 1024 * 1024 /*10 MiB*/,
92 LogTool::Encoding::kUtf8) {}
93
94 virtual ~ArcBugReportLog() = default;
95};
mhasank80cbe4d2020-04-02 22:46:08 -070096
Miriam Zimmermand91d8e72019-06-27 12:24:04 -070097// NOTE: IF YOU ADD AN ENTRY TO THIS LIST, PLEASE:
98// * add a row to http://go/cros-feedback-audit and fill it out
Miriam Zimmerman4f142ba2020-06-01 14:15:21 -070099// * email cros-telemetry@
Miriam Zimmermand91d8e72019-06-27 12:24:04 -0700100// (Eventually we'll have a better process, but for now please do this.)
Tom Hughesd6c2d392020-08-24 18:12:11 -0700101// clang-format off
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700102const std::vector<Log> kCommandLogs {
Mike Frysingerb0350992018-09-14 13:45:35 -0400103 // We need to enter init's mount namespace because it has /home/chronos
104 // mounted which is where the consent knob lives. We don't have that mount
105 // in our own mount namespace (by design). https://crbug.com/884249
Chris Morin853d3442019-04-01 21:35:13 -0700106 {kCommand, "CLIENT_ID", "/usr/bin/nsenter -t1 -m /usr/bin/metrics_client -i",
107 kRoot, kDebugfsGroup},
108 {kCommand, "LOGDATE", "/bin/date"},
Yusuke Sato27a31672019-04-29 15:26:37 -0700109 // We need to enter init's mount namespace to access /home/root. Also, we use
110 // neither ARC container's mount namespace (with android-sh) nor
111 // /opt/google/containers/android/rootfs/android-data/ so that we can get
112 // results even when the container is down.
113 {kCommand, "android_app_storage", "/usr/bin/nsenter -t1 -m "
114 "/bin/sh -c \"/usr/bin/du -h /home/root/*/android-data/data/\"",
115 kRoot, kDebugfsGroup},
Chris Morin853d3442019-04-01 21:35:13 -0700116 {kFile, "atrus_logs", "/var/log/atrus.log"},
117 {kFile, "authpolicy", "/var/log/authpolicy.log"},
Kimiyuki Onakafc372892020-11-24 23:28:20 +0900118#if USE_ARCVM
119 {kCommand, "arcvm_console_output", "/usr/bin/vm_pstore_dump", "crosvm",
120 "crosvm", Log::kDefaultMaxBytes, LogTool::Encoding::kAutodetect, true},
121#endif // USE_ARCVM
Brian Norrisafc9f632019-05-09 14:08:28 -0700122 {kCommand, "bootstat_summary", "/usr/bin/bootstat_summary",
123 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
124 Log::kDefaultMaxBytes, LogTool::Encoding::kAutodetect, true},
Craig Hesling5c384b52019-04-20 15:18:06 -0700125 {kFile, "bio_crypto_init.LATEST",
126 "/var/log/bio_crypto_init/bio_crypto_init.LATEST"},
127 {kFile, "bio_crypto_init.PREVIOUS",
128 "/var/log/bio_crypto_init/bio_crypto_init.PREVIOUS"},
Chris Morin853d3442019-04-01 21:35:13 -0700129 {kFile, "biod.LATEST", "/var/log/biod/biod.LATEST"},
130 {kFile, "biod.PREVIOUS", "/var/log/biod/biod.PREVIOUS"},
Craig Hesling4c3891e2019-04-20 12:53:54 -0700131 {kFile, "bio_fw_updater.LATEST", "/var/log/biod/bio_fw_updater.LATEST"},
132 {kFile, "bio_fw_updater.PREVIOUS", "/var/log/biod/bio_fw_updater.PREVIOUS"},
Chris Morin853d3442019-04-01 21:35:13 -0700133 {kFile, "bios_info", "/var/log/bios_info.txt"},
134 {kCommand, "bios_log", "cat /sys/firmware/log "
135 "/proc/device-tree/chosen/ap-console-buffer 2>/dev/null"},
136 {kFile, "bios_times", "/var/log/bios_times.txt"},
Anand K Mistryccceb1e2020-01-16 14:00:49 +1100137 // Slow or non-responsive block devices could cause this command to stall. Use
138 // a timeout to prevent this command from blocking log fetching. This command
139 // is expected to take O(100ms) in the normal case.
140 {kCommand, "blkid", "timeout -s KILL 5s /sbin/blkid", kRoot, kRoot},
Chris Morin853d3442019-04-01 21:35:13 -0700141 {kFile, "buddyinfo", "/proc/buddyinfo"},
142 {kCommand, "cbi_info", "/usr/share/userfeedback/scripts/cbi_info", kRoot,
143 kRoot},
144 {kFile, "cheets_log", "/var/log/arc.log"},
145 {kFile, "clobber.log", "/var/log/clobber.log"},
146 {kFile, "clobber-state.log", "/var/log/clobber-state.log"},
Sonny Raobd3dc002020-05-27 21:40:35 -0700147 {kCommand, "chromeos-pgmem", "/usr/bin/chromeos-pgmem", kRoot, kRoot},
Chris Morin853d3442019-04-01 21:35:13 -0700148 {kFile, "chrome_system_log", "/var/log/chrome/chrome"},
149 {kFile, "chrome_system_log.PREVIOUS", "/var/log/chrome/chrome.PREVIOUS"},
Mike Frysinger32cdf3e2017-08-14 18:17:06 -0400150 // There might be more than one record, so grab them all.
151 // Plus, for <linux-3.19, it's named "console-ramoops", but for newer
152 // versions, it's named "console-ramoops-#".
Mike Frysinger020c2402020-12-16 05:40:53 -0500153 {kGlob, "console-ramoops", "/sys/fs/pstore/console-ramoops*"},
Chris Morin853d3442019-04-01 21:35:13 -0700154 {kFile, "cpuinfo", "/proc/cpuinfo"},
155 {kFile, "cr50_version", "/var/cache/cr50-version"},
Nicolas Boichatf3dd82d2020-09-07 15:11:15 +0800156 {kFile, "cros_ec.log", "/var/log/cros_ec.log",
157 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
158 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
159 {kFile, "cros_ec.previous", "/var/log/cros_ec.previous",
160 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
161 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
Chris Morin853d3442019-04-01 21:35:13 -0700162 {kFile, "cros_ec_panicinfo", "/sys/kernel/debug/cros_ec/panicinfo",
Nicolas Boichat28272d72020-09-03 09:10:44 +0800163 SandboxedProcess::kDefaultUser, kDebugfsGroup, Log::kDefaultMaxBytes,
164 LogTool::Encoding::kBase64},
Stephen Boydf00c5a02020-09-10 19:11:35 -0700165 {kCommand, "cros_ec_pdinfo",
166 "for port in 0 1 2 3 4 5 6 7 8; do "
167 "echo \"-----------\"; "
168 // stderr output just tells us it failed
169 "ectool usbpd \"${port}\" 2>/dev/null || break; "
170 "done", kRoot, kRoot},
Nicolas Boichatf3dd82d2020-09-07 15:11:15 +0800171 {kFile, "cros_fp.previous", "/var/log/cros_fp.previous",
172 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
173 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
174 {kFile, "cros_fp.log", "/var/log/cros_fp.log",
175 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
176 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
177 {kFile, "cros_ish.previous", "/var/log/cros_ish.previous",
178 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
179 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
180 {kFile, "cros_ish.log", "/var/log/cros_ish.log",
181 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
182 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
Nicolas Boichat579ccf32020-08-31 11:17:21 +0800183 {kFile, "cros_scp.previous", "/var/log/cros_scp.previous",
184 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
185 64 * 1024, LogTool::Encoding::kUtf8},
186 {kFile, "cros_scp.log", "/var/log/cros_scp.log",
187 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
188 64 * 1024, LogTool::Encoding::kUtf8},
David Munro0eb1ac32020-08-19 22:22:56 +1000189 {kCommand, "crosvm.log", "nsenter -t1 -m /bin/sh -c 'tail -n+1"
190 " /run/daemon-store/crosvm/*/log/*.log.1"
191 " /run/daemon-store/crosvm/*/log/*.log'", kRoot, kRoot},
Jorge Lucangeli Obesaf8f79c2020-11-13 08:54:55 -0500192 // 'dmesg' needs CAP_SYSLOG.
193 {kCommand, "dmesg", "/bin/dmesg", kRoot, kRoot},
Mike Frysinger020c2402020-12-16 05:40:53 -0500194 {kGlob, "drm_gem_objects", "/sys/kernel/debug/dri/?/gem",
Stephen Boyda8287162020-07-30 18:07:53 -0700195 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Mike Frysinger020c2402020-12-16 05:40:53 -0500196 {kGlob, "drm_state", "/sys/kernel/debug/dri/?/state",
Stephen Boyda8287162020-07-30 18:07:53 -0700197 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Chris Morin853d3442019-04-01 21:35:13 -0700198 {kFile, "ec_info", "/var/log/ec_info.txt"},
Chris Morin853d3442019-04-01 21:35:13 -0700199 {kCommand, "edid-decode",
Stephen Boydaf3118b2020-08-11 11:42:22 -0700200 "for f in /sys/class/drm/card?-*/edid; do "
Chris Morin853d3442019-04-01 21:35:13 -0700201 "echo \"----------- ${f}\"; "
Chris Morin853d3442019-04-01 21:35:13 -0700202 // edid-decode's stderr output is redundant, so silence it.
Jeffrey Kardatzke9ba9f322019-08-29 10:23:14 -0700203 "edid-decode \"${f}\" 2>/dev/null; "
Chris Morin853d3442019-04-01 21:35:13 -0700204 "done"},
205 {kFile, "eventlog", "/var/log/eventlog.txt"},
Chris Morin853d3442019-04-01 21:35:13 -0700206 {kCommand, "font_info", "/usr/share/userfeedback/scripts/font_info"},
Mike Frysinger020c2402020-12-16 05:40:53 -0500207 {kGlob, "framebuffer", "/sys/kernel/debug/dri/?/framebuffer",
Kuo-Hsin Yang95296e12020-03-06 17:52:35 +0800208 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Daniel Campello9f0b2b82020-10-23 11:01:01 -0600209 {kCommand, "fwupd_state", "/sbin/initctl emit fwupdtool-getdevices;"
210 "cat /var/lib/fwupd/state.json", kRoot, kRoot},
Chris Morin853d3442019-04-01 21:35:13 -0700211 {kCommand, "sensor_info", "/usr/share/userfeedback/scripts/sensor_info"},
212 {kFile, "hammerd", "/var/log/hammerd.log"},
213 {kCommand, "hardware_class", "/usr/bin/crossystem hwid"},
Yong Hong15e4b032020-03-05 15:41:31 +0800214 {kFile, "hardware_verification_report",
215 "/var/cache/hardware_verifier.result"},
Chris Morin853d3442019-04-01 21:35:13 -0700216 {kCommand, "hostname", "/bin/hostname"},
217 {kFile, "i915_gem_gtt", "/sys/kernel/debug/dri/0/i915_gem_gtt",
218 SandboxedProcess::kDefaultUser, kDebugfsGroup},
219 {kFile, "i915_gem_objects", "/sys/kernel/debug/dri/0/i915_gem_objects",
220 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Chris Morin853d3442019-04-01 21:35:13 -0700221 {kCommand, "i915_error_state",
222 "/usr/bin/xz -c /sys/kernel/debug/dri/0/i915_error_state 2>/dev/null",
223 SandboxedProcess::kDefaultUser, kDebugfsGroup, Log::kDefaultMaxBytes,
Chris Morin790fd262019-04-03 20:29:36 -0700224 LogTool::Encoding::kBase64},
Chris Morin853d3442019-04-01 21:35:13 -0700225 {kCommand, "ifconfig", "/bin/ifconfig -a"},
226 {kFile, "input_devices", "/proc/bus/input/devices"},
Eric Carusob1820c02017-08-24 15:39:56 -0700227 // Hardware capabilities of the wiphy device.
Alex Levine1c6d572019-09-17 14:45:33 -0700228 {kFile, "interrupts", "/proc/interrupts"},
Chris Morin853d3442019-04-01 21:35:13 -0700229 {kCommand, "iw_list", "/usr/sbin/iw list"},
Eric Carusoa879fd92017-10-11 12:57:10 -0700230#if USE_IWLWIFI_DUMP
Chris Morin853d3442019-04-01 21:35:13 -0700231 {kCommand, "iwlmvm_module_params", CMD_KERNEL_MODULE_PARAMS(iwlmvm)},
232 {kCommand, "iwlwifi_module_params", CMD_KERNEL_MODULE_PARAMS(iwlwifi)},
Eric Carusoa879fd92017-10-11 12:57:10 -0700233#endif // USE_IWLWIFI_DUMP
Mike Frysinger020c2402020-12-16 05:40:53 -0500234 {kGlob, "kernel-crashes", "/var/spool/crash/kernel.*.kcrash",
Mike Frysinger2abf7a12020-12-16 05:39:02 -0500235 SandboxedProcess::kDefaultUser, "crash-access"},
Anand K Mistryccceb1e2020-01-16 14:00:49 +1100236 {kCommand, "lsblk", "timeout -s KILL 5s lsblk -a", kRoot, kRoot,
237 Log::kDefaultMaxBytes, LogTool::Encoding::kAutodetect, true},
Chris Morin853d3442019-04-01 21:35:13 -0700238 {kCommand, "lsmod", "lsmod"},
239 {kCommand, "lspci", "/usr/sbin/lspci"},
240 {kCommand, "lsusb", "lsusb && lsusb -t"},
Kuo-Hsin Yang66d89832020-02-10 17:22:28 +0800241 {kFile, "mali_memory", "/sys/kernel/debug/mali0/gpu_memory",
242 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Chris Morin853d3442019-04-01 21:35:13 -0700243 {kFile, "memd.parameters", "/var/log/memd/memd.parameters"},
Mike Frysinger020c2402020-12-16 05:40:53 -0500244 {kGlob, "memd clips", "/var/log/memd/memd.clip*"},
Chris Morin853d3442019-04-01 21:35:13 -0700245 {kFile, "meminfo", "/proc/meminfo"},
246 {kCommand, "memory_spd_info",
247 // mosys may use 'i2c-dev', which may not be loaded yet.
248 "modprobe i2c-dev 2>/dev/null && mosys -l memory spd print all 2>/dev/null",
249 kRoot, kDebugfsGroup},
Simon Quecb63b9c2017-06-19 14:53:31 -0400250 // The sed command finds the EDID blob (starting the line after "value:") and
251 // replaces the serial number with all zeroes.
252 //
253 // The EDID is printed as a hex dump over several lines, each line containing
254 // the contents of 16 bytes. The first 16 bytes are broken down as follows:
255 // uint64_t fixed_pattern; // Always 00 FF FF FF FF FF FF 00.
256 // uint16_t manufacturer_id; // Manufacturer ID, encoded as PNP IDs.
257 // uint16_t product_code; // Manufacturer product code, little-endian.
258 // uint32_t serial_number; // Serial number, little-endian.
259 // Source: https://en.wikipedia.org/wiki/EDID#EDID_1.3_data_format
260 //
261 // The subsequent substitution command looks for the fixed pattern followed by
262 // two 32-bit fields (manufacturer + product, serial number). It replaces the
263 // latter field with 8 bytes of zeroes.
264 //
265 // TODO(crbug.com/731133): Remove the sed command once modetest itself can
266 // remove serial numbers.
Chris Morin853d3442019-04-01 21:35:13 -0700267 {kCommand, "modetest",
268 "(modetest; modetest -M evdi; modetest -M udl) | "
269 "sed -E '/EDID/ {:a;n;/value:/!ba;n;"
270 "s/(00f{12}00)([0-9a-f]{8})([0-9a-f]{8})/\\1\\200000000/}'",
271 kRoot, kRoot},
272 {kFile, "mount-encrypted", "/var/log/mount-encrypted.log"},
273 {kFile, "mountinfo", "/proc/1/mountinfo"},
274 {kCommand, "netlog",
275 "/usr/share/userfeedback/scripts/getmsgs /var/log/net.log"},
Chris Morin853d3442019-04-01 21:35:13 -0700276 {kFile, "nvmap_iovmm", "/sys/kernel/debug/nvmap/iovmm/allocations",
277 SandboxedProcess::kDefaultUser, kDebugfsGroup},
278 {kCommand, "oemdata", "/usr/share/cros/oemdata.sh", kRoot, kRoot},
Kuo-Hsin Yanga69ecc62020-03-11 17:37:11 +0800279 {kFile, "pagetypeinfo", "/proc/pagetypeinfo", kRoot},
Jack Rosenthal3cf794a2020-02-19 13:32:56 -0700280 {kFile, "platform_identity_name",
281 "/run/chromeos-config/v1/identity/platform-name"},
282 {kFile, "platform_identity_model", "/run/chromeos-config/v1/name"},
283 {kFile, "platform_identity_sku", "/run/chromeos-config/v1/identity/sku-id"},
284 {kFile, "platform_identity_whitelabel_tag",
285 "/run/chromeos-config/v1/identity/whitelabel-tag"},
286 {kFile, "platform_identity_customization_id",
287 "/run/chromeos-config/v1/identity/customization-id"},
Chris Morin853d3442019-04-01 21:35:13 -0700288 {kCommand, "power_supply_info", "/usr/bin/power_supply_info"},
289 {kCommand, "power_supply_sysfs", "/usr/bin/print_sysfs_power_supply_data"},
290 {kFile, "powerd.LATEST", "/var/log/power_manager/powerd.LATEST"},
291 {kFile, "powerd.PREVIOUS", "/var/log/power_manager/powerd.PREVIOUS"},
292 {kFile, "powerd.out", "/var/log/powerd.out"},
293 {kFile, "powerwash_count", "/var/log/powerwash_count"},
Brian Norris4cde3d12019-04-16 10:10:34 -0700294 {kCommand, "ps", "/bin/ps auxZ"},
Mike Frysinger020c2402020-12-16 05:40:53 -0500295 {kGlob, "qcom_fw_info", "/sys/kernel/debug/qcom_socinfo/*/*",
Stephen Boyd57779f92020-12-15 23:24:31 -0800296 SandboxedProcess::kDefaultUser, kDebugfsGroup},
yusukes34171ba2017-04-27 15:46:01 -0700297 // /proc/slabinfo is owned by root and has 0400 permission.
Chris Morin853d3442019-04-01 21:35:13 -0700298 {kFile, "slabinfo", "/proc/slabinfo", kRoot, kRoot},
299 {kFile, "storage_info", "/var/log/storage_info.txt"},
300 {kCommand, "swap_info", "/usr/share/cros/init/swap.sh status 2>/dev/null",
301 SandboxedProcess::kDefaultUser, kDebugfsGroup},
302 {kCommand, "syslog",
303 "/usr/share/userfeedback/scripts/getmsgs /var/log/messages"},
304 {kCommand, "system_log_stats",
305 "echo 'BLOCK_SIZE=1024'; "
306 "find /var/log/ -type f -exec du --block-size=1024 {} + | sort -n -r",
307 kRoot, kRoot},
308 {kCommand, "threads", "/bin/ps -T axo pid,ppid,spid,pcpu,ni,stat,time,comm"},
309 {kFile, "tlsdate", "/var/log/tlsdate.log"},
Nick Sandersad5dc132019-11-15 15:59:42 -0800310 {kCommand, "top thread", "/usr/bin/top -Hbc -w128 -n 1 | head -n 40"},
311 {kCommand, "top memory",
312 "/usr/bin/top -o \"+%MEM\" -w128 -bcn 1 | head -n 57"},
Chris Morin853d3442019-04-01 21:35:13 -0700313 {kCommand, "touch_fw_version",
Stephen Boyddb9eb2f2020-08-11 11:25:41 -0700314 "grep -aE"
Chris Morin853d3442019-04-01 21:35:13 -0700315 " -e 'synaptics: Touchpad model'"
316 " -e 'chromeos-[a-z]*-touch-[a-z]*-update'"
317 " /var/log/messages | tail -n 20"},
318 {kCommand, "tpm-firmware-updater", "/usr/share/userfeedback/scripts/getmsgs "
319 "/var/log/tpm-firmware-updater.log"},
Mattias Nissler887dce22017-07-03 14:44:35 +0200320 // TODO(jorgelo,mnissler): Don't run this as root.
321 // On TPM 1.2 devices this will likely require adding a new user to the 'tss'
322 // group.
323 // On TPM 2.0 devices 'get_version_info' uses D-Bus and therefore can run as
324 // any user.
Chris Morin853d3442019-04-01 21:35:13 -0700325 {kCommand, "tpm_version", "/usr/sbin/tpm-manager get_version_info", kRoot,
326 kRoot},
327 {kCommand, "atmel_ts_refs",
328 "/opt/google/touch/scripts/atmel_tools.sh ts r", kRoot, kRoot},
329 {kCommand, "atmel_tp_refs",
330 "/opt/google/touch/scripts/atmel_tools.sh tp r", kRoot, kRoot},
331 {kCommand, "atmel_ts_deltas",
332 "/opt/google/touch/scripts/atmel_tools.sh ts d", kRoot, kRoot},
333 {kCommand, "atmel_tp_deltas",
334 "/opt/google/touch/scripts/atmel_tools.sh tp d", kRoot, kRoot},
335 {kFile, "stateful_trim_state", "/var/lib/trim/stateful_trim_state"},
336 {kFile, "stateful_trim_data", "/var/lib/trim/stateful_trim_data"},
337 {kFile, "ui_log", "/var/log/ui/ui.LATEST"},
338 {kCommand, "uname", "/bin/uname -a"},
339 {kCommand, "update_engine.log",
340 "cat $(ls -1tr /var/log/update_engine | tail -5 | sed"
341 " s.^./var/log/update_engine/.)"},
Chris Morinca152712019-05-03 13:17:28 -0700342 {kFile, "upstart", "/var/log/upstart.log"},
Chris Morin853d3442019-04-01 21:35:13 -0700343 {kCommand, "uptime", "/usr/bin/cut -d' ' -f1 /proc/uptime"},
344 {kFile, "verified boot", "/var/log/debug_vboot_noisy.log"},
345 {kFile, "vmlog.1.LATEST", "/var/log/vmlog/vmlog.1.LATEST"},
346 {kFile, "vmlog.1.PREVIOUS", "/var/log/vmlog/vmlog.1.PREVIOUS"},
347 {kFile, "vmlog.LATEST", "/var/log/vmlog/vmlog.LATEST"},
348 {kFile, "vmlog.PREVIOUS", "/var/log/vmlog/vmlog.PREVIOUS"},
349 {kFile, "vmstat", "/proc/vmstat"},
350 {kFile, "vpd_2.0", "/var/log/vpd_2.0.txt"},
Chris Morin853d3442019-04-01 21:35:13 -0700351 {kFile, "zram compressed data size", "/sys/block/zram0/compr_data_size"},
352 {kFile, "zram original data size", "/sys/block/zram0/orig_data_size"},
353 {kFile, "zram total memory used", "/sys/block/zram0/mem_used_total"},
354 {kFile, "zram total reads", "/sys/block/zram0/num_reads"},
355 {kFile, "zram total writes", "/sys/block/zram0/num_writes"},
356 {kCommand, "zram new stats names",
357 "echo orig_size compr_size used_total limit used_max zero_pages migrated"},
358 {kFile, "zram new stats values", "/sys/block/zram0/mm_stat"},
359 {kFile, "cros_tp version", "/sys/class/chromeos/cros_tp/version"},
360 {kCommand, "cros_tp console", "/usr/sbin/ectool --name=cros_tp console",
361 kRoot, kRoot},
362 {kCommand, "cros_tp frame", "/usr/sbin/ectool --name=cros_tp tpframeget",
363 kRoot, kRoot},
364 {kCommand, "crostini", "/usr/bin/cicerone_client --get_info"},
Sean Paulbfc5c422020-07-24 11:03:51 -0400365 // TODO(seanpaul): Once we've finished moving over to the upstream tracefs
366 // implementation, remove drm_trace_legacy. Tracked in
367 // b/163580546.
368 {kFile, "drm_trace_legacy", "/sys/kernel/debug/dri/trace",
369 SandboxedProcess::kDefaultUser, kDebugfsGroup},
370 {kFile, "drm_trace", "/sys/kernel/debug/tracing/instances/drm/trace",
Sean Paul5ce118f2019-12-05 08:41:32 -0500371 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Elly Jones03cd6d72012-06-11 13:04:28 -0400372 // Stuff pulled out of the original list. These need access to the running X
373 // session, which we'd rather not give to debugd, or return info specific to
374 // the current session (in the setsid(2) sense), which is not useful for
375 // debugd
Chris Morin853d3442019-04-01 21:35:13 -0700376 // {kCommand, "env", "set"},
377 // {kCommand, "setxkbmap", "/usr/bin/setxkbmap -print -query"},
378 // {kCommand, "xrandr", "/usr/bin/xrandr --verbose}
Elly Jones533c7c42012-08-10 15:07:05 -0400379};
Tom Hughesd6c2d392020-08-24 18:12:11 -0700380// clang-format on
Elly Jones533c7c42012-08-10 15:07:05 -0400381
Junichi Uekawaba686c82020-09-01 16:24:24 +0900382// Extra logs are logs such as netstat and logcat which should appear in
383// chrome://system but not in feedback reports. Open sockets may have privacy
384// implications, and logcat is already incorporated via arc-bugreport.
385//
Tom Hughesd6c2d392020-08-24 18:12:11 -0700386// clang-format off
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700387const std::vector<Log> kExtraLogs {
Ben Chan36e42282014-02-12 22:32:34 -0800388#if USE_CELLULAR
Chris Morin853d3442019-04-01 21:35:13 -0700389 {kCommand, "mm-status", "/usr/bin/modem status"},
Ben Chan36e42282014-02-12 22:32:34 -0800390#endif // USE_CELLULAR
Chris Morin853d3442019-04-01 21:35:13 -0700391 {kCommand, "network-devices", "/usr/bin/connectivity show devices"},
392 {kCommand, "network-services", "/usr/bin/connectivity show services"},
Jeffrey Kardatzke36791f22019-07-11 11:53:22 -0700393 {kCommand, "wifi_status_no_anonymize",
394 "/usr/bin/network_diag --wifi-internal --no-log"},
Chris Morin253a2b02019-04-12 16:04:25 -0700395 // --processes requires root.
396 {kCommand, "netstat",
397 "/sbin/ss --all --query inet --numeric --processes", kRoot, kRoot},
Kansho Nishida6ae546f2019-08-13 17:14:58 +0900398 {kCommand, "logcat",
399 "/usr/bin/nsenter -t1 -m /usr/sbin/android-sh -c '/system/bin/logcat -d'",
Chris Morin253a2b02019-04-12 16:04:25 -0700400 kRoot, kRoot, Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
Elly Jones533c7c42012-08-10 15:07:05 -0400401};
Tom Hughesd6c2d392020-08-24 18:12:11 -0700402// clang-format on
Elly Jones533c7c42012-08-10 15:07:05 -0400403
Tom Hughesd6c2d392020-08-24 18:12:11 -0700404// clang-format off
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700405const std::vector<Log> kFeedbackLogs {
Ben Chan36e42282014-02-12 22:32:34 -0800406#if USE_CELLULAR
Chris Morin853d3442019-04-01 21:35:13 -0700407 {kCommand, "mm-status", "/usr/bin/modem status-feedback"},
Ben Chan36e42282014-02-12 22:32:34 -0800408#endif // USE_CELLULAR
Chris Morin853d3442019-04-01 21:35:13 -0700409 {kCommand, "network-devices",
410 "/usr/bin/connectivity show-feedback devices"},
411 {kCommand, "network-services",
412 "/usr/bin/connectivity show-feedback services"},
Jeffrey Kardatzke36791f22019-07-11 11:53:22 -0700413 {kCommand, "wifi_status",
414 "/usr/bin/network_diag --wifi-internal --no-log --anonymize"},
Elly Jones03cd6d72012-06-11 13:04:28 -0400415};
Tom Hughesd6c2d392020-08-24 18:12:11 -0700416// clang-format on
Elly Jones03cd6d72012-06-11 13:04:28 -0400417
Jeffrey Kardatzkee3ec6fd2019-08-05 12:25:17 -0700418// Fills |dictionary| with the contents of the logs in |logs|.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700419void GetLogsInDictionary(const std::vector<Log>& logs,
hscham2311cc22020-10-28 12:13:10 +0900420 base::Value* dictionary) {
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700421 for (const Log& log : logs) {
hscham2311cc22020-10-28 12:13:10 +0900422 dictionary->SetStringKey(log.GetName(), log.GetLogData());
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800423 }
424}
425
426// Serializes the |dictionary| into the file with the given |fd| in a JSON
427// format.
hscham2311cc22020-10-28 12:13:10 +0900428void SerializeLogsAsJSON(const base::Value& dictionary,
Eric Caruso0b241882018-04-04 13:43:46 -0700429 const base::ScopedFD& fd) {
Eric Caruso96d03d32017-04-25 18:01:17 -0700430 string logs_json;
Tom Hughesd6c2d392020-08-24 18:12:11 -0700431 base::JSONWriter::WriteWithOptions(
432 dictionary, base::JSONWriter::OPTIONS_PRETTY_PRINT, &logs_json);
Eric Caruso0b241882018-04-04 13:43:46 -0700433 base::WriteFileDescriptor(fd.get(), logs_json.c_str(), logs_json.size());
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800434}
435
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700436bool GetNamedLogFrom(const string& name,
437 const std::vector<Log>& logs,
Elly Jones533c7c42012-08-10 15:07:05 -0400438 string* result) {
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700439 for (const Log& log : logs) {
440 if (name == log.GetName()) {
441 *result = log.GetLogData();
Elly Jones533c7c42012-08-10 15:07:05 -0400442 return true;
443 }
444 }
445 *result = "<invalid log name>";
446 return false;
Elly Jones03cd6d72012-06-11 13:04:28 -0400447}
448
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700449void GetLogsFrom(const std::vector<Log>& logs, LogTool::LogMap* map) {
450 for (const Log& log : logs)
451 (*map)[log.GetName()] = log.GetLogData();
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800452}
453
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600454void GetLsbReleaseInfo(LogTool::LogMap* map) {
455 const base::FilePath lsb_release(kLsbReleasePath);
456 brillo::KeyValueStore store;
457 if (!store.Load(lsb_release)) {
458 // /etc/lsb-release might not be present (cros deploying a new
459 // configuration or no fields set at all). Just print a debug
460 // message and continue.
461 DLOG(INFO) << "Could not load fields from " << lsb_release.value();
462 } else {
463 for (const auto& key : store.GetKeys()) {
464 std::string value;
465 store.GetString(key, &value);
466 (*map)[key] = value;
467 }
468 }
469}
470
471void GetOsReleaseInfo(LogTool::LogMap* map) {
472 brillo::OsReleaseReader reader;
473 reader.Load();
474 for (const auto& key : reader.GetKeys()) {
475 std::string value;
476 reader.GetString(key, &value);
477 (*map)["os-release " + key] = value;
478 }
479}
480
481void PopulateDictionaryValue(const LogTool::LogMap& map,
hscham2311cc22020-10-28 12:13:10 +0900482 base::Value* dictionary) {
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600483 for (const auto& kv : map) {
hscham2311cc22020-10-28 12:13:10 +0900484 dictionary->SetStringKey(kv.first, kv.second);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600485 }
486}
487
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800488bool CompressXzBuffer(const std::vector<uint8_t>& in_buffer,
489 std::vector<uint8_t>* out_buffer) {
490 size_t out_size = lzma_stream_buffer_bound(in_buffer.size());
491 out_buffer->resize(out_size);
492 size_t out_pos = 0;
493
494 lzma_ret ret = lzma_easy_buffer_encode(
495 LZMA_PRESET_DEFAULT, LZMA_CHECK_CRC64, nullptr, in_buffer.data(),
496 in_buffer.size(), out_buffer->data(), &out_pos, out_size);
497
498 if (ret != LZMA_OK) {
499 out_buffer->clear();
500 return false;
501 }
502
503 out_buffer->resize(out_pos);
504 return true;
505}
506
507void GetPerfData(LogTool::LogMap* map) {
508 // Run perf to collect system-wide performance profile when user triggers
509 // feedback report. Perf runs at sampling frequency of ~500 hz (499 is used
510 // to avoid sampling periodic system activities), with callstack in each
511 // sample (-g).
512 std::vector<std::string> perf_args = {
Tom Hughesd6c2d392020-08-24 18:12:11 -0700513 "perf", "record", "-a", "-g", "-F", "499",
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800514 };
515 std::vector<uint8_t> perf_data;
516 int32_t status;
517
518 debugd::PerfTool perf_tool;
519 if (!perf_tool.GetPerfOutput(kPerfDurationSecs, perf_args, &perf_data,
520 nullptr, &status, nullptr))
521 return;
522
523 // XZ compress the profile data.
524 std::vector<uint8_t> perf_data_xz;
525 if (!CompressXzBuffer(perf_data, &perf_data_xz))
526 return;
527
528 // Base64 encode the compressed data.
529 std::string perf_data_str(reinterpret_cast<const char*>(perf_data_xz.data()),
530 perf_data_xz.size());
Tom Hughesd6c2d392020-08-24 18:12:11 -0700531 (*map)["perf-data"] = std::string(kPerfDataDescription) +
532 LogTool::EncodeString(std::move(perf_data_str),
533 LogTool::Encoding::kBase64);
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800534}
535
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800536} // namespace
537
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700538Log::Log(Log::LogType type,
539 std::string name,
540 std::string data,
541 std::string user,
542 std::string group,
543 int64_t max_bytes,
Brian Norrisafc9f632019-05-09 14:08:28 -0700544 LogTool::Encoding encoding,
545 bool access_root_mount_ns)
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700546 : type_(type),
547 name_(name),
548 data_(data),
549 user_(user),
550 group_(group),
551 max_bytes_(max_bytes),
Brian Norrisafc9f632019-05-09 14:08:28 -0700552 encoding_(encoding),
553 access_root_mount_ns_(access_root_mount_ns) {}
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700554
555std::string Log::GetName() const {
556 return name_;
557}
558
559std::string Log::GetLogData() const {
560 // The reason this code uses a switch statement on a type enum rather than
561 // using inheritance/virtual dispatch is so that all of the Log objects can
562 // be constructed statically. Switching to heap allocated subclasses of Log
563 // makes the code that declares all of the log entries much more verbose
564 // and harder to understand.
Chris Morin790fd262019-04-03 20:29:36 -0700565 std::string output;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700566 switch (type_) {
567 case kCommand:
Chris Morin790fd262019-04-03 20:29:36 -0700568 output = GetCommandLogData();
569 break;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700570 case kFile:
Chris Morin790fd262019-04-03 20:29:36 -0700571 output = GetFileLogData();
572 break;
Mike Frysinger020c2402020-12-16 05:40:53 -0500573 case kGlob:
574 output = GetGlobLogData();
575 break;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700576 default:
Mike Frysingerdf3be7f2020-12-16 03:17:42 -0500577 DCHECK(false) << "unknown log type";
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700578 return "<unknown log type>";
579 }
Chris Morin790fd262019-04-03 20:29:36 -0700580
581 if (output.empty())
582 return "<empty>";
583
584 return LogTool::EncodeString(std::move(output), encoding_);
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700585}
586
587// TODO(ellyjones): sandbox. crosbug.com/35122
588std::string Log::GetCommandLogData() const {
Mike Frysingerdf3be7f2020-12-16 03:17:42 -0500589 DCHECK_EQ(type_, kCommand);
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700590 if (type_ != kCommand)
591 return "<log type mismatch>";
592 std::string tailed_cmdline =
593 base::StringPrintf("%s | tail -c %" PRId64, data_.c_str(), max_bytes_);
594 ProcessWithOutput p;
595 if (minijail_disabled_for_test_)
596 p.set_use_minijail(false);
597 if (!user_.empty() && !group_.empty())
598 p.SandboxAs(user_, group_);
Brian Norrisafc9f632019-05-09 14:08:28 -0700599 if (access_root_mount_ns_)
600 p.AllowAccessRootMountNamespace();
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700601 if (!p.Init())
602 return "<not available>";
603 p.AddArg(kShell);
604 p.AddStringOption("-c", tailed_cmdline);
605 if (p.Run())
606 return "<not available>";
607 std::string output;
608 p.GetOutput(&output);
Chris Morin790fd262019-04-03 20:29:36 -0700609 return output;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700610}
611
Mike Frysinger020c2402020-12-16 05:40:53 -0500612// static
613std::string Log::GetFileData(const base::FilePath& path,
614 int64_t max_bytes,
615 const std::string& user,
616 const std::string& group) {
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700617 uid_t old_euid = geteuid();
Mike Frysinger020c2402020-12-16 05:40:53 -0500618 uid_t new_euid = UidForUser(user);
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700619 gid_t old_egid = getegid();
Mike Frysinger020c2402020-12-16 05:40:53 -0500620 gid_t new_egid = GidForGroup(group);
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700621
622 if (new_euid == -1 || new_egid == -1) {
623 return "<not available>";
624 }
625
626 // Make sure to set group first, since if we set user first we lose root
627 // and therefore the ability to set our effective gid to arbitrary gids.
628 if (setegid(new_egid)) {
629 PLOG(ERROR) << "Failed to set effective group id to " << new_egid;
630 return "<not available>";
631 }
632 if (seteuid(new_euid)) {
633 PLOG(ERROR) << "Failed to set effective user id to " << new_euid;
634 if (setegid(old_egid))
635 PLOG(ERROR) << "Failed to restore effective group id to " << old_egid;
636 return "<not available>";
637 }
638
639 std::string contents;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700640 // Handle special files that don't properly report length/allow lseek.
641 if (base::FilePath("/dev").IsParent(path) ||
642 base::FilePath("/proc").IsParent(path) ||
643 base::FilePath("/sys").IsParent(path)) {
644 if (!base::ReadFileToString(path, &contents))
645 contents = "<not available>";
Mike Frysinger020c2402020-12-16 05:40:53 -0500646 if (contents.size() > max_bytes)
647 contents.erase(0, contents.size() - max_bytes);
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700648 } else {
649 base::File file(path, base::File::FLAG_OPEN | base::File::FLAG_READ);
650 if (!file.IsValid()) {
651 contents = "<not available>";
652 } else {
653 int64_t length = file.GetLength();
Mike Frysinger020c2402020-12-16 05:40:53 -0500654 if (length > max_bytes) {
655 file.Seek(base::File::FROM_END, -max_bytes);
656 length = max_bytes;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700657 }
658 std::vector<char> buf(length);
659 int read = file.ReadAtCurrentPos(buf.data(), buf.size());
660 if (read < 0) {
661 PLOG(ERROR) << "Could not read from file " << path.value();
662 } else {
663 contents = std::string(buf.begin(), buf.begin() + read);
664 }
665 }
666 }
667
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700668 // Make sure we restore our old euid/egid before returning.
669 if (seteuid(old_euid))
670 PLOG(ERROR) << "Failed to restore effective user id to " << old_euid;
671
672 if (setegid(old_egid))
673 PLOG(ERROR) << "Failed to restore effective group id to " << old_egid;
674
Chris Morin790fd262019-04-03 20:29:36 -0700675 return contents;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700676}
677
Mike Frysinger020c2402020-12-16 05:40:53 -0500678std::string Log::GetFileLogData() const {
679 DCHECK_EQ(type_, kFile);
680 if (type_ != kFile)
681 return "<log type mismatch>";
682
683 return GetFileData(base::FilePath(data_), max_bytes_, user_, group_);
684}
685
686std::string Log::GetGlobLogData() const {
687 DCHECK_EQ(type_, kGlob);
688 if (type_ != kGlob)
689 return "<log type mismatch>";
690
691 // NB: base::FileEnumerator requires a directory to walk, and a pattern to
692 // match against each result. Here we accept full paths with globs in them.
693 glob_t g;
694 // NB: Feel free to add GLOB_BRACE if a user comes up.
695 int gret = glob(data_.c_str(), 0, nullptr, &g);
696 if (gret == GLOB_NOMATCH) {
697 globfree(&g);
698 return "<no matches>";
699 } else if (gret) {
700 globfree(&g);
701 PLOG(ERROR) << "glob " << data_ << " failed";
702 return "<not available>";
703 }
704
705 // The results array will hold 2 entries per file: the filename, and the
706 // results of reading that file.
707 size_t output_size = 0;
708 std::vector<std::string> results;
709 results.reserve(g.gl_pathc * 2);
710
711 for (size_t pathc = 0; pathc < g.gl_pathc; ++pathc) {
712 const base::FilePath path(g.gl_pathv[pathc]);
713 std::string contents = GetFileData(path, max_bytes_, user_, group_);
714 // NB: The 3 represents the bytes we add in the output string below.
715 output_size += path.value().size() + contents.size() + 3;
716 results.push_back(path.value());
717 results.push_back(contents);
718 }
719 globfree(&g);
720
721 // Combine the results into a single string. We have a header with the
722 // filename followed by that file's contents. Very basic format.
723 std::string output;
724 output.reserve(output_size);
725 for (auto iter = results.begin(); iter != results.end(); ++iter) {
726 output += *iter + ":\n";
727 ++iter;
728 output += *iter + "\n";
729 }
730
731 return output;
732}
733
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700734void Log::DisableMinijailForTest() {
735 minijail_disabled_for_test_ = true;
736}
737
738// static
739uid_t Log::UidForUser(const std::string& user) {
740 struct passwd entry;
741 struct passwd* result;
742 std::vector<char> buf(1024);
743 getpwnam_r(user.c_str(), &entry, &buf[0], buf.size(), &result);
744 if (!result) {
745 LOG(ERROR) << "User not found: " << user;
746 return -1;
747 }
748 return entry.pw_uid;
749}
750
751// static
752gid_t Log::GidForGroup(const std::string& group) {
753 struct group entry;
754 struct group* result;
755 std::vector<char> buf(1024);
756 getgrnam_r(group.c_str(), &entry, &buf[0], buf.size(), &result);
757 if (!result) {
758 LOG(ERROR) << "Group not found: " << group;
759 return -1;
760 }
761 return entry.gr_gid;
762}
763
mhasankaf5251d2020-04-29 18:53:03 -0700764LogTool::LogTool(
765 scoped_refptr<dbus::Bus> bus,
766 std::unique_ptr<org::chromium::CryptohomeInterfaceProxyInterface>
767 cryptohome_proxy,
768 std::unique_ptr<LogTool::Log> arc_bug_report_log,
769 const base::FilePath& daemon_store_base_dir)
770 : bus_(bus),
771 cryptohome_proxy_(std::move(cryptohome_proxy)),
772 arc_bug_report_log_(std::move(arc_bug_report_log)),
773 daemon_store_base_dir_(daemon_store_base_dir) {}
mhasank80cbe4d2020-04-02 22:46:08 -0700774
mhasank4f599d32020-04-09 22:07:35 -0700775LogTool::LogTool(scoped_refptr<dbus::Bus> bus)
mhasankaf5251d2020-04-29 18:53:03 -0700776 : LogTool(bus,
777 std::make_unique<org::chromium::CryptohomeInterfaceProxy>(bus),
778 std::make_unique<ArcBugReportLog>(),
779 base::FilePath(kDaemonStoreBaseDir)) {}
mhasank4f599d32020-04-09 22:07:35 -0700780
mhasank7186aae2020-09-16 20:06:00 -0700781bool LogTool::IsUserHashValid(const std::string& userhash) {
782 return brillo::cryptohome::home::IsSanitizedUserName(userhash) &&
783 base::PathExists(daemon_store_base_dir_.Append(userhash));
784}
785
Tom Hughesd6c2d392020-08-24 18:12:11 -0700786base::FilePath LogTool::GetArcBugReportBackupFilePath(
787 const std::string& userhash) {
Tom Hughesd6c2d392020-08-24 18:12:11 -0700788 return daemon_store_base_dir_.Append(userhash).Append(
789 kArcBugReportBackupFileName);
mhasank80cbe4d2020-04-02 22:46:08 -0700790}
791
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700792void LogTool::CreateConnectivityReport(bool wait_for_results) {
Rebecca Silbersteine78af402014-10-02 10:55:04 -0700793 // Perform ConnectivityTrial to report connection state in feedback log.
Ben Chan8e9f6d02017-09-26 23:04:21 -0700794 auto shill = std::make_unique<org::chromium::flimflam::ManagerProxy>(bus_);
Rebecca Silbersteine78af402014-10-02 10:55:04 -0700795 // Give the connection trial time to test the connection and log the results
796 // before collecting the logs for feedback.
797 // TODO(silberst): Replace the simple approach of a single timeout with a more
798 // coordinated effort.
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700799 if (shill && shill->CreateConnectivityReport(nullptr) && wait_for_results)
Eric Carusocc7106c2017-04-27 14:22:42 -0700800 sleep(kConnectionTesterTimeoutSeconds);
Rebecca Silbersteine78af402014-10-02 10:55:04 -0700801}
802
Eric Carusoc93a15c2017-04-24 16:15:12 -0700803string LogTool::GetLog(const string& name) {
Elly Jones533c7c42012-08-10 15:07:05 -0400804 string result;
Tom Hughesd6c2d392020-08-24 18:12:11 -0700805 GetNamedLogFrom(name, kCommandLogs, &result) ||
806 GetNamedLogFrom(name, kExtraLogs, &result) ||
807 GetNamedLogFrom(name, kFeedbackLogs, &result);
Elly Jones533c7c42012-08-10 15:07:05 -0400808 return result;
809}
810
Eric Carusof9091f82017-04-28 14:18:59 -0700811LogTool::LogMap LogTool::GetAllLogs() {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700812 CreateConnectivityReport(false);
Elly Jones533c7c42012-08-10 15:07:05 -0400813 LogMap result;
Ben Chancf7d6412017-08-10 22:30:09 -0700814 GetLogsFrom(kCommandLogs, &result);
815 GetLogsFrom(kExtraLogs, &result);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600816 GetLsbReleaseInfo(&result);
817 GetOsReleaseInfo(&result);
Elly Jones533c7c42012-08-10 15:07:05 -0400818 return result;
819}
820
Brian Norrisca4fc042018-04-03 00:24:26 -0700821LogTool::LogMap LogTool::GetAllDebugLogs() {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700822 CreateConnectivityReport(true);
Brian Norrisca4fc042018-04-03 00:24:26 -0700823 LogMap result;
824 GetLogsFrom(kCommandLogs, &result);
825 GetLogsFrom(kExtraLogs, &result);
mhasankd2b84882020-05-04 17:02:19 -0700826 result[arc_bug_report_log_->GetName()] = GetArcBugReport("", nullptr);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600827 GetLsbReleaseInfo(&result);
828 GetOsReleaseInfo(&result);
Brian Norrisca4fc042018-04-03 00:24:26 -0700829 return result;
830}
831
mhasank4f599d32020-04-09 22:07:35 -0700832void LogTool::GetBigFeedbackLogs(const base::ScopedFD& fd,
833 const std::string& username) {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700834 CreateConnectivityReport(true);
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800835 LogMap map;
836 GetPerfData(&map);
hscham2311cc22020-10-28 12:13:10 +0900837 base::Value dictionary(base::Value::Type::DICTIONARY);
Jeffrey Kardatzkee3ec6fd2019-08-05 12:25:17 -0700838 GetLogsInDictionary(kCommandLogs, &dictionary);
839 GetLogsInDictionary(kFeedbackLogs, &dictionary);
mhasankd2b84882020-05-04 17:02:19 -0700840 bool is_backup;
841 std::string arc_bug_report = GetArcBugReport(username, &is_backup);
hscham2311cc22020-10-28 12:13:10 +0900842 dictionary.SetStringKey(kArcBugReportBackupKey,
843 (is_backup ? "true" : "false"));
844 dictionary.SetStringKey(arc_bug_report_log_->GetName(), arc_bug_report);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600845 GetLsbReleaseInfo(&map);
846 GetOsReleaseInfo(&map);
847 PopulateDictionaryValue(map, &dictionary);
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800848 SerializeLogsAsJSON(dictionary, fd);
849}
850
mhasank4f599d32020-04-09 22:07:35 -0700851std::string GetSanitizedUsername(
852 org::chromium::CryptohomeInterfaceProxyInterface* cryptohome_proxy,
mhasankaf5251d2020-04-29 18:53:03 -0700853 const std::string& username) {
mhasank4f599d32020-04-09 22:07:35 -0700854 if (username.empty()) {
855 return std::string();
856 }
857
858 std::string sanitized_username;
859 brillo::ErrorPtr error;
860 if (!cryptohome_proxy->GetSanitizedUsername(username, &sanitized_username,
861 &error)) {
862 LOG(ERROR) << "Failed to call GetSanitizedUsername, error: "
863 << error->GetMessage();
864 return std::string();
865 }
866
867 return sanitized_username;
868}
869
mhasankd2b84882020-05-04 17:02:19 -0700870std::string LogTool::GetArcBugReport(const std::string& username,
871 bool* is_backup) {
872 if (is_backup) {
873 *is_backup = true;
874 }
mhasank4f599d32020-04-09 22:07:35 -0700875 std::string userhash =
876 GetSanitizedUsername(cryptohome_proxy_.get(), username);
877
878 std::string contents;
879 if (userhash.empty() ||
880 arc_bug_report_backups_.find(userhash) == arc_bug_report_backups_.end() ||
881 !base::ReadFileToString(GetArcBugReportBackupFilePath(userhash),
882 &contents)) {
883 // If |userhash| was not empty, but was not found in the backup set
884 // or the file did not exist, attempt to delete the file.
885 if (!userhash.empty()) {
mhasank40a80482020-09-09 17:44:24 -0700886 DeleteArcBugReportBackup(username);
mhasank4f599d32020-04-09 22:07:35 -0700887 }
mhasankd2b84882020-05-04 17:02:19 -0700888 if (is_backup) {
889 *is_backup = false;
890 }
mhasankaf5251d2020-04-29 18:53:03 -0700891 contents = arc_bug_report_log_->GetLogData();
mhasank4f599d32020-04-09 22:07:35 -0700892 }
893
894 return contents;
895}
896
mhasank7186aae2020-09-16 20:06:00 -0700897void LogTool::BackupArcBugReport(const std::string& username) {
mhasank80cbe4d2020-04-02 22:46:08 -0700898 DLOG(INFO) << "Backing up ARC bug report";
899
mhasank40a80482020-09-09 17:44:24 -0700900 const std::string userhash =
mhasank7186aae2020-09-16 20:06:00 -0700901 GetSanitizedUsername(cryptohome_proxy_.get(), username);
902 if (!IsUserHashValid(userhash)) {
903 LOG(ERROR) << "Invalid userhash '" << userhash << "'";
904 return;
905 }
mhasank40a80482020-09-09 17:44:24 -0700906
mhasank80cbe4d2020-04-02 22:46:08 -0700907 const base::FilePath reportPath = GetArcBugReportBackupFilePath(userhash);
mhasankaf5251d2020-04-29 18:53:03 -0700908 const std::string logData = arc_bug_report_log_->GetLogData();
mhasank4f599d32020-04-09 22:07:35 -0700909 if (base::WriteFile(reportPath, logData.c_str(), logData.length())) {
910 arc_bug_report_backups_.insert(userhash);
911 } else {
mhasank7186aae2020-09-16 20:06:00 -0700912 PLOG(ERROR) << "Failed to back up ARC bug report";
mhasank80cbe4d2020-04-02 22:46:08 -0700913 }
914}
915
mhasank7186aae2020-09-16 20:06:00 -0700916void LogTool::DeleteArcBugReportBackup(const std::string& username) {
mhasank80cbe4d2020-04-02 22:46:08 -0700917 DLOG(INFO) << "Deleting the ARC bug report backup";
918
mhasank40a80482020-09-09 17:44:24 -0700919 const std::string userhash =
mhasank7186aae2020-09-16 20:06:00 -0700920 GetSanitizedUsername(cryptohome_proxy_.get(), username);
921 if (!IsUserHashValid(userhash)) {
922 LOG(ERROR) << "Invalid userhash '" << userhash << "'";
923 return;
924 }
mhasank40a80482020-09-09 17:44:24 -0700925
mhasank80cbe4d2020-04-02 22:46:08 -0700926 const base::FilePath reportPath = GetArcBugReportBackupFilePath(userhash);
mhasank4f599d32020-04-09 22:07:35 -0700927 arc_bug_report_backups_.erase(userhash);
hscham53cf73a2020-11-30 15:58:42 +0900928 if (!base::DeleteFile(reportPath)) {
mhasank80cbe4d2020-04-02 22:46:08 -0700929 PLOG(ERROR) << "Failed to delete ARC bug report backup";
930 }
931}
932
Jeffrey Kardatzkee3ec6fd2019-08-05 12:25:17 -0700933void LogTool::GetJournalLog(const base::ScopedFD& fd) {
Chris Morin790fd262019-04-03 20:29:36 -0700934 Log journal(kCommand, "journal.export", "journalctl -n 10000 -o export",
935 "syslog", "syslog", 10 * 1024 * 1024, LogTool::Encoding::kBinary);
Jeffrey Kardatzkee3ec6fd2019-08-05 12:25:17 -0700936 std::string output = journal.GetLogData();
Chris Morin790fd262019-04-03 20:29:36 -0700937 base::WriteFileDescriptor(fd.get(), output.data(), output.size());
938}
939
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -0700940// static
Tom Hughesd6c2d392020-08-24 18:12:11 -0700941string LogTool::EncodeString(string value, LogTool::Encoding source_encoding) {
Chris Morin790fd262019-04-03 20:29:36 -0700942 if (source_encoding == LogTool::Encoding::kBinary)
943 return value;
944
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -0700945 if (source_encoding == LogTool::Encoding::kAutodetect) {
946 if (base::IsStringUTF8(value))
947 return value;
Chris Morin790fd262019-04-03 20:29:36 -0700948 source_encoding = LogTool::Encoding::kBase64;
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -0700949 }
950
951 if (source_encoding == LogTool::Encoding::kUtf8) {
952 string output;
953 const char* src = value.data();
954 int32_t src_len = static_cast<int32_t>(value.length());
955
956 output.reserve(value.size());
957 for (int32_t char_index = 0; char_index < src_len; char_index++) {
958 uint32_t code_point;
959 if (!base::ReadUnicodeCharacter(src, src_len, &char_index, &code_point) ||
960 !base::IsValidCharacter(code_point)) {
961 // Replace invalid characters with U+FFFD REPLACEMENT CHARACTER.
962 code_point = 0xFFFD;
963 }
964 base::WriteUnicodeCharacter(code_point, &output);
965 }
966 return output;
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -0700967 }
Chris Morin853d3442019-04-01 21:35:13 -0700968
969 base::Base64Encode(value, &value);
970 return "<base64>: " + value;
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -0700971}
972
Ben Chana0011d82014-05-13 00:19:29 -0700973} // namespace debugd