blob: 016ab86724f9e49733a158cd46270538ff45a39f [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
Fletcher Woodruff07c28532019-01-24 11:08:53 -070079 Log(kCommand, "CLIENT_ID",
80 "/usr/bin/nsenter -t1 -m /usr/bin/metrics_client -i", kRoot,
81 kDebugfsGroup),
82 Log(kCommand, "LOGDATE", "/bin/date"),
83 Log(kFile, "atrus_logs", "/var/log/atrus.log"),
84 Log(kFile, "authpolicy", "/var/log/authpolicy.log"),
85 Log(kCommand, "bootstat_summary", "/usr/bin/bootstat_summary"),
86 Log(kFile, "bio_crypto_init.log",
87 "/var/log/bio_crypto_init/bio_crypto_init.log"),
88 Log(kFile, "biod.LATEST", "/var/log/biod/biod.LATEST"),
89 Log(kFile, "biod.PREVIOUS", "/var/log/biod/biod.PREVIOUS"),
90 Log(kFile, "bios_info", "/var/log/bios_info.txt"),
91 Log(kCommand, "bios_log",
92 "cat /sys/firmware/log "
93 "/proc/device-tree/chosen/ap-console-buffer 2>/dev/null"),
94 Log(kFile, "bios_times", "/var/log/bios_times.txt"),
95 Log(kCommand, "board-specific",
96 "/usr/share/userfeedback/scripts/get_board_specific_info"),
97 Log(kFile, "buddyinfo", "/proc/buddyinfo"),
98 Log(kCommand, "cbi_info", "/usr/share/userfeedback/scripts/cbi_info", kRoot,
99 kRoot),
100 Log(kFile, "cheets_log", "/var/log/arc.log"),
101 Log(kFile, "clobber.log", "/var/log/clobber.log"),
102 Log(kFile, "clobber-state.log", "/var/log/clobber-state.log"),
103 Log(kFile, "chrome_system_log", "/var/log/chrome/chrome"),
104 Log(kFile, "chrome_system_log.PREVIOUS", "/var/log/chrome/chrome.PREVIOUS"),
Mike Frysinger32cdf3e2017-08-14 18:17:06 -0400105 // There might be more than one record, so grab them all.
106 // Plus, for <linux-3.19, it's named "console-ramoops", but for newer
107 // versions, it's named "console-ramoops-#".
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700108 Log(kCommand, "console-ramoops",
109 "cat /sys/fs/pstore/console-ramoops* 2>/dev/null"),
110 Log(kFile, "cpuinfo", "/proc/cpuinfo"),
111 Log(kFile, "cr50_version", "/var/cache/cr50-version"),
112 Log(kFile, "cros_ec.log", "/var/log/cros_ec.log"),
113 Log(kFile, "cros_ec.previous", "/var/log/cros_ec.previous"),
114 Log(kFile, "cros_ec_panicinfo", "/sys/kernel/debug/cros_ec/panicinfo",
115 SandboxedProcess::kDefaultUser, kDebugfsGroup),
116 Log(kFile, "cros_ec_pdinfo", "/sys/kernel/debug/cros_ec/pdinfo",
117 SandboxedProcess::kDefaultUser, kDebugfsGroup),
118 Log(kFile, "cros_fp.previous", "/var/log/cros_fp.previous"),
119 Log(kFile, "cros_fp.log", "/var/log/cros_fp.log"),
120 Log(kCommand, "dmesg", "/bin/dmesg"),
121 Log(kFile, "ec_info", "/var/log/ec_info.txt"),
Miguel Casas8d4e54f2018-03-29 09:42:52 -0400122 // The sed command replaces the EDID serial number (4 bytes at position 12)
123 // with zeroes. See https://en.wikipedia.org/wiki/EDID#EDID_1.4_data_format.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700124 Log(kCommand, "edid-decode",
125 "for f in /sys/class/drm/card0-*/edid; do "
Miguel Casas8d4e54f2018-03-29 09:42:52 -0400126 "echo \"----------- ${f}\"; "
Miguel Casas1b8d2792018-08-17 20:00:52 -0400127 "sed -E 's/^(.{11}).{4}/\\1\\x0\\x0\\x0\\x0/' \"${f}\" | "
128 // edid-decode's stderr output is redundant, so silence it.
129 "edid-decode 2>/dev/null; "
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700130 "done"),
131 Log(kFile, "eventlog", "/var/log/eventlog.txt"),
132 Log(kFile, "exynos_gem_objects", "/sys/kernel/debug/dri/0/exynos_gem_objects",
133 SandboxedProcess::kDefaultUser, kDebugfsGroup),
134 Log(kCommand, "font_info", "/usr/share/userfeedback/scripts/font_info"),
135 Log(kCommand, "sensor_info", "/usr/share/userfeedback/scripts/sensor_info"),
136 Log(kFile, "hammerd", "/var/log/hammerd.log"),
137 Log(kCommand, "hardware_class", "/usr/bin/crossystem hwid"),
138 Log(kCommand, "hostname", "/bin/hostname"),
139 Log(kFile, "i915_gem_gtt", "/sys/kernel/debug/dri/0/i915_gem_gtt",
140 SandboxedProcess::kDefaultUser, kDebugfsGroup),
141 Log(kFile, "i915_gem_objects", "/sys/kernel/debug/dri/0/i915_gem_objects",
142 SandboxedProcess::kDefaultUser, kDebugfsGroup),
143 Log(kFile, "i915_gem_objects", "/sys/kernel/debug/dri/0/i915_gem_objects",
144 SandboxedProcess::kDefaultUser, kDebugfsGroup),
145 Log(kCommand, "i915_error_state",
146 "/usr/bin/xz -c /sys/kernel/debug/dri/0/i915_error_state 2>/dev/null",
147 SandboxedProcess::kDefaultUser, kDebugfsGroup, Log::kDefaultMaxBytes,
148 LogTool::Encoding::kBinary),
149 Log(kCommand, "ifconfig", "/bin/ifconfig -a"),
150 Log(kFile, "input_devices", "/proc/bus/input/devices"),
Eric Carusob1820c02017-08-24 15:39:56 -0700151 // Information about the wiphy device, such as current channel.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700152 Log(kCommand, "iw_dev", "/usr/sbin/iw dev"),
Eric Carusob1820c02017-08-24 15:39:56 -0700153 // Hardware capabilities of the wiphy device.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700154 Log(kCommand, "iw_list", "/usr/sbin/iw list"),
Eric Carusoa879fd92017-10-11 12:57:10 -0700155#if USE_IWLWIFI_DUMP
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700156 Log(kCommand, "iwlmvm_module_params", CMD_KERNEL_MODULE_PARAMS(iwlmvm)),
157 Log(kCommand, "iwlwifi_module_params", CMD_KERNEL_MODULE_PARAMS(iwlwifi)),
Eric Carusoa879fd92017-10-11 12:57:10 -0700158#endif // USE_IWLWIFI_DUMP
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700159 Log(kCommand, "kernel-crashes",
160 "cat /var/spool/crash/kernel.*.kcrash 2>/dev/null"),
161 Log(kCommand, "logcat", "/usr/sbin/android-sh -c '/system/bin/logcat -d'",
162 kRoot, kRoot, Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8),
163 Log(kCommand, "lsmod", "lsmod"),
164 Log(kCommand, "lspci", "/usr/sbin/lspci"),
165 Log(kCommand, "lsusb", "lsusb && lsusb -t"),
166 Log(kFile, "mali_memory", "/sys/class/misc/mali0/device/memory"),
167 Log(kFile, "memd.parameters", "/var/log/memd/memd.parameters"),
168 Log(kCommand, "memd clips", "cat /var/log/memd/memd.clip* 2>/dev/null"),
169 Log(kFile, "meminfo", "/proc/meminfo"),
170 Log(kCommand, "memory_spd_info",
171 // mosys may use 'i2c-dev', which may not be loaded yet.
172 "modprobe i2c-dev 2>/dev/null && "
173 "mosys -l memory spd print all 2>/dev/null",
174 kRoot, kDebugfsGroup),
Simon Quecb63b9c2017-06-19 14:53:31 -0400175 // The sed command finds the EDID blob (starting the line after "value:") and
176 // replaces the serial number with all zeroes.
177 //
178 // The EDID is printed as a hex dump over several lines, each line containing
179 // the contents of 16 bytes. The first 16 bytes are broken down as follows:
180 // uint64_t fixed_pattern; // Always 00 FF FF FF FF FF FF 00.
181 // uint16_t manufacturer_id; // Manufacturer ID, encoded as PNP IDs.
182 // uint16_t product_code; // Manufacturer product code, little-endian.
183 // uint32_t serial_number; // Serial number, little-endian.
184 // Source: https://en.wikipedia.org/wiki/EDID#EDID_1.3_data_format
185 //
186 // The subsequent substitution command looks for the fixed pattern followed by
187 // two 32-bit fields (manufacturer + product, serial number). It replaces the
188 // latter field with 8 bytes of zeroes.
189 //
190 // TODO(crbug.com/731133): Remove the sed command once modetest itself can
191 // remove serial numbers.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700192 Log(kCommand, "modetest",
193 "(modetest; modetest -M evdi; modetest -M udl) | "
194 "sed -E '/EDID/ {:a;n;/value:/!ba;n;"
195 "s/(00f{12}00)([0-9a-f]{8})([0-9a-f]{8})/\\1\\200000000/}'",
196 kRoot, kRoot),
197 Log(kFile, "mount-encrypted", "/var/log/mount-encrypted.log"),
198 Log(kFile, "mountinfo", "/proc/1/mountinfo"),
199 Log(kCommand, "netlog",
200 "/usr/share/userfeedback/scripts/getmsgs /var/log/net.log"),
Kevin Cernekee143e2af2018-03-20 13:28:20 -0700201 // --processes requires root.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700202 Log(kCommand, "netstat",
203 "/sbin/ss --all --query inet --numeric --processes", kRoot, kRoot),
204 Log(kFile, "nvmap_iovmm", "/sys/kernel/debug/nvmap/iovmm/allocations",
205 SandboxedProcess::kDefaultUser, kDebugfsGroup),
206 Log(kCommand, "oemdata", "/usr/share/cros/oemdata.sh", kRoot, kRoot),
207 Log(kFile, "pagetypeinfo", "/proc/pagetypeinfo"),
208 Log(kCommand, "platform_info",
209 // mosys may use 'i2c-dev', which may not be loaded yet.
210 "modprobe i2c-dev 2>/dev/null && "
211 "for param in "
212 "vendor "
213 "name "
214 "version "
215 "family "
216 "model "
217
218 "sku "
219 "customization "
220 "; do "
221 "mosys -l platform \"${param}\" 2>/dev/null; "
222 "done",
223 kRoot, kDebugfsGroup),
224 Log(kCommand, "power_supply_info", "/usr/bin/power_supply_info"),
225 Log(kCommand, "power_supply_sysfs",
226 "/usr/bin/print_sysfs_power_supply_data"),
227 Log(kFile, "powerd.LATEST", "/var/log/power_manager/powerd.LATEST"),
228 Log(kFile, "powerd.PREVIOUS", "/var/log/power_manager/powerd.PREVIOUS"),
229 Log(kFile, "powerd.out", "/var/log/powerd.out"),
230 Log(kFile, "powerwash_count", "/var/log/powerwash_count"),
Mattias Nissler887dce22017-07-03 14:44:35 +0200231 // Changed from 'ps ux' to 'ps aux' since we're running as debugd,
232 // not chronos.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700233 Log(kCommand, "ps", "/bin/ps aux"),
yusukes34171ba2017-04-27 15:46:01 -0700234 // /proc/slabinfo is owned by root and has 0400 permission.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700235 Log(kFile, "slabinfo", "/proc/slabinfo", kRoot, kRoot),
236 Log(kFile, "storage_info", "/var/log/storage_info.txt"),
237 Log(kCommand, "swap_info",
238 "/usr/share/cros/init/swap.sh status 2>/dev/null",
239 SandboxedProcess::kDefaultUser, kDebugfsGroup),
240 Log(kCommand, "syslog",
241 "/usr/share/userfeedback/scripts/getmsgs /var/log/messages"),
242 Log(kCommand, "system_log_stats",
243 "echo 'BLOCK_SIZE=1024'; "
244 "find /var/log/ -type f -exec du --block-size=1024 {} + | sort -n -r",
245 kRoot, kRoot),
246 Log(kCommand, "threads",
247 "/bin/ps -T axo pid,ppid,spid,pcpu,ni,stat,time,comm"),
248 Log(kFile, "tlsdate", "/var/log/tlsdate.log"),
249 Log(kCommand, "top thread", "/usr/bin/top -Hb -n 1 | head -n 40"),
250 Log(kCommand, "top memory", "/usr/bin/top -o \"+%MEM\" -bn 1 | head -n 57"),
251 Log(kCommand, "touch_fw_version",
252 "grep -E"
253 " -e 'synaptics: Touchpad model'"
254 " -e 'chromeos-[a-z]*-touch-[a-z]*-update'"
255 " /var/log/messages | tail -n 20"),
256 Log(kCommand, "tpm-firmware-updater",
257 "/usr/share/userfeedback/scripts/getmsgs "
258 "/var/log/tpm-firmware-updater.log"),
Mattias Nissler887dce22017-07-03 14:44:35 +0200259 // TODO(jorgelo,mnissler): Don't run this as root.
260 // On TPM 1.2 devices this will likely require adding a new user to the 'tss'
261 // group.
262 // On TPM 2.0 devices 'get_version_info' uses D-Bus and therefore can run as
263 // any user.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700264 Log(kCommand, "tpm_version", "/usr/sbin/tpm-manager get_version_info", kRoot,
265 kRoot),
266 Log(kCommand, "atmel_ts_refs",
267 "/opt/google/touch/scripts/atmel_tools.sh ts r", kRoot, kRoot),
268 Log(kCommand, "atmel_tp_refs",
269 "/opt/google/touch/scripts/atmel_tools.sh tp r", kRoot, kRoot),
270 Log(kCommand, "atmel_ts_deltas",
271 "/opt/google/touch/scripts/atmel_tools.sh ts d", kRoot, kRoot),
272 Log(kCommand, "atmel_tp_deltas",
273 "/opt/google/touch/scripts/atmel_tools.sh tp d", kRoot, kRoot),
274 Log(kFile, "stateful_trim_state", "/var/lib/trim/stateful_trim_state"),
275 Log(kFile, "stateful_trim_data", "/var/lib/trim/stateful_trim_data"),
276 Log(kCommand, "ui_log",
277 "/usr/share/userfeedback/scripts/get_log /var/log/ui/ui.LATEST"),
278 Log(kCommand, "uname", "/bin/uname -a"),
279 Log(kCommand, "update_engine.log",
280 "cat $(ls -1tr /var/log/update_engine | tail -5 | sed"
281 " s.^./var/log/update_engine/.)"),
282 Log(kCommand, "uptime", "/usr/bin/cut -d' ' -f1 /proc/uptime"),
283 Log(kFile, "verified boot", "/var/log/debug_vboot_noisy.log"),
284 Log(kFile, "vmlog.1.LATEST", "/var/log/vmlog/vmlog.1.LATEST"),
285 Log(kFile, "vmlog.1.PREVIOUS", "/var/log/vmlog/vmlog.1.PREVIOUS"),
286 Log(kFile, "vmlog.LATEST", "/var/log/vmlog/vmlog.LATEST"),
287 Log(kFile, "vmlog.PREVIOUS", "/var/log/vmlog/vmlog.PREVIOUS"),
288 Log(kFile, "vmstat", "/proc/vmstat"),
289 Log(kFile, "vpd_2.0", "/var/log/vpd_2.0.txt"),
290 Log(kCommand, "wifi_status",
291 "/usr/bin/network_diag --wifi-internal --no-log"),
292 Log(kFile, "zram compressed data size", "/sys/block/zram0/compr_data_size"),
293 Log(kFile, "zram original data size", "/sys/block/zram0/orig_data_size"),
294 Log(kFile, "zram total memory used", "/sys/block/zram0/mem_used_total"),
295 Log(kFile, "zram total reads", "/sys/block/zram0/num_reads"),
296 Log(kFile, "zram total writes", "/sys/block/zram0/num_writes"),
297 Log(kCommand, "zram new stats names",
298 "echo orig_size compr_size used_total limit used_max zero_pages "
299 "migrated"),
300 Log(kFile, "zram new stats values", "/sys/block/zram0/mm_stat"),
301 Log(kFile, "cros_tp version", "/sys/class/chromeos/cros_tp/version"),
302 Log(kCommand, "cros_tp console", "/usr/sbin/ectool --name=cros_tp console",
303 kRoot, kRoot),
304 Log(kCommand, "cros_tp frame", "/usr/sbin/ectool --name=cros_tp tpframeget",
305 kRoot, kRoot),
306 Log(kCommand, "crostini", "/usr/bin/cicerone_client --get_info"),
Elly Jones03cd6d72012-06-11 13:04:28 -0400307 // Stuff pulled out of the original list. These need access to the running X
308 // session, which we'd rather not give to debugd, or return info specific to
309 // the current session (in the setsid(2) sense), which is not useful for
310 // debugd
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700311 // Log(kCommand, "env", "set"),
312 // Log(kCommand, "setxkbmap", "/usr/bin/setxkbmap -print -query"),
313 // Log(kCommand, "xrandr", "/usr/bin/xrandr --verbose)
Elly Jones533c7c42012-08-10 15:07:05 -0400314};
315
Kevin Cernekee143e2af2018-03-20 13:28:20 -0700316// netstat and logcat should appear in chrome://system but not in feedback
317// reports. Open sockets may have privacy implications, and logcat is
318// already incorporated via arc-bugreport.
319const std::vector<string> kCommandLogsExclude = {"netstat", "logcat"};
320
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700321const std::vector<Log> kExtraLogs {
Ben Chan36e42282014-02-12 22:32:34 -0800322#if USE_CELLULAR
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700323 Log(kCommand, "mm-status", "/usr/bin/modem status"),
Ben Chan36e42282014-02-12 22:32:34 -0800324#endif // USE_CELLULAR
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700325 Log(kCommand, "network-devices", "/usr/bin/connectivity show devices"),
326 Log(kCommand, "network-services", "/usr/bin/connectivity show services"),
Elly Jones533c7c42012-08-10 15:07:05 -0400327};
328
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700329const std::vector<Log> kFeedbackLogs {
Ben Chan36e42282014-02-12 22:32:34 -0800330#if USE_CELLULAR
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700331 Log(kCommand, "mm-status", "/usr/bin/modem status-feedback"),
Ben Chan36e42282014-02-12 22:32:34 -0800332#endif // USE_CELLULAR
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700333 Log(kCommand, "network-devices",
334 "/usr/bin/connectivity show-feedback devices"),
335 Log(kCommand, "network-services",
336 "/usr/bin/connectivity show-feedback services"),
Elly Jones03cd6d72012-06-11 13:04:28 -0400337};
338
Ahmed Fakhry1498b4e2016-03-30 12:42:20 -0700339// List of log files needed to be part of the feedback report that are huge and
340// must be sent back to the client via the file descriptor using
341// LogTool::GetBigFeedbackLogs().
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700342const std::vector<Log> kBigFeedbackLogs{
343 // ARC bugreport permissions are weird. Since we're just reading a file,
344 // this shouldn't cause any issues.
345 Log(kFile, "arc-bugreport", "/run/arc/bugreport/pipe", kRoot, kRoot,
346 10 * 1024 * 1024, LogTool::Encoding::kUtf8),
Ahmed Fakhry1498b4e2016-03-30 12:42:20 -0700347};
348
Gaurav Shahf6c8f2a2012-10-11 17:22:43 -0700349// List of log files that must directly be collected by Chrome. This is because
350// debugd is running under a VFS namespace and does not have access to later
351// cryptohome mounts.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700352using UserLog = std::pair<std::string, std::string>;
353const std::vector<UserLog> kUserLogs = {
354 UserLog("chrome_user_log", "log/chrome"),
355 UserLog("libassistant_user_log", "log/libassistant.log"),
356 UserLog("login-times", "login-times"),
357 UserLog("logout-times", "logout-times"),
Gaurav Shahf6c8f2a2012-10-11 17:22:43 -0700358};
359
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800360// Fills |dictionary| with the anonymized contents of the logs in |logs|.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700361void GetLogsInDictionary(const std::vector<Log>& logs,
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800362 AnonymizerTool* anonymizer,
363 base::DictionaryValue* dictionary) {
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700364 for (const Log& log : logs) {
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800365 dictionary->SetStringWithoutPathExpansion(
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700366 log.GetName(), anonymizer->Anonymize(log.GetLogData()));
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800367 }
368}
369
370// Serializes the |dictionary| into the file with the given |fd| in a JSON
371// format.
372void SerializeLogsAsJSON(const base::DictionaryValue& dictionary,
Eric Caruso0b241882018-04-04 13:43:46 -0700373 const base::ScopedFD& fd) {
Eric Caruso96d03d32017-04-25 18:01:17 -0700374 string logs_json;
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800375 base::JSONWriter::WriteWithOptions(dictionary,
376 base::JSONWriter::OPTIONS_PRETTY_PRINT,
377 &logs_json);
Eric Caruso0b241882018-04-04 13:43:46 -0700378 base::WriteFileDescriptor(fd.get(), logs_json.c_str(), logs_json.size());
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800379}
380
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700381bool GetNamedLogFrom(const string& name,
382 const std::vector<Log>& logs,
Elly Jones533c7c42012-08-10 15:07:05 -0400383 string* result) {
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700384 for (const Log& log : logs) {
385 if (name == log.GetName()) {
386 *result = log.GetLogData();
Elly Jones533c7c42012-08-10 15:07:05 -0400387 return true;
388 }
389 }
390 *result = "<invalid log name>";
391 return false;
Elly Jones03cd6d72012-06-11 13:04:28 -0400392}
393
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700394void GetLogsFrom(const std::vector<Log>& logs, LogTool::LogMap* map) {
395 for (const Log& log : logs)
396 (*map)[log.GetName()] = log.GetLogData();
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800397}
398
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600399void GetLsbReleaseInfo(LogTool::LogMap* map) {
400 const base::FilePath lsb_release(kLsbReleasePath);
401 brillo::KeyValueStore store;
402 if (!store.Load(lsb_release)) {
403 // /etc/lsb-release might not be present (cros deploying a new
404 // configuration or no fields set at all). Just print a debug
405 // message and continue.
406 DLOG(INFO) << "Could not load fields from " << lsb_release.value();
407 } else {
408 for (const auto& key : store.GetKeys()) {
409 std::string value;
410 store.GetString(key, &value);
411 (*map)[key] = value;
412 }
413 }
414}
415
416void GetOsReleaseInfo(LogTool::LogMap* map) {
417 brillo::OsReleaseReader reader;
418 reader.Load();
419 for (const auto& key : reader.GetKeys()) {
420 std::string value;
421 reader.GetString(key, &value);
422 (*map)["os-release " + key] = value;
423 }
424}
425
426void PopulateDictionaryValue(const LogTool::LogMap& map,
427 base::DictionaryValue* dictionary) {
428 for (const auto& kv : map) {
429 dictionary->SetString(kv.first, kv.second);
430 }
431}
432
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800433bool CompressXzBuffer(const std::vector<uint8_t>& in_buffer,
434 std::vector<uint8_t>* out_buffer) {
435 size_t out_size = lzma_stream_buffer_bound(in_buffer.size());
436 out_buffer->resize(out_size);
437 size_t out_pos = 0;
438
439 lzma_ret ret = lzma_easy_buffer_encode(
440 LZMA_PRESET_DEFAULT, LZMA_CHECK_CRC64, nullptr, in_buffer.data(),
441 in_buffer.size(), out_buffer->data(), &out_pos, out_size);
442
443 if (ret != LZMA_OK) {
444 out_buffer->clear();
445 return false;
446 }
447
448 out_buffer->resize(out_pos);
449 return true;
450}
451
452void GetPerfData(LogTool::LogMap* map) {
453 // Run perf to collect system-wide performance profile when user triggers
454 // feedback report. Perf runs at sampling frequency of ~500 hz (499 is used
455 // to avoid sampling periodic system activities), with callstack in each
456 // sample (-g).
457 std::vector<std::string> perf_args = {
458 "perf", "record", "-a", "-g", "-F", "499"
459 };
460 std::vector<uint8_t> perf_data;
461 int32_t status;
462
463 debugd::PerfTool perf_tool;
464 if (!perf_tool.GetPerfOutput(kPerfDurationSecs, perf_args, &perf_data,
465 nullptr, &status, nullptr))
466 return;
467
468 // XZ compress the profile data.
469 std::vector<uint8_t> perf_data_xz;
470 if (!CompressXzBuffer(perf_data, &perf_data_xz))
471 return;
472
473 // Base64 encode the compressed data.
474 std::string perf_data_str(reinterpret_cast<const char*>(perf_data_xz.data()),
475 perf_data_xz.size());
476 (*map)["perf-data"] =
Chinglin Yu3c8d0a22019-02-20 11:32:52 +0800477 std::string(kPerfDataDescription) +
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800478 LogTool::EnsureUTF8String(perf_data_str, LogTool::Encoding::kBinary);
479}
480
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800481} // namespace
482
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700483Log::Log(Log::LogType type,
484 std::string name,
485 std::string data,
486 std::string user,
487 std::string group,
488 int64_t max_bytes,
489 LogTool::Encoding encoding)
490 : type_(type),
491 name_(name),
492 data_(data),
493 user_(user),
494 group_(group),
495 max_bytes_(max_bytes),
496 encoding_(encoding) {}
497
498std::string Log::GetName() const {
499 return name_;
500}
501
502std::string Log::GetLogData() const {
503 // The reason this code uses a switch statement on a type enum rather than
504 // using inheritance/virtual dispatch is so that all of the Log objects can
505 // be constructed statically. Switching to heap allocated subclasses of Log
506 // makes the code that declares all of the log entries much more verbose
507 // and harder to understand.
508 switch (type_) {
509 case kCommand:
510 return GetCommandLogData();
511 case kFile:
512 return GetFileLogData();
513 default:
514 return "<unknown log type>";
515 }
516}
517
518// TODO(ellyjones): sandbox. crosbug.com/35122
519std::string Log::GetCommandLogData() const {
520 if (type_ != kCommand)
521 return "<log type mismatch>";
522 std::string tailed_cmdline =
523 base::StringPrintf("%s | tail -c %" PRId64, data_.c_str(), max_bytes_);
524 ProcessWithOutput p;
525 if (minijail_disabled_for_test_)
526 p.set_use_minijail(false);
527 if (!user_.empty() && !group_.empty())
528 p.SandboxAs(user_, group_);
529 if (!p.Init())
530 return "<not available>";
531 p.AddArg(kShell);
532 p.AddStringOption("-c", tailed_cmdline);
533 if (p.Run())
534 return "<not available>";
535 std::string output;
536 p.GetOutput(&output);
537 if (output.empty())
538 return "<empty>";
539 return LogTool::EnsureUTF8String(output, encoding_);
540}
541
542std::string Log::GetFileLogData() const {
543 if (type_ != kFile)
544 return "<log type mismatch>";
545
546 uid_t old_euid = geteuid();
547 uid_t new_euid = UidForUser(user_);
548 gid_t old_egid = getegid();
549 gid_t new_egid = GidForGroup(group_);
550
551 if (new_euid == -1 || new_egid == -1) {
552 return "<not available>";
553 }
554
555 // Make sure to set group first, since if we set user first we lose root
556 // and therefore the ability to set our effective gid to arbitrary gids.
557 if (setegid(new_egid)) {
558 PLOG(ERROR) << "Failed to set effective group id to " << new_egid;
559 return "<not available>";
560 }
561 if (seteuid(new_euid)) {
562 PLOG(ERROR) << "Failed to set effective user id to " << new_euid;
563 if (setegid(old_egid))
564 PLOG(ERROR) << "Failed to restore effective group id to " << old_egid;
565 return "<not available>";
566 }
567
568 std::string contents;
569 const base::FilePath path(data_);
570 // Handle special files that don't properly report length/allow lseek.
571 if (base::FilePath("/dev").IsParent(path) ||
572 base::FilePath("/proc").IsParent(path) ||
573 base::FilePath("/sys").IsParent(path)) {
574 if (!base::ReadFileToString(path, &contents))
575 contents = "<not available>";
576 if (contents.size() > max_bytes_)
577 contents.erase(0, contents.size() - max_bytes_);
578 } else {
579 base::File file(path, base::File::FLAG_OPEN | base::File::FLAG_READ);
580 if (!file.IsValid()) {
581 contents = "<not available>";
582 } else {
583 int64_t length = file.GetLength();
584 if (length > max_bytes_) {
585 file.Seek(base::File::FROM_END, -max_bytes_);
586 length = max_bytes_;
587 }
588 std::vector<char> buf(length);
589 int read = file.ReadAtCurrentPos(buf.data(), buf.size());
590 if (read < 0) {
591 PLOG(ERROR) << "Could not read from file " << path.value();
592 } else {
593 contents = std::string(buf.begin(), buf.begin() + read);
594 }
595 }
596 }
597
598 if (contents.empty())
599 contents = "<empty>";
600
601 // Make sure we restore our old euid/egid before returning.
602 if (seteuid(old_euid))
603 PLOG(ERROR) << "Failed to restore effective user id to " << old_euid;
604
605 if (setegid(old_egid))
606 PLOG(ERROR) << "Failed to restore effective group id to " << old_egid;
607
608 return LogTool::EnsureUTF8String(contents, encoding_);
609}
610
611void Log::DisableMinijailForTest() {
612 minijail_disabled_for_test_ = true;
613}
614
615// static
616uid_t Log::UidForUser(const std::string& user) {
617 struct passwd entry;
618 struct passwd* result;
619 std::vector<char> buf(1024);
620 getpwnam_r(user.c_str(), &entry, &buf[0], buf.size(), &result);
621 if (!result) {
622 LOG(ERROR) << "User not found: " << user;
623 return -1;
624 }
625 return entry.pw_uid;
626}
627
628// static
629gid_t Log::GidForGroup(const std::string& group) {
630 struct group entry;
631 struct group* result;
632 std::vector<char> buf(1024);
633 getgrnam_r(group.c_str(), &entry, &buf[0], buf.size(), &result);
634 if (!result) {
635 LOG(ERROR) << "Group not found: " << group;
636 return -1;
637 }
638 return entry.gr_gid;
639}
640
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700641void LogTool::CreateConnectivityReport(bool wait_for_results) {
Rebecca Silbersteine78af402014-10-02 10:55:04 -0700642 // Perform ConnectivityTrial to report connection state in feedback log.
Ben Chan8e9f6d02017-09-26 23:04:21 -0700643 auto shill = std::make_unique<org::chromium::flimflam::ManagerProxy>(bus_);
Rebecca Silbersteine78af402014-10-02 10:55:04 -0700644 // Give the connection trial time to test the connection and log the results
645 // before collecting the logs for feedback.
646 // TODO(silberst): Replace the simple approach of a single timeout with a more
647 // coordinated effort.
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700648 if (shill && shill->CreateConnectivityReport(nullptr) && wait_for_results)
Eric Carusocc7106c2017-04-27 14:22:42 -0700649 sleep(kConnectionTesterTimeoutSeconds);
Rebecca Silbersteine78af402014-10-02 10:55:04 -0700650}
651
Eric Carusoc93a15c2017-04-24 16:15:12 -0700652string LogTool::GetLog(const string& name) {
Elly Jones533c7c42012-08-10 15:07:05 -0400653 string result;
Ben Chancf7d6412017-08-10 22:30:09 -0700654 GetNamedLogFrom(name, kCommandLogs, &result)
655 || GetNamedLogFrom(name, kExtraLogs, &result)
656 || GetNamedLogFrom(name, kFeedbackLogs, &result);
Elly Jones533c7c42012-08-10 15:07:05 -0400657 return result;
658}
659
Eric Carusof9091f82017-04-28 14:18:59 -0700660LogTool::LogMap LogTool::GetAllLogs() {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700661 CreateConnectivityReport(false);
Elly Jones533c7c42012-08-10 15:07:05 -0400662 LogMap result;
Ben Chancf7d6412017-08-10 22:30:09 -0700663 GetLogsFrom(kCommandLogs, &result);
664 GetLogsFrom(kExtraLogs, &result);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600665 GetLsbReleaseInfo(&result);
666 GetOsReleaseInfo(&result);
Elly Jones533c7c42012-08-10 15:07:05 -0400667 return result;
668}
669
Brian Norrisca4fc042018-04-03 00:24:26 -0700670LogTool::LogMap LogTool::GetAllDebugLogs() {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700671 CreateConnectivityReport(true);
Brian Norrisca4fc042018-04-03 00:24:26 -0700672 LogMap result;
673 GetLogsFrom(kCommandLogs, &result);
674 GetLogsFrom(kExtraLogs, &result);
675 GetLogsFrom(kBigFeedbackLogs, &result);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600676 GetLsbReleaseInfo(&result);
677 GetOsReleaseInfo(&result);
Brian Norrisca4fc042018-04-03 00:24:26 -0700678 return result;
679}
680
Eric Carusof9091f82017-04-28 14:18:59 -0700681LogTool::LogMap LogTool::GetFeedbackLogs() {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700682 CreateConnectivityReport(true);
Elly Jones533c7c42012-08-10 15:07:05 -0400683 LogMap result;
Ben Chancf7d6412017-08-10 22:30:09 -0700684 GetLogsFrom(kCommandLogs, &result);
Kevin Cernekee143e2af2018-03-20 13:28:20 -0700685 for (const auto& key : kCommandLogsExclude) {
686 result.erase(key);
687 }
Ben Chancf7d6412017-08-10 22:30:09 -0700688 GetLogsFrom(kFeedbackLogs, &result);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600689 GetLsbReleaseInfo(&result);
690 GetOsReleaseInfo(&result);
Darin Petkovce9b3a12013-01-10 16:38:54 +0100691 AnonymizeLogMap(&result);
Elly Jones03cd6d72012-06-11 13:04:28 -0400692 return result;
693}
694
Eric Caruso0b241882018-04-04 13:43:46 -0700695void LogTool::GetBigFeedbackLogs(const base::ScopedFD& fd) {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700696 CreateConnectivityReport(true);
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800697 LogMap map;
698 GetPerfData(&map);
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800699 base::DictionaryValue dictionary;
Ben Chancf7d6412017-08-10 22:30:09 -0700700 GetLogsInDictionary(kCommandLogs, &anonymizer_, &dictionary);
Kevin Cernekee143e2af2018-03-20 13:28:20 -0700701 for (const auto& key : kCommandLogsExclude) {
702 dictionary.Remove(key, nullptr);
703 }
Ben Chancf7d6412017-08-10 22:30:09 -0700704 GetLogsInDictionary(kFeedbackLogs, &anonymizer_, &dictionary);
705 GetLogsInDictionary(kBigFeedbackLogs, &anonymizer_, &dictionary);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600706 GetLsbReleaseInfo(&map);
707 GetOsReleaseInfo(&map);
708 PopulateDictionaryValue(map, &dictionary);
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800709 SerializeLogsAsJSON(dictionary, fd);
710}
711
Eric Carusoc93a15c2017-04-24 16:15:12 -0700712LogTool::LogMap LogTool::GetUserLogFiles() {
Gaurav Shahf6c8f2a2012-10-11 17:22:43 -0700713 LogMap result;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700714 for (const UserLog& ul : kUserLogs)
715 result[ul.first] = ul.second;
Gaurav Shahf6c8f2a2012-10-11 17:22:43 -0700716 return result;
717}
718
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -0700719// static
720string LogTool::EnsureUTF8String(const string& value,
721 LogTool::Encoding source_encoding) {
722 if (source_encoding == LogTool::Encoding::kAutodetect) {
723 if (base::IsStringUTF8(value))
724 return value;
725 source_encoding = LogTool::Encoding::kBinary;
726 }
727
728 if (source_encoding == LogTool::Encoding::kUtf8) {
729 string output;
730 const char* src = value.data();
731 int32_t src_len = static_cast<int32_t>(value.length());
732
733 output.reserve(value.size());
734 for (int32_t char_index = 0; char_index < src_len; char_index++) {
735 uint32_t code_point;
736 if (!base::ReadUnicodeCharacter(src, src_len, &char_index, &code_point) ||
737 !base::IsValidCharacter(code_point)) {
738 // Replace invalid characters with U+FFFD REPLACEMENT CHARACTER.
739 code_point = 0xFFFD;
740 }
741 base::WriteUnicodeCharacter(code_point, &output);
742 }
743 return output;
744 } else {
745 string encoded_value;
746 base::Base64Encode(value, &encoded_value);
747 return "<base64>: " + encoded_value;
748 }
749}
750
Darin Petkovce9b3a12013-01-10 16:38:54 +0100751void LogTool::AnonymizeLogMap(LogMap* log_map) {
Ben Chane2fa3572017-02-08 22:46:18 -0800752 for (auto& entry : *log_map)
753 entry.second = anonymizer_.Anonymize(entry.second);
Darin Petkovce9b3a12013-01-10 16:38:54 +0100754}
755
Ben Chana0011d82014-05-13 00:19:29 -0700756} // namespace debugd