blob: 6fa368d0560aeeebf09d8ac381c51046d6002ced [file] [log] [blame]
Chris Sosae4a86032010-06-16 17:08:34 -07001// Copyright (c) 2010 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
Ken Mixter03403162010-08-18 15:23:16 -07005#include "crash-reporter/user_collector.h"
6
Ken Mixter777484c2010-07-23 16:22:44 -07007#include <grp.h> // For struct group.
8#include <pwd.h> // For struct passwd.
Ken Mixter2953c3a2010-10-18 14:42:20 -07009#include <sys/types.h> // For getpwuid_r, getgrnam_r, WEXITSTATUS.
Ken Mixter777484c2010-07-23 16:22:44 -070010
Chris Sosae4a86032010-06-16 17:08:34 -070011#include <string>
Ken Mixter2953c3a2010-10-18 14:42:20 -070012#include <vector>
Chris Sosae4a86032010-06-16 17:08:34 -070013
14#include "base/file_util.h"
15#include "base/logging.h"
16#include "base/string_util.h"
Ken Mixter03403162010-08-18 15:23:16 -070017#include "crash-reporter/system_logging.h"
Ken Mixter207694d2010-10-28 15:42:37 -070018#include "gflags/gflags.h"
Chris Sosae4a86032010-06-16 17:08:34 -070019
Ken Mixterc6a58e02010-11-01 18:05:30 -070020#pragma GCC diagnostic ignored "-Wstrict-aliasing"
Ken Mixter207694d2010-10-28 15:42:37 -070021DEFINE_bool(core2md_failure_test, false, "Core2md failure test");
22DEFINE_bool(directory_failure_test, false, "Spool directory failure test");
Ken Mixterc6a58e02010-11-01 18:05:30 -070023DEFINE_string(filter_in, "",
24 "Ignore all crashes but this for testing");
25#pragma GCC diagnostic error "-Wstrict-aliasing"
Ken Mixter207694d2010-10-28 15:42:37 -070026
27static const char kCollectionErrorSignature[] =
28 "crash_reporter-user-collection";
Chris Sosae4a86032010-06-16 17:08:34 -070029// This procfs file is used to cause kernel core file writing to
30// instead pipe the core file into a user space process. See
31// core(5) man page.
32static const char kCorePatternFile[] = "/proc/sys/kernel/core_pattern";
Ken Mixter777484c2010-07-23 16:22:44 -070033static const char kCoreToMinidumpConverterPath[] = "/usr/bin/core2md";
Ken Mixter7ac7a702010-08-13 15:43:34 -070034static const char kLeaveCoreFile[] = "/root/.leave_core";
Ken Mixter777484c2010-07-23 16:22:44 -070035
36const char *UserCollector::kUserId = "Uid:\t";
37const char *UserCollector::kGroupId = "Gid:\t";
Chris Sosae4a86032010-06-16 17:08:34 -070038
39UserCollector::UserCollector()
Ken Mixter777484c2010-07-23 16:22:44 -070040 : generate_diagnostics_(false),
41 core_pattern_file_(kCorePatternFile),
Ken Mixter03403162010-08-18 15:23:16 -070042 initialized_(false) {
Chris Sosae4a86032010-06-16 17:08:34 -070043}
44
45void UserCollector::Initialize(
46 UserCollector::CountCrashFunction count_crash_function,
47 const std::string &our_path,
48 UserCollector::IsFeedbackAllowedFunction is_feedback_allowed_function,
Ken Mixter777484c2010-07-23 16:22:44 -070049 SystemLogging *logger,
50 bool generate_diagnostics) {
Ken Mixter03403162010-08-18 15:23:16 -070051 CrashCollector::Initialize(count_crash_function,
52 is_feedback_allowed_function,
53 logger);
Chris Sosae4a86032010-06-16 17:08:34 -070054 our_path_ = our_path;
Chris Sosae4a86032010-06-16 17:08:34 -070055 initialized_ = true;
Ken Mixter777484c2010-07-23 16:22:44 -070056 generate_diagnostics_ = generate_diagnostics;
Chris Sosae4a86032010-06-16 17:08:34 -070057}
58
59UserCollector::~UserCollector() {
60}
61
62std::string UserCollector::GetPattern(bool enabled) const {
63 if (enabled) {
Ken Mixter777484c2010-07-23 16:22:44 -070064 return StringPrintf("|%s --signal=%%s --pid=%%p", our_path_.c_str());
Chris Sosae4a86032010-06-16 17:08:34 -070065 } else {
66 return "core";
67 }
68}
69
70bool UserCollector::SetUpInternal(bool enabled) {
71 CHECK(initialized_);
Ken Mixter03403162010-08-18 15:23:16 -070072 logger_->LogInfo("%s user crash handling",
73 enabled ? "Enabling" : "Disabling");
Chris Sosae4a86032010-06-16 17:08:34 -070074 std::string pattern = GetPattern(enabled);
75 if (file_util::WriteFile(FilePath(core_pattern_file_),
76 pattern.c_str(),
77 pattern.length()) !=
78 static_cast<int>(pattern.length())) {
79 logger_->LogError("Unable to write %s", core_pattern_file_.c_str());
80 return false;
81 }
82 return true;
83}
84
Ken Mixter777484c2010-07-23 16:22:44 -070085FilePath UserCollector::GetProcessPath(pid_t pid) {
86 return FilePath(StringPrintf("/proc/%d", pid));
87}
88
89bool UserCollector::GetSymlinkTarget(const FilePath &symlink,
90 FilePath *target) {
91 int max_size = 32;
92 scoped_array<char> buffer;
93 while (true) {
94 buffer.reset(new char[max_size + 1]);
95 ssize_t size = readlink(symlink.value().c_str(), buffer.get(), max_size);
96 if (size < 0) {
97 return false;
98 }
99 buffer[size] = 0;
100 if (size == max_size) {
101 // Avoid overflow when doubling.
102 if (max_size * 2 > max_size) {
103 max_size *= 2;
104 continue;
105 } else {
106 return false;
107 }
108 }
109 break;
110 }
111
112 *target = FilePath(buffer.get());
113 return true;
114}
115
116bool UserCollector::GetExecutableBaseNameFromPid(uid_t pid,
117 std::string *base_name) {
118 FilePath target;
119 if (!GetSymlinkTarget(GetProcessPath(pid).Append("exe"), &target))
120 return false;
121 *base_name = target.BaseName().value();
122 return true;
123}
124
125bool UserCollector::GetIdFromStatus(const char *prefix,
126 IdKind kind,
127 const std::string &status_contents,
128 int *id) {
129 // From fs/proc/array.c:task_state(), this file contains:
130 // \nUid:\t<uid>\t<euid>\t<suid>\t<fsuid>\n
131 std::vector<std::string> status_lines;
132 SplitString(status_contents, '\n', &status_lines);
133 std::vector<std::string>::iterator line_iterator;
134 for (line_iterator = status_lines.begin();
135 line_iterator != status_lines.end();
136 ++line_iterator) {
137 if (line_iterator->find(prefix) == 0)
138 break;
139 }
140 if (line_iterator == status_lines.end()) {
141 return false;
142 }
143 std::string id_substring = line_iterator->substr(strlen(prefix),
144 std::string::npos);
145 std::vector<std::string> ids;
146 SplitString(id_substring, '\t', &ids);
147 if (ids.size() != kIdMax || kind < 0 || kind >= kIdMax) {
148 return false;
149 }
150 const char *number = ids[kind].c_str();
151 char *end_number = NULL;
152 *id = strtol(number, &end_number, 10);
153 if (*end_number != '\0')
154 return false;
155 return true;
156}
157
Ken Mixter207694d2010-10-28 15:42:37 -0700158void UserCollector::LogCollectionError(const std::string &error_message) {
159 error_log_.append(error_message.c_str());
160 error_log_.append("\n");
161 logger_->LogError(error_message.c_str());
162}
163
164void UserCollector::EnqueueCollectionErrorLog(pid_t pid,
165 const std::string &exec) {
166 FilePath crash_path;
167 logger_->LogInfo("Writing conversion problems as separate crash report.");
168 if (!GetCreatedCrashDirectoryByEuid(0, &crash_path, NULL)) {
169 logger_->LogError("Could not even get log directory; out of space?");
170 return;
171 }
172 std::string dump_basename = FormatDumpBasename(exec, time(NULL), pid);
173 FilePath log_path = GetCrashPath(crash_path, dump_basename, "log");
174 FilePath meta_path = GetCrashPath(crash_path, dump_basename, "meta");
Ken Mixter9b346472010-11-07 13:45:45 -0800175 // We must use WriteNewFile instead of file_util::WriteFile as we do
176 // not want to write with root access to a symlink that an attacker
177 // might have created.
178 WriteNewFile(log_path, error_log_.data(), error_log_.length());
Ken Mixter207694d2010-10-28 15:42:37 -0700179 AddCrashMetaData("sig", kCollectionErrorSignature);
180 WriteCrashMetaData(meta_path, exec, log_path.value());
181}
182
Ken Mixter777484c2010-07-23 16:22:44 -0700183bool UserCollector::CopyOffProcFiles(pid_t pid,
184 const FilePath &container_dir) {
185 if (!file_util::CreateDirectory(container_dir)) {
Ken Mixter207694d2010-10-28 15:42:37 -0700186 LogCollectionError(StringPrintf("Could not create %s",
187 container_dir.value().c_str()));
Ken Mixter777484c2010-07-23 16:22:44 -0700188 return false;
189 }
190 FilePath process_path = GetProcessPath(pid);
191 if (!file_util::PathExists(process_path)) {
Ken Mixter207694d2010-10-28 15:42:37 -0700192 LogCollectionError(StringPrintf("Path %s does not exist",
193 process_path.value().c_str()));
Ken Mixter777484c2010-07-23 16:22:44 -0700194 return false;
195 }
196 static const char *proc_files[] = {
197 "auxv",
198 "cmdline",
199 "environ",
200 "maps",
201 "status"
202 };
203 for (unsigned i = 0; i < arraysize(proc_files); ++i) {
204 if (!file_util::CopyFile(process_path.Append(proc_files[i]),
205 container_dir.Append(proc_files[i]))) {
Ken Mixter207694d2010-10-28 15:42:37 -0700206 LogCollectionError(StringPrintf("Could not copy %s file",
207 proc_files[i]));
Ken Mixter777484c2010-07-23 16:22:44 -0700208 return false;
209 }
210 }
211 return true;
212}
213
Ken Mixter777484c2010-07-23 16:22:44 -0700214bool UserCollector::GetCreatedCrashDirectory(pid_t pid,
Ken Mixter207694d2010-10-28 15:42:37 -0700215 FilePath *crash_file_path,
216 bool *out_of_capacity) {
Ken Mixter777484c2010-07-23 16:22:44 -0700217 FilePath process_path = GetProcessPath(pid);
218 std::string status;
Ken Mixter207694d2010-10-28 15:42:37 -0700219 if (FLAGS_directory_failure_test) {
220 LogCollectionError("Purposefully failing to create spool directory");
221 return false;
222 }
Ken Mixter777484c2010-07-23 16:22:44 -0700223 if (!file_util::ReadFileToString(process_path.Append("status"),
224 &status)) {
Ken Mixter207694d2010-10-28 15:42:37 -0700225 LogCollectionError("Could not read status file");
Ken Mixter777484c2010-07-23 16:22:44 -0700226 return false;
227 }
228 int process_euid;
229 if (!GetIdFromStatus(kUserId, kIdEffective, status, &process_euid)) {
Ken Mixter207694d2010-10-28 15:42:37 -0700230 LogCollectionError("Could not find euid in status file");
Ken Mixter777484c2010-07-23 16:22:44 -0700231 return false;
232 }
Ken Mixter207694d2010-10-28 15:42:37 -0700233 if (!GetCreatedCrashDirectoryByEuid(process_euid,
234 crash_file_path,
235 out_of_capacity)) {
236 LogCollectionError("Could not create crash directory");
237 return false;
238 }
239 return true;
Ken Mixter777484c2010-07-23 16:22:44 -0700240}
241
242bool UserCollector::CopyStdinToCoreFile(const FilePath &core_path) {
243 // Copy off all stdin to a core file.
244 FilePath stdin_path("/dev/fd/0");
245 if (file_util::CopyFile(stdin_path, core_path)) {
246 return true;
247 }
248
Ken Mixter207694d2010-10-28 15:42:37 -0700249 LogCollectionError("Could not write core file");
Ken Mixter777484c2010-07-23 16:22:44 -0700250 // If the file system was full, make sure we remove any remnants.
251 file_util::Delete(core_path, false);
252 return false;
253}
254
Ken Mixter207694d2010-10-28 15:42:37 -0700255bool UserCollector::RunCoreToMinidump(const FilePath &core_path,
256 const FilePath &procfs_directory,
257 const FilePath &minidump_path,
258 const FilePath &temp_directory) {
Ken Mixter777484c2010-07-23 16:22:44 -0700259 FilePath output_path = temp_directory.Append("output");
Ken Mixter2953c3a2010-10-18 14:42:20 -0700260 std::vector<const char *> core2md_arguments;
261 core2md_arguments.push_back(kCoreToMinidumpConverterPath);
262 core2md_arguments.push_back(core_path.value().c_str());
263 core2md_arguments.push_back(procfs_directory.value().c_str());
264 core2md_arguments.push_back(minidump_path.value().c_str());
265
Ken Mixter207694d2010-10-28 15:42:37 -0700266 if (FLAGS_core2md_failure_test) {
267 // To test how core2md errors are propagaged, cause an error
268 // by forgetting a required argument.
269 core2md_arguments.pop_back();
270 }
271
Ken Mixter2953c3a2010-10-18 14:42:20 -0700272 int errorlevel = ForkExecAndPipe(core2md_arguments,
273 output_path.value().c_str());
Ken Mixter777484c2010-07-23 16:22:44 -0700274
275 std::string output;
276 file_util::ReadFileToString(output_path, &output);
277 if (errorlevel != 0) {
Ken Mixter207694d2010-10-28 15:42:37 -0700278 LogCollectionError(StringPrintf("Problem during %s [result=%d]: %s",
279 kCoreToMinidumpConverterPath,
280 errorlevel,
281 output.c_str()));
Ken Mixter777484c2010-07-23 16:22:44 -0700282 return false;
283 }
284
285 if (!file_util::PathExists(minidump_path)) {
Ken Mixter207694d2010-10-28 15:42:37 -0700286 LogCollectionError(StringPrintf("Minidump file %s was not created",
287 minidump_path.value().c_str()));
Ken Mixter777484c2010-07-23 16:22:44 -0700288 return false;
289 }
290 return true;
291}
292
Ken Mixter207694d2010-10-28 15:42:37 -0700293bool UserCollector::ConvertCoreToMinidump(pid_t pid,
294 const FilePath &container_dir,
295 const FilePath &core_path,
296 const FilePath &minidump_path) {
Ken Mixter777484c2010-07-23 16:22:44 -0700297 if (!CopyOffProcFiles(pid, container_dir)) {
Ken Mixter777484c2010-07-23 16:22:44 -0700298 return false;
299 }
300
Ken Mixter777484c2010-07-23 16:22:44 -0700301 if (!CopyStdinToCoreFile(core_path)) {
Ken Mixter777484c2010-07-23 16:22:44 -0700302 return false;
303 }
304
Ken Mixter207694d2010-10-28 15:42:37 -0700305 bool conversion_result = RunCoreToMinidump(
306 core_path,
307 container_dir, // procfs directory
308 minidump_path,
309 container_dir); // temporary directory
Ken Mixteree849c52010-09-30 15:30:10 -0700310
Ken Mixter777484c2010-07-23 16:22:44 -0700311 if (conversion_result) {
312 logger_->LogInfo("Stored minidump to %s", minidump_path.value().c_str());
313 }
314
Ken Mixter207694d2010-10-28 15:42:37 -0700315 return conversion_result;
316}
317
318bool UserCollector::ConvertAndEnqueueCrash(int pid,
319 const std::string &exec,
320 bool *out_of_capacity) {
321 FilePath crash_path;
322 if (!GetCreatedCrashDirectory(pid, &crash_path, out_of_capacity)) {
323 LogCollectionError("Unable to find/create process-specific crash path");
324 return false;
325 }
326
327 // Directory like /tmp/crash_reporter.1234 which contains the
328 // procfs entries and other temporary files used during conversion.
329 FilePath container_dir = FilePath("/tmp").Append(
330 StringPrintf("crash_reporter.%d", pid));
331 std::string dump_basename = FormatDumpBasename(exec, time(NULL), pid);
332 FilePath core_path = GetCrashPath(crash_path, dump_basename, "core");
333 FilePath meta_path = GetCrashPath(crash_path, dump_basename, "meta");
334 FilePath minidump_path = GetCrashPath(crash_path, dump_basename, "dmp");
335
336 if (!ConvertCoreToMinidump(pid, container_dir, core_path,
337 minidump_path)) {
338 logger_->LogInfo("Leaving core file at %s due to conversion error",
339 core_path.value().c_str());
340 return false;
341 }
342
343 // Here we commit to sending this file. We must not return false
344 // after this point or we will generate a log report as well as a
345 // crash report.
346 WriteCrashMetaData(meta_path,
347 exec,
348 minidump_path.value());
349
Ken Mixter777484c2010-07-23 16:22:44 -0700350 if (!file_util::PathExists(FilePath(kLeaveCoreFile))) {
351 file_util::Delete(core_path, false);
352 } else {
Ken Mixter207694d2010-10-28 15:42:37 -0700353 logger_->LogInfo("Leaving core file at %s due to developer image",
354 core_path.value().c_str());
Ken Mixter777484c2010-07-23 16:22:44 -0700355 }
356
Ken Mixter207694d2010-10-28 15:42:37 -0700357 file_util::Delete(container_dir, true);
358 return true;
Ken Mixter777484c2010-07-23 16:22:44 -0700359}
360
361bool UserCollector::HandleCrash(int signal, int pid, const char *force_exec) {
Chris Sosae4a86032010-06-16 17:08:34 -0700362 CHECK(initialized_);
Ken Mixter777484c2010-07-23 16:22:44 -0700363 std::string exec;
364 if (force_exec) {
365 exec.assign(force_exec);
366 } else if (!GetExecutableBaseNameFromPid(pid, &exec)) {
367 // If for some reason we don't have the base name, avoid completely
368 // failing by indicating an unknown name.
369 exec = "unknown";
370 }
Ken Mixterc6a58e02010-11-01 18:05:30 -0700371
372 // Allow us to test the crash reporting mechanism successfully even if
373 // other parts of the system crash.
374 if (!FLAGS_filter_in.empty() &&
375 (FLAGS_filter_in == "none" ||
376 FLAGS_filter_in != exec)) {
377 // We use a different format message to make it more obvious in tests
378 // which crashes are test generated and which are real.
379 logger_->LogWarning("Ignoring crash from %s[%d] while filter_in=%s",
380 exec.c_str(), pid, FLAGS_filter_in.c_str());
381 return true;
382 }
383
Ken Mixteree849c52010-09-30 15:30:10 -0700384 bool feedback = is_feedback_allowed_function_();
385 logger_->LogWarning("Received crash notification for %s[%d] sig %d (%s)",
386 exec.c_str(), pid, signal,
Ken Mixter207694d2010-10-28 15:42:37 -0700387 feedback ? "handling" : "ignoring - no consent");
Chris Sosae4a86032010-06-16 17:08:34 -0700388
Ken Mixteree849c52010-09-30 15:30:10 -0700389 if (feedback) {
Chris Sosae4a86032010-06-16 17:08:34 -0700390 count_crash_function_();
Ken Mixter777484c2010-07-23 16:22:44 -0700391
Ken Mixter03403162010-08-18 15:23:16 -0700392 if (generate_diagnostics_) {
Ken Mixter207694d2010-10-28 15:42:37 -0700393 bool out_of_capacity = false;
394 if (!ConvertAndEnqueueCrash(pid, exec, &out_of_capacity)) {
395 if (!out_of_capacity)
396 EnqueueCollectionErrorLog(pid, exec);
397 return false;
398 }
Ken Mixter03403162010-08-18 15:23:16 -0700399 }
Ken Mixter777484c2010-07-23 16:22:44 -0700400 }
Ken Mixter207694d2010-10-28 15:42:37 -0700401
Ken Mixter777484c2010-07-23 16:22:44 -0700402 return true;
Chris Sosae4a86032010-06-16 17:08:34 -0700403}