blob: 20263180e55e8e1e08d7a075df229a38f8329de3 [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
Fletcher Woodruff07c28532019-01-24 11:08:53 -07007#include <grp.h>
8#include <inttypes.h>
Chinglin Yuaeb4ec72018-12-10 18:53:30 +08009#include <lzma.h>
Fletcher Woodruff07c28532019-01-24 11:08:53 -070010#include <pwd.h>
11#include <stdint.h>
12#include <sys/types.h>
13#include <unistd.h>
Ben Chan8e9f6d02017-09-26 23:04:21 -070014#include <memory>
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -070015#include <string>
Fletcher Woodruff07c28532019-01-24 11:08:53 -070016#include <utility>
Ben Chana0011d82014-05-13 00:19:29 -070017#include <vector>
18
Ben Chanab93abf2017-01-24 13:32:51 -080019#include <base/base64.h>
Fletcher Woodruff07c28532019-01-24 11:08:53 -070020#include <base/files/file.h>
21#include <base/files/file_path.h>
Ben Chancd8fda42014-09-05 08:21:06 -070022#include <base/files/file_util.h>
Ahmed Fakhry21140cf2016-03-04 17:15:19 -080023#include <base/json/json_writer.h>
Elly Jones03cd6d72012-06-11 13:04:28 -040024#include <base/logging.h>
Ben Chan9953a592014-02-05 23:32:00 -080025#include <base/strings/string_split.h>
26#include <base/strings/string_util.h>
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -070027#include <base/strings/stringprintf.h>
28#include <base/strings/utf_string_conversion_utils.h>
Ahmed Fakhry21140cf2016-03-04 17:15:19 -080029#include <base/values.h>
Elly Jones03cd6d72012-06-11 13:04:28 -040030
Rebecca Silbersteine78af402014-10-02 10:55:04 -070031#include <chromeos/dbus/service_constants.h>
Eric Carusocc7106c2017-04-27 14:22:42 -070032#include <shill/dbus-proxies.h>
Rebecca Silbersteine78af402014-10-02 10:55:04 -070033
Ben Chanaf125862017-02-08 23:11:18 -080034#include "debugd/src/constants.h"
Chinglin Yuaeb4ec72018-12-10 18:53:30 +080035#include "debugd/src/perf_tool.h"
Alex Vakulenko262be3f2014-07-30 15:25:50 -070036#include "debugd/src/process_with_output.h"
Elly Jones03cd6d72012-06-11 13:04:28 -040037
Kartik Hegde1c4b97b2018-09-09 19:09:34 -060038#include "brillo/key_value_store.h"
39#include <brillo/osrelease_reader.h>
40
Elly Jones03cd6d72012-06-11 13:04:28 -040041namespace debugd {
42
Elly Jones03cd6d72012-06-11 13:04:28 -040043using std::string;
Elly Jones03cd6d72012-06-11 13:04:28 -040044
Eric Caruso96d03d32017-04-25 18:01:17 -070045using Strings = std::vector<string>;
Elly Jones03cd6d72012-06-11 13:04:28 -040046
Ahmed Fakhry21140cf2016-03-04 17:15:19 -080047namespace {
48
Ben Chanaf125862017-02-08 23:11:18 -080049const char kRoot[] = "root";
50const char kShell[] = "/bin/sh";
Kartik Hegde1c4b97b2018-09-09 19:09:34 -060051constexpr char kLsbReleasePath[] = "/etc/lsb-release";
Ahmed Fakhry21140cf2016-03-04 17:15:19 -080052
53// Minimum time in seconds needed to allow shill to test active connections.
54const int kConnectionTesterTimeoutSeconds = 5;
Ben Chanf6cd93a2012-10-14 19:37:00 -070055
Chinglin Yuaeb4ec72018-12-10 18:53:30 +080056// Default running perf for 2 seconds.
57constexpr const int kPerfDurationSecs = 2;
Chinglin Yu3c8d0a22019-02-20 11:32:52 +080058// TODO(chinglinyu) Remove after crbug/934702 is fixed.
59// The following description is added to 'perf-data' as a temporary solution
60// before the update of feedback disclosure to users is done in crbug/934702.
61constexpr const char kPerfDataDescription[] =
62 "perf-data contains performance profiling information about how much time "
63 "the system spends on various activities (program execution stack traces). "
64 "This might reveal some information about what system features and "
65 "resources are being used. The full detail of perf-data can be found in "
66 "the PerfDataProto protocol buffer message type in the chromium source "
67 "repository.\n";
Chinglin Yuaeb4ec72018-12-10 18:53:30 +080068
Eric Carusoa879fd92017-10-11 12:57:10 -070069#define CMD_KERNEL_MODULE_PARAMS(module_name) \
Luigi Semenzato7e2c08f2018-06-26 14:58:49 -070070 "cd /sys/module/" #module_name "/parameters 2>/dev/null && grep -sH ^ *"
Eric Carusoa879fd92017-10-11 12:57:10 -070071
Fletcher Woodruff07c28532019-01-24 11:08:53 -070072using Log = LogTool::Log;
73constexpr Log::LogType kCommand = Log::kCommand;
74constexpr Log::LogType kFile = Log::kFile;
75const std::vector<Log> kCommandLogs {
Mike Frysingerb0350992018-09-14 13:45:35 -040076 // We need to enter init's mount namespace because it has /home/chronos
77 // mounted which is where the consent knob lives. We don't have that mount
78 // in our own mount namespace (by design). https://crbug.com/884249
Chris Morin853d3442019-04-01 21:35:13 -070079 {kCommand, "CLIENT_ID", "/usr/bin/nsenter -t1 -m /usr/bin/metrics_client -i",
80 kRoot, kDebugfsGroup},
81 {kCommand, "LOGDATE", "/bin/date"},
82 {kFile, "atrus_logs", "/var/log/atrus.log"},
83 {kFile, "authpolicy", "/var/log/authpolicy.log"},
84 {kCommand, "bootstat_summary", "/usr/bin/bootstat_summary"},
85 {kFile, "bio_crypto_init.log",
86 "/var/log/bio_crypto_init/bio_crypto_init.log"},
87 {kFile, "biod.LATEST", "/var/log/biod/biod.LATEST"},
88 {kFile, "biod.PREVIOUS", "/var/log/biod/biod.PREVIOUS"},
89 {kFile, "bios_info", "/var/log/bios_info.txt"},
90 {kCommand, "bios_log", "cat /sys/firmware/log "
91 "/proc/device-tree/chosen/ap-console-buffer 2>/dev/null"},
92 {kFile, "bios_times", "/var/log/bios_times.txt"},
93 {kCommand, "board-specific",
94 "/usr/share/userfeedback/scripts/get_board_specific_info"},
95 {kFile, "buddyinfo", "/proc/buddyinfo"},
96 {kCommand, "cbi_info", "/usr/share/userfeedback/scripts/cbi_info", kRoot,
97 kRoot},
98 {kFile, "cheets_log", "/var/log/arc.log"},
99 {kFile, "clobber.log", "/var/log/clobber.log"},
100 {kFile, "clobber-state.log", "/var/log/clobber-state.log"},
101 {kFile, "chrome_system_log", "/var/log/chrome/chrome"},
102 {kFile, "chrome_system_log.PREVIOUS", "/var/log/chrome/chrome.PREVIOUS"},
Mike Frysinger32cdf3e2017-08-14 18:17:06 -0400103 // There might be more than one record, so grab them all.
104 // Plus, for <linux-3.19, it's named "console-ramoops", but for newer
105 // versions, it's named "console-ramoops-#".
Chris Morin853d3442019-04-01 21:35:13 -0700106 {kCommand, "console-ramoops",
107 "cat /sys/fs/pstore/console-ramoops* 2>/dev/null"},
108 {kFile, "cpuinfo", "/proc/cpuinfo"},
109 {kFile, "cr50_version", "/var/cache/cr50-version"},
110 {kFile, "cros_ec.log", "/var/log/cros_ec.log"},
111 {kFile, "cros_ec.previous", "/var/log/cros_ec.previous"},
112 {kFile, "cros_ec_panicinfo", "/sys/kernel/debug/cros_ec/panicinfo",
113 SandboxedProcess::kDefaultUser, kDebugfsGroup},
114 {kFile, "cros_ec_pdinfo", "/sys/kernel/debug/cros_ec/pdinfo",
115 SandboxedProcess::kDefaultUser, kDebugfsGroup},
116 {kFile, "cros_fp.previous", "/var/log/cros_fp.previous"},
117 {kFile, "cros_fp.log", "/var/log/cros_fp.log"},
118 {kCommand, "dmesg", "/bin/dmesg"},
119 {kFile, "ec_info", "/var/log/ec_info.txt"},
Miguel Casas8d4e54f2018-03-29 09:42:52 -0400120 // The sed command replaces the EDID serial number (4 bytes at position 12)
121 // with zeroes. See https://en.wikipedia.org/wiki/EDID#EDID_1.4_data_format.
Chris Morin853d3442019-04-01 21:35:13 -0700122 {kCommand, "edid-decode",
123 "for f in /sys/class/drm/card0-*/edid; do "
124 "echo \"----------- ${f}\"; "
125 "sed -E 's/^(.{11}).{4}/\\1\\x0\\x0\\x0\\x0/' \"${f}\" | "
126 // edid-decode's stderr output is redundant, so silence it.
127 "edid-decode 2>/dev/null; "
128 "done"},
129 {kFile, "eventlog", "/var/log/eventlog.txt"},
130 {kFile, "exynos_gem_objects", "/sys/kernel/debug/dri/0/exynos_gem_objects",
131 SandboxedProcess::kDefaultUser, kDebugfsGroup},
132 {kCommand, "font_info", "/usr/share/userfeedback/scripts/font_info"},
133 {kFile, "fwupd_state", "/var/lib/fwupd/state.json"},
134 {kCommand, "sensor_info", "/usr/share/userfeedback/scripts/sensor_info"},
135 {kFile, "hammerd", "/var/log/hammerd.log"},
136 {kCommand, "hardware_class", "/usr/bin/crossystem hwid"},
137 {kCommand, "hostname", "/bin/hostname"},
138 {kFile, "i915_gem_gtt", "/sys/kernel/debug/dri/0/i915_gem_gtt",
139 SandboxedProcess::kDefaultUser, kDebugfsGroup},
140 {kFile, "i915_gem_objects", "/sys/kernel/debug/dri/0/i915_gem_objects",
141 SandboxedProcess::kDefaultUser, kDebugfsGroup},
142 {kFile, "i915_gem_objects", "/sys/kernel/debug/dri/0/i915_gem_objects",
143 SandboxedProcess::kDefaultUser, kDebugfsGroup},
144 {kCommand, "i915_error_state",
145 "/usr/bin/xz -c /sys/kernel/debug/dri/0/i915_error_state 2>/dev/null",
146 SandboxedProcess::kDefaultUser, kDebugfsGroup, Log::kDefaultMaxBytes,
147 LogTool::Encoding::kBinary},
148 {kCommand, "ifconfig", "/bin/ifconfig -a"},
149 {kFile, "input_devices", "/proc/bus/input/devices"},
Eric Carusob1820c02017-08-24 15:39:56 -0700150 // Information about the wiphy device, such as current channel.
Chris Morin853d3442019-04-01 21:35:13 -0700151 {kCommand, "iw_dev", "/usr/sbin/iw dev"},
Eric Carusob1820c02017-08-24 15:39:56 -0700152 // Hardware capabilities of the wiphy device.
Chris Morin853d3442019-04-01 21:35:13 -0700153 {kCommand, "iw_list", "/usr/sbin/iw list"},
Eric Carusoa879fd92017-10-11 12:57:10 -0700154#if USE_IWLWIFI_DUMP
Chris Morin853d3442019-04-01 21:35:13 -0700155 {kCommand, "iwlmvm_module_params", CMD_KERNEL_MODULE_PARAMS(iwlmvm)},
156 {kCommand, "iwlwifi_module_params", CMD_KERNEL_MODULE_PARAMS(iwlwifi)},
Eric Carusoa879fd92017-10-11 12:57:10 -0700157#endif // USE_IWLWIFI_DUMP
Chris Morin853d3442019-04-01 21:35:13 -0700158 {kCommand, "kernel-crashes",
159 "cat /var/spool/crash/kernel.*.kcrash 2>/dev/null"},
160 {kCommand, "logcat", "/usr/sbin/android-sh -c '/system/bin/logcat -d'",
161 kRoot, kRoot, Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
162 {kCommand, "lsmod", "lsmod"},
163 {kCommand, "lspci", "/usr/sbin/lspci"},
164 {kCommand, "lsusb", "lsusb && lsusb -t"},
165 {kFile, "mali_memory", "/sys/class/misc/mali0/device/memory"},
166 {kFile, "memd.parameters", "/var/log/memd/memd.parameters"},
167 {kCommand, "memd clips", "cat /var/log/memd/memd.clip* 2>/dev/null"},
168 {kFile, "meminfo", "/proc/meminfo"},
169 {kCommand, "memory_spd_info",
170 // mosys may use 'i2c-dev', which may not be loaded yet.
171 "modprobe i2c-dev 2>/dev/null && mosys -l memory spd print all 2>/dev/null",
172 kRoot, kDebugfsGroup},
Simon Quecb63b9c2017-06-19 14:53:31 -0400173 // The sed command finds the EDID blob (starting the line after "value:") and
174 // replaces the serial number with all zeroes.
175 //
176 // The EDID is printed as a hex dump over several lines, each line containing
177 // the contents of 16 bytes. The first 16 bytes are broken down as follows:
178 // uint64_t fixed_pattern; // Always 00 FF FF FF FF FF FF 00.
179 // uint16_t manufacturer_id; // Manufacturer ID, encoded as PNP IDs.
180 // uint16_t product_code; // Manufacturer product code, little-endian.
181 // uint32_t serial_number; // Serial number, little-endian.
182 // Source: https://en.wikipedia.org/wiki/EDID#EDID_1.3_data_format
183 //
184 // The subsequent substitution command looks for the fixed pattern followed by
185 // two 32-bit fields (manufacturer + product, serial number). It replaces the
186 // latter field with 8 bytes of zeroes.
187 //
188 // TODO(crbug.com/731133): Remove the sed command once modetest itself can
189 // remove serial numbers.
Chris Morin853d3442019-04-01 21:35:13 -0700190 {kCommand, "modetest",
191 "(modetest; modetest -M evdi; modetest -M udl) | "
192 "sed -E '/EDID/ {:a;n;/value:/!ba;n;"
193 "s/(00f{12}00)([0-9a-f]{8})([0-9a-f]{8})/\\1\\200000000/}'",
194 kRoot, kRoot},
195 {kFile, "mount-encrypted", "/var/log/mount-encrypted.log"},
196 {kFile, "mountinfo", "/proc/1/mountinfo"},
197 {kCommand, "netlog",
198 "/usr/share/userfeedback/scripts/getmsgs /var/log/net.log"},
Kevin Cernekee143e2af2018-03-20 13:28:20 -0700199 // --processes requires root.
Chris Morin853d3442019-04-01 21:35:13 -0700200 {kCommand, "netstat",
201 "/sbin/ss --all --query inet --numeric --processes", kRoot, kRoot},
202 {kFile, "nvmap_iovmm", "/sys/kernel/debug/nvmap/iovmm/allocations",
203 SandboxedProcess::kDefaultUser, kDebugfsGroup},
204 {kCommand, "oemdata", "/usr/share/cros/oemdata.sh", kRoot, kRoot},
205 {kFile, "pagetypeinfo", "/proc/pagetypeinfo"},
206 {kCommand, "platform_info",
207 // mosys may use 'i2c-dev', which may not be loaded yet.
208 "modprobe i2c-dev 2>/dev/null && "
209 "for param in "
210 "vendor "
211 "name "
212 "version "
213 "family "
214 "model "
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700215
Chris Morin853d3442019-04-01 21:35:13 -0700216 "sku "
217 "customization "
218 "; do "
219 "mosys -l platform \"${param}\" 2>/dev/null; "
220 "done",
221 kRoot, kDebugfsGroup},
222 {kCommand, "power_supply_info", "/usr/bin/power_supply_info"},
223 {kCommand, "power_supply_sysfs", "/usr/bin/print_sysfs_power_supply_data"},
224 {kFile, "powerd.LATEST", "/var/log/power_manager/powerd.LATEST"},
225 {kFile, "powerd.PREVIOUS", "/var/log/power_manager/powerd.PREVIOUS"},
226 {kFile, "powerd.out", "/var/log/powerd.out"},
227 {kFile, "powerwash_count", "/var/log/powerwash_count"},
Brian Norris4cde3d12019-04-16 10:10:34 -0700228 {kCommand, "ps", "/bin/ps auxZ"},
yusukes34171ba2017-04-27 15:46:01 -0700229 // /proc/slabinfo is owned by root and has 0400 permission.
Chris Morin853d3442019-04-01 21:35:13 -0700230 {kFile, "slabinfo", "/proc/slabinfo", kRoot, kRoot},
231 {kFile, "storage_info", "/var/log/storage_info.txt"},
232 {kCommand, "swap_info", "/usr/share/cros/init/swap.sh status 2>/dev/null",
233 SandboxedProcess::kDefaultUser, kDebugfsGroup},
234 {kCommand, "syslog",
235 "/usr/share/userfeedback/scripts/getmsgs /var/log/messages"},
236 {kCommand, "system_log_stats",
237 "echo 'BLOCK_SIZE=1024'; "
238 "find /var/log/ -type f -exec du --block-size=1024 {} + | sort -n -r",
239 kRoot, kRoot},
240 {kCommand, "threads", "/bin/ps -T axo pid,ppid,spid,pcpu,ni,stat,time,comm"},
241 {kFile, "tlsdate", "/var/log/tlsdate.log"},
242 {kCommand, "top thread", "/usr/bin/top -Hb -n 1 | head -n 40"},
243 {kCommand, "top memory", "/usr/bin/top -o \"+%MEM\" -bn 1 | head -n 57"},
244 {kCommand, "touch_fw_version",
245 "grep -E"
246 " -e 'synaptics: Touchpad model'"
247 " -e 'chromeos-[a-z]*-touch-[a-z]*-update'"
248 " /var/log/messages | tail -n 20"},
249 {kCommand, "tpm-firmware-updater", "/usr/share/userfeedback/scripts/getmsgs "
250 "/var/log/tpm-firmware-updater.log"},
Mattias Nissler887dce22017-07-03 14:44:35 +0200251 // TODO(jorgelo,mnissler): Don't run this as root.
252 // On TPM 1.2 devices this will likely require adding a new user to the 'tss'
253 // group.
254 // On TPM 2.0 devices 'get_version_info' uses D-Bus and therefore can run as
255 // any user.
Chris Morin853d3442019-04-01 21:35:13 -0700256 {kCommand, "tpm_version", "/usr/sbin/tpm-manager get_version_info", kRoot,
257 kRoot},
258 {kCommand, "atmel_ts_refs",
259 "/opt/google/touch/scripts/atmel_tools.sh ts r", kRoot, kRoot},
260 {kCommand, "atmel_tp_refs",
261 "/opt/google/touch/scripts/atmel_tools.sh tp r", kRoot, kRoot},
262 {kCommand, "atmel_ts_deltas",
263 "/opt/google/touch/scripts/atmel_tools.sh ts d", kRoot, kRoot},
264 {kCommand, "atmel_tp_deltas",
265 "/opt/google/touch/scripts/atmel_tools.sh tp d", kRoot, kRoot},
266 {kFile, "stateful_trim_state", "/var/lib/trim/stateful_trim_state"},
267 {kFile, "stateful_trim_data", "/var/lib/trim/stateful_trim_data"},
268 {kFile, "ui_log", "/var/log/ui/ui.LATEST"},
269 {kCommand, "uname", "/bin/uname -a"},
270 {kCommand, "update_engine.log",
271 "cat $(ls -1tr /var/log/update_engine | tail -5 | sed"
272 " s.^./var/log/update_engine/.)"},
273 {kCommand, "uptime", "/usr/bin/cut -d' ' -f1 /proc/uptime"},
274 {kFile, "verified boot", "/var/log/debug_vboot_noisy.log"},
275 {kFile, "vmlog.1.LATEST", "/var/log/vmlog/vmlog.1.LATEST"},
276 {kFile, "vmlog.1.PREVIOUS", "/var/log/vmlog/vmlog.1.PREVIOUS"},
277 {kFile, "vmlog.LATEST", "/var/log/vmlog/vmlog.LATEST"},
278 {kFile, "vmlog.PREVIOUS", "/var/log/vmlog/vmlog.PREVIOUS"},
279 {kFile, "vmstat", "/proc/vmstat"},
280 {kFile, "vpd_2.0", "/var/log/vpd_2.0.txt"},
281 {kCommand, "wifi_status", "/usr/bin/network_diag --wifi-internal --no-log"},
282 {kFile, "zram compressed data size", "/sys/block/zram0/compr_data_size"},
283 {kFile, "zram original data size", "/sys/block/zram0/orig_data_size"},
284 {kFile, "zram total memory used", "/sys/block/zram0/mem_used_total"},
285 {kFile, "zram total reads", "/sys/block/zram0/num_reads"},
286 {kFile, "zram total writes", "/sys/block/zram0/num_writes"},
287 {kCommand, "zram new stats names",
288 "echo orig_size compr_size used_total limit used_max zero_pages migrated"},
289 {kFile, "zram new stats values", "/sys/block/zram0/mm_stat"},
290 {kFile, "cros_tp version", "/sys/class/chromeos/cros_tp/version"},
291 {kCommand, "cros_tp console", "/usr/sbin/ectool --name=cros_tp console",
292 kRoot, kRoot},
293 {kCommand, "cros_tp frame", "/usr/sbin/ectool --name=cros_tp tpframeget",
294 kRoot, kRoot},
295 {kCommand, "crostini", "/usr/bin/cicerone_client --get_info"},
Elly Jones03cd6d72012-06-11 13:04:28 -0400296 // Stuff pulled out of the original list. These need access to the running X
297 // session, which we'd rather not give to debugd, or return info specific to
298 // the current session (in the setsid(2) sense), which is not useful for
299 // debugd
Chris Morin853d3442019-04-01 21:35:13 -0700300 // {kCommand, "env", "set"},
301 // {kCommand, "setxkbmap", "/usr/bin/setxkbmap -print -query"},
302 // {kCommand, "xrandr", "/usr/bin/xrandr --verbose}
Elly Jones533c7c42012-08-10 15:07:05 -0400303};
304
Kevin Cernekee143e2af2018-03-20 13:28:20 -0700305// netstat and logcat should appear in chrome://system but not in feedback
306// reports. Open sockets may have privacy implications, and logcat is
307// already incorporated via arc-bugreport.
308const std::vector<string> kCommandLogsExclude = {"netstat", "logcat"};
309
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700310const std::vector<Log> kExtraLogs {
Ben Chan36e42282014-02-12 22:32:34 -0800311#if USE_CELLULAR
Chris Morin853d3442019-04-01 21:35:13 -0700312 {kCommand, "mm-status", "/usr/bin/modem status"},
Ben Chan36e42282014-02-12 22:32:34 -0800313#endif // USE_CELLULAR
Chris Morin853d3442019-04-01 21:35:13 -0700314 {kCommand, "network-devices", "/usr/bin/connectivity show devices"},
315 {kCommand, "network-services", "/usr/bin/connectivity show services"},
Elly Jones533c7c42012-08-10 15:07:05 -0400316};
317
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700318const std::vector<Log> kFeedbackLogs {
Ben Chan36e42282014-02-12 22:32:34 -0800319#if USE_CELLULAR
Chris Morin853d3442019-04-01 21:35:13 -0700320 {kCommand, "mm-status", "/usr/bin/modem status-feedback"},
Ben Chan36e42282014-02-12 22:32:34 -0800321#endif // USE_CELLULAR
Chris Morin853d3442019-04-01 21:35:13 -0700322 {kCommand, "network-devices",
323 "/usr/bin/connectivity show-feedback devices"},
324 {kCommand, "network-services",
325 "/usr/bin/connectivity show-feedback services"},
Elly Jones03cd6d72012-06-11 13:04:28 -0400326};
327
Ahmed Fakhry1498b4e2016-03-30 12:42:20 -0700328// List of log files needed to be part of the feedback report that are huge and
329// must be sent back to the client via the file descriptor using
330// LogTool::GetBigFeedbackLogs().
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700331const std::vector<Log> kBigFeedbackLogs{
Fletcher Woodruffc9f36a72019-03-20 08:05:15 -0600332 // ARC bugreport permissions are weird. Since we're just running cat,
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700333 // this shouldn't cause any issues.
Chris Morin853d3442019-04-01 21:35:13 -0700334 {kCommand, "arc-bugreport", "cat /run/arc/bugreport/pipe 2>/dev/null",
335 kRoot, kRoot, 10 * 1024 * 1024, LogTool::Encoding::kUtf8},
Ahmed Fakhry1498b4e2016-03-30 12:42:20 -0700336};
337
Gaurav Shahf6c8f2a2012-10-11 17:22:43 -0700338// List of log files that must directly be collected by Chrome. This is because
339// debugd is running under a VFS namespace and does not have access to later
340// cryptohome mounts.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700341using UserLog = std::pair<std::string, std::string>;
342const std::vector<UserLog> kUserLogs = {
Chris Morin853d3442019-04-01 21:35:13 -0700343 {"chrome_user_log", "log/chrome"},
344 {"libassistant_user_log", "log/libassistant.log"},
345 {"login-times", "login-times"},
346 {"logout-times", "logout-times"},
Gaurav Shahf6c8f2a2012-10-11 17:22:43 -0700347};
348
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800349// Fills |dictionary| with the anonymized contents of the logs in |logs|.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700350void GetLogsInDictionary(const std::vector<Log>& logs,
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800351 AnonymizerTool* anonymizer,
352 base::DictionaryValue* dictionary) {
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700353 for (const Log& log : logs) {
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800354 dictionary->SetStringWithoutPathExpansion(
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700355 log.GetName(), anonymizer->Anonymize(log.GetLogData()));
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800356 }
357}
358
359// Serializes the |dictionary| into the file with the given |fd| in a JSON
360// format.
361void SerializeLogsAsJSON(const base::DictionaryValue& dictionary,
Eric Caruso0b241882018-04-04 13:43:46 -0700362 const base::ScopedFD& fd) {
Eric Caruso96d03d32017-04-25 18:01:17 -0700363 string logs_json;
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800364 base::JSONWriter::WriteWithOptions(dictionary,
365 base::JSONWriter::OPTIONS_PRETTY_PRINT,
366 &logs_json);
Eric Caruso0b241882018-04-04 13:43:46 -0700367 base::WriteFileDescriptor(fd.get(), logs_json.c_str(), logs_json.size());
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800368}
369
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700370bool GetNamedLogFrom(const string& name,
371 const std::vector<Log>& logs,
Elly Jones533c7c42012-08-10 15:07:05 -0400372 string* result) {
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700373 for (const Log& log : logs) {
374 if (name == log.GetName()) {
375 *result = log.GetLogData();
Elly Jones533c7c42012-08-10 15:07:05 -0400376 return true;
377 }
378 }
379 *result = "<invalid log name>";
380 return false;
Elly Jones03cd6d72012-06-11 13:04:28 -0400381}
382
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700383void GetLogsFrom(const std::vector<Log>& logs, LogTool::LogMap* map) {
384 for (const Log& log : logs)
385 (*map)[log.GetName()] = log.GetLogData();
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800386}
387
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600388void GetLsbReleaseInfo(LogTool::LogMap* map) {
389 const base::FilePath lsb_release(kLsbReleasePath);
390 brillo::KeyValueStore store;
391 if (!store.Load(lsb_release)) {
392 // /etc/lsb-release might not be present (cros deploying a new
393 // configuration or no fields set at all). Just print a debug
394 // message and continue.
395 DLOG(INFO) << "Could not load fields from " << lsb_release.value();
396 } else {
397 for (const auto& key : store.GetKeys()) {
398 std::string value;
399 store.GetString(key, &value);
400 (*map)[key] = value;
401 }
402 }
403}
404
405void GetOsReleaseInfo(LogTool::LogMap* map) {
406 brillo::OsReleaseReader reader;
407 reader.Load();
408 for (const auto& key : reader.GetKeys()) {
409 std::string value;
410 reader.GetString(key, &value);
411 (*map)["os-release " + key] = value;
412 }
413}
414
415void PopulateDictionaryValue(const LogTool::LogMap& map,
416 base::DictionaryValue* dictionary) {
417 for (const auto& kv : map) {
418 dictionary->SetString(kv.first, kv.second);
419 }
420}
421
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800422bool CompressXzBuffer(const std::vector<uint8_t>& in_buffer,
423 std::vector<uint8_t>* out_buffer) {
424 size_t out_size = lzma_stream_buffer_bound(in_buffer.size());
425 out_buffer->resize(out_size);
426 size_t out_pos = 0;
427
428 lzma_ret ret = lzma_easy_buffer_encode(
429 LZMA_PRESET_DEFAULT, LZMA_CHECK_CRC64, nullptr, in_buffer.data(),
430 in_buffer.size(), out_buffer->data(), &out_pos, out_size);
431
432 if (ret != LZMA_OK) {
433 out_buffer->clear();
434 return false;
435 }
436
437 out_buffer->resize(out_pos);
438 return true;
439}
440
441void GetPerfData(LogTool::LogMap* map) {
442 // Run perf to collect system-wide performance profile when user triggers
443 // feedback report. Perf runs at sampling frequency of ~500 hz (499 is used
444 // to avoid sampling periodic system activities), with callstack in each
445 // sample (-g).
446 std::vector<std::string> perf_args = {
447 "perf", "record", "-a", "-g", "-F", "499"
448 };
449 std::vector<uint8_t> perf_data;
450 int32_t status;
451
452 debugd::PerfTool perf_tool;
453 if (!perf_tool.GetPerfOutput(kPerfDurationSecs, perf_args, &perf_data,
454 nullptr, &status, nullptr))
455 return;
456
457 // XZ compress the profile data.
458 std::vector<uint8_t> perf_data_xz;
459 if (!CompressXzBuffer(perf_data, &perf_data_xz))
460 return;
461
462 // Base64 encode the compressed data.
463 std::string perf_data_str(reinterpret_cast<const char*>(perf_data_xz.data()),
464 perf_data_xz.size());
465 (*map)["perf-data"] =
Chinglin Yu3c8d0a22019-02-20 11:32:52 +0800466 std::string(kPerfDataDescription) +
Chris Morin853d3442019-04-01 21:35:13 -0700467 LogTool::EnsureUTF8String(std::move(perf_data_str),
468 LogTool::Encoding::kBinary);
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800469}
470
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800471} // namespace
472
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700473Log::Log(Log::LogType type,
474 std::string name,
475 std::string data,
476 std::string user,
477 std::string group,
478 int64_t max_bytes,
479 LogTool::Encoding encoding)
480 : type_(type),
481 name_(name),
482 data_(data),
483 user_(user),
484 group_(group),
485 max_bytes_(max_bytes),
486 encoding_(encoding) {}
487
488std::string Log::GetName() const {
489 return name_;
490}
491
492std::string Log::GetLogData() const {
493 // The reason this code uses a switch statement on a type enum rather than
494 // using inheritance/virtual dispatch is so that all of the Log objects can
495 // be constructed statically. Switching to heap allocated subclasses of Log
496 // makes the code that declares all of the log entries much more verbose
497 // and harder to understand.
498 switch (type_) {
499 case kCommand:
500 return GetCommandLogData();
501 case kFile:
502 return GetFileLogData();
503 default:
504 return "<unknown log type>";
505 }
506}
507
508// TODO(ellyjones): sandbox. crosbug.com/35122
509std::string Log::GetCommandLogData() const {
510 if (type_ != kCommand)
511 return "<log type mismatch>";
512 std::string tailed_cmdline =
513 base::StringPrintf("%s | tail -c %" PRId64, data_.c_str(), max_bytes_);
514 ProcessWithOutput p;
515 if (minijail_disabled_for_test_)
516 p.set_use_minijail(false);
517 if (!user_.empty() && !group_.empty())
518 p.SandboxAs(user_, group_);
519 if (!p.Init())
520 return "<not available>";
521 p.AddArg(kShell);
522 p.AddStringOption("-c", tailed_cmdline);
523 if (p.Run())
524 return "<not available>";
525 std::string output;
526 p.GetOutput(&output);
527 if (output.empty())
528 return "<empty>";
Chris Morin853d3442019-04-01 21:35:13 -0700529 return LogTool::EnsureUTF8String(std::move(output), encoding_);
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700530}
531
532std::string Log::GetFileLogData() const {
533 if (type_ != kFile)
534 return "<log type mismatch>";
535
536 uid_t old_euid = geteuid();
537 uid_t new_euid = UidForUser(user_);
538 gid_t old_egid = getegid();
539 gid_t new_egid = GidForGroup(group_);
540
541 if (new_euid == -1 || new_egid == -1) {
542 return "<not available>";
543 }
544
545 // Make sure to set group first, since if we set user first we lose root
546 // and therefore the ability to set our effective gid to arbitrary gids.
547 if (setegid(new_egid)) {
548 PLOG(ERROR) << "Failed to set effective group id to " << new_egid;
549 return "<not available>";
550 }
551 if (seteuid(new_euid)) {
552 PLOG(ERROR) << "Failed to set effective user id to " << new_euid;
553 if (setegid(old_egid))
554 PLOG(ERROR) << "Failed to restore effective group id to " << old_egid;
555 return "<not available>";
556 }
557
558 std::string contents;
559 const base::FilePath path(data_);
560 // Handle special files that don't properly report length/allow lseek.
561 if (base::FilePath("/dev").IsParent(path) ||
562 base::FilePath("/proc").IsParent(path) ||
563 base::FilePath("/sys").IsParent(path)) {
564 if (!base::ReadFileToString(path, &contents))
565 contents = "<not available>";
566 if (contents.size() > max_bytes_)
567 contents.erase(0, contents.size() - max_bytes_);
568 } else {
569 base::File file(path, base::File::FLAG_OPEN | base::File::FLAG_READ);
570 if (!file.IsValid()) {
571 contents = "<not available>";
572 } else {
573 int64_t length = file.GetLength();
574 if (length > max_bytes_) {
575 file.Seek(base::File::FROM_END, -max_bytes_);
576 length = max_bytes_;
577 }
578 std::vector<char> buf(length);
579 int read = file.ReadAtCurrentPos(buf.data(), buf.size());
580 if (read < 0) {
581 PLOG(ERROR) << "Could not read from file " << path.value();
582 } else {
583 contents = std::string(buf.begin(), buf.begin() + read);
584 }
585 }
586 }
587
588 if (contents.empty())
589 contents = "<empty>";
590
591 // Make sure we restore our old euid/egid before returning.
592 if (seteuid(old_euid))
593 PLOG(ERROR) << "Failed to restore effective user id to " << old_euid;
594
595 if (setegid(old_egid))
596 PLOG(ERROR) << "Failed to restore effective group id to " << old_egid;
597
Chris Morin853d3442019-04-01 21:35:13 -0700598 return LogTool::EnsureUTF8String(std::move(contents), encoding_);
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700599}
600
601void Log::DisableMinijailForTest() {
602 minijail_disabled_for_test_ = true;
603}
604
605// static
606uid_t Log::UidForUser(const std::string& user) {
607 struct passwd entry;
608 struct passwd* result;
609 std::vector<char> buf(1024);
610 getpwnam_r(user.c_str(), &entry, &buf[0], buf.size(), &result);
611 if (!result) {
612 LOG(ERROR) << "User not found: " << user;
613 return -1;
614 }
615 return entry.pw_uid;
616}
617
618// static
619gid_t Log::GidForGroup(const std::string& group) {
620 struct group entry;
621 struct group* result;
622 std::vector<char> buf(1024);
623 getgrnam_r(group.c_str(), &entry, &buf[0], buf.size(), &result);
624 if (!result) {
625 LOG(ERROR) << "Group not found: " << group;
626 return -1;
627 }
628 return entry.gr_gid;
629}
630
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700631void LogTool::CreateConnectivityReport(bool wait_for_results) {
Rebecca Silbersteine78af402014-10-02 10:55:04 -0700632 // Perform ConnectivityTrial to report connection state in feedback log.
Ben Chan8e9f6d02017-09-26 23:04:21 -0700633 auto shill = std::make_unique<org::chromium::flimflam::ManagerProxy>(bus_);
Rebecca Silbersteine78af402014-10-02 10:55:04 -0700634 // Give the connection trial time to test the connection and log the results
635 // before collecting the logs for feedback.
636 // TODO(silberst): Replace the simple approach of a single timeout with a more
637 // coordinated effort.
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700638 if (shill && shill->CreateConnectivityReport(nullptr) && wait_for_results)
Eric Carusocc7106c2017-04-27 14:22:42 -0700639 sleep(kConnectionTesterTimeoutSeconds);
Rebecca Silbersteine78af402014-10-02 10:55:04 -0700640}
641
Eric Carusoc93a15c2017-04-24 16:15:12 -0700642string LogTool::GetLog(const string& name) {
Elly Jones533c7c42012-08-10 15:07:05 -0400643 string result;
Ben Chancf7d6412017-08-10 22:30:09 -0700644 GetNamedLogFrom(name, kCommandLogs, &result)
645 || GetNamedLogFrom(name, kExtraLogs, &result)
646 || GetNamedLogFrom(name, kFeedbackLogs, &result);
Elly Jones533c7c42012-08-10 15:07:05 -0400647 return result;
648}
649
Eric Carusof9091f82017-04-28 14:18:59 -0700650LogTool::LogMap LogTool::GetAllLogs() {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700651 CreateConnectivityReport(false);
Elly Jones533c7c42012-08-10 15:07:05 -0400652 LogMap result;
Ben Chancf7d6412017-08-10 22:30:09 -0700653 GetLogsFrom(kCommandLogs, &result);
654 GetLogsFrom(kExtraLogs, &result);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600655 GetLsbReleaseInfo(&result);
656 GetOsReleaseInfo(&result);
Elly Jones533c7c42012-08-10 15:07:05 -0400657 return result;
658}
659
Brian Norrisca4fc042018-04-03 00:24:26 -0700660LogTool::LogMap LogTool::GetAllDebugLogs() {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700661 CreateConnectivityReport(true);
Brian Norrisca4fc042018-04-03 00:24:26 -0700662 LogMap result;
663 GetLogsFrom(kCommandLogs, &result);
664 GetLogsFrom(kExtraLogs, &result);
665 GetLogsFrom(kBigFeedbackLogs, &result);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600666 GetLsbReleaseInfo(&result);
667 GetOsReleaseInfo(&result);
Brian Norrisca4fc042018-04-03 00:24:26 -0700668 return result;
669}
670
Eric Carusof9091f82017-04-28 14:18:59 -0700671LogTool::LogMap LogTool::GetFeedbackLogs() {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700672 CreateConnectivityReport(true);
Elly Jones533c7c42012-08-10 15:07:05 -0400673 LogMap result;
Ben Chancf7d6412017-08-10 22:30:09 -0700674 GetLogsFrom(kCommandLogs, &result);
Kevin Cernekee143e2af2018-03-20 13:28:20 -0700675 for (const auto& key : kCommandLogsExclude) {
676 result.erase(key);
677 }
Ben Chancf7d6412017-08-10 22:30:09 -0700678 GetLogsFrom(kFeedbackLogs, &result);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600679 GetLsbReleaseInfo(&result);
680 GetOsReleaseInfo(&result);
Darin Petkovce9b3a12013-01-10 16:38:54 +0100681 AnonymizeLogMap(&result);
Elly Jones03cd6d72012-06-11 13:04:28 -0400682 return result;
683}
684
Eric Caruso0b241882018-04-04 13:43:46 -0700685void LogTool::GetBigFeedbackLogs(const base::ScopedFD& fd) {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700686 CreateConnectivityReport(true);
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800687 LogMap map;
688 GetPerfData(&map);
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800689 base::DictionaryValue dictionary;
Ben Chancf7d6412017-08-10 22:30:09 -0700690 GetLogsInDictionary(kCommandLogs, &anonymizer_, &dictionary);
Kevin Cernekee143e2af2018-03-20 13:28:20 -0700691 for (const auto& key : kCommandLogsExclude) {
692 dictionary.Remove(key, nullptr);
693 }
Ben Chancf7d6412017-08-10 22:30:09 -0700694 GetLogsInDictionary(kFeedbackLogs, &anonymizer_, &dictionary);
695 GetLogsInDictionary(kBigFeedbackLogs, &anonymizer_, &dictionary);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600696 GetLsbReleaseInfo(&map);
697 GetOsReleaseInfo(&map);
698 PopulateDictionaryValue(map, &dictionary);
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800699 SerializeLogsAsJSON(dictionary, fd);
700}
701
Eric Carusoc93a15c2017-04-24 16:15:12 -0700702LogTool::LogMap LogTool::GetUserLogFiles() {
Gaurav Shahf6c8f2a2012-10-11 17:22:43 -0700703 LogMap result;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700704 for (const UserLog& ul : kUserLogs)
705 result[ul.first] = ul.second;
Gaurav Shahf6c8f2a2012-10-11 17:22:43 -0700706 return result;
707}
708
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -0700709// static
Chris Morin853d3442019-04-01 21:35:13 -0700710string LogTool::EnsureUTF8String(string value,
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -0700711 LogTool::Encoding source_encoding) {
712 if (source_encoding == LogTool::Encoding::kAutodetect) {
713 if (base::IsStringUTF8(value))
714 return value;
715 source_encoding = LogTool::Encoding::kBinary;
716 }
717
718 if (source_encoding == LogTool::Encoding::kUtf8) {
719 string output;
720 const char* src = value.data();
721 int32_t src_len = static_cast<int32_t>(value.length());
722
723 output.reserve(value.size());
724 for (int32_t char_index = 0; char_index < src_len; char_index++) {
725 uint32_t code_point;
726 if (!base::ReadUnicodeCharacter(src, src_len, &char_index, &code_point) ||
727 !base::IsValidCharacter(code_point)) {
728 // Replace invalid characters with U+FFFD REPLACEMENT CHARACTER.
729 code_point = 0xFFFD;
730 }
731 base::WriteUnicodeCharacter(code_point, &output);
732 }
733 return output;
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -0700734 }
Chris Morin853d3442019-04-01 21:35:13 -0700735
736 base::Base64Encode(value, &value);
737 return "<base64>: " + value;
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -0700738}
739
Darin Petkovce9b3a12013-01-10 16:38:54 +0100740void LogTool::AnonymizeLogMap(LogMap* log_map) {
Ben Chane2fa3572017-02-08 22:46:18 -0800741 for (auto& entry : *log_map)
742 entry.second = anonymizer_.Anonymize(entry.second);
Darin Petkovce9b3a12013-01-10 16:38:54 +0100743}
744
Ben Chana0011d82014-05-13 00:19:29 -0700745} // namespace debugd