1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define TRACE_TAG ADB
18
19 #include "sysdeps.h"
20
21 #include "bugreport.h"
22
23 #include <string>
24 #include <vector>
25
26 #include <android-base/file.h>
27 #include <android-base/strings.h>
28
29 #include "adb_client.h"
30 #include "adb_utils.h"
31 #include "client/file_sync_client.h"
32
33 static constexpr char BUGZ_BEGIN_PREFIX[] = "BEGIN:";
34 static constexpr char BUGZ_PROGRESS_PREFIX[] = "PROGRESS:";
35 static constexpr char BUGZ_PROGRESS_SEPARATOR[] = "/";
36 static constexpr char BUGZ_OK_PREFIX[] = "OK:";
37 static constexpr char BUGZ_FAIL_PREFIX[] = "FAIL:";
38
39 // Custom callback used to handle the output of zipped bugreports.
40 class BugreportStandardStreamsCallback : public StandardStreamsCallbackInterface {
41 public:
BugreportStandardStreamsCallback(const std::string & dest_dir,const std::string & dest_file,bool show_progress,Bugreport * br)42 BugreportStandardStreamsCallback(const std::string& dest_dir, const std::string& dest_file,
43 bool show_progress, Bugreport* br)
44 : br_(br),
45 src_file_(),
46 dest_dir_(dest_dir),
47 dest_file_(dest_file),
48 line_message_(),
49 invalid_lines_(),
50 show_progress_(show_progress),
51 status_(0),
52 line_(),
53 last_progress_percentage_(0) {
54 SetLineMessage("generating");
55 }
56
OnStdout(const char * buffer,size_t length)57 bool OnStdout(const char* buffer, size_t length) {
58 for (size_t i = 0; i < length; i++) {
59 char c = buffer[i];
60 if (c == '\n') {
61 ProcessLine(line_);
62 line_.clear();
63 } else {
64 line_.append(1, c);
65 }
66 }
67 return true;
68 }
69
OnStderr(const char * buffer,size_t length)70 bool OnStderr(const char* buffer, size_t length) {
71 return OnStream(nullptr, stderr, buffer, length, false);
72 }
73
Done(int unused_)74 int Done(int unused_) {
75 // Process remaining line, if any.
76 ProcessLine(line_);
77
78 // Warn about invalid lines, if any.
79 if (!invalid_lines_.empty()) {
80 fprintf(stderr,
81 "WARNING: bugreportz generated %zu line(s) with unknown commands, "
82 "device might not support zipped bugreports:\n",
83 invalid_lines_.size());
84 for (const auto& line : invalid_lines_) {
85 fprintf(stderr, "\t%s\n", line.c_str());
86 }
87 fprintf(stderr,
88 "If the zipped bugreport was not generated, try 'adb bugreport' instead.\n");
89 }
90
91 // Pull the generated bug report.
92 if (status_ == 0) {
93 if (src_file_.empty()) {
94 fprintf(stderr, "bugreportz did not return a '%s' or '%s' line\n", BUGZ_OK_PREFIX,
95 BUGZ_FAIL_PREFIX);
96 return -1;
97 }
98 std::string destination;
99 if (dest_dir_.empty()) {
100 destination = dest_file_;
101 } else {
102 destination = android::base::StringPrintf("%s%c%s", dest_dir_.c_str(),
103 OS_PATH_SEPARATOR, dest_file_.c_str());
104 }
105 std::vector<const char*> srcs{src_file_.c_str()};
106 SetLineMessage("pulling");
107 status_ =
108 br_->DoSyncPull(srcs, destination.c_str(), false, line_message_.c_str()) ? 0 : 1;
109 if (status_ == 0) {
110 printf("Bug report copied to %s\n", destination.c_str());
111 } else {
112 fprintf(stderr,
113 "Bug report finished but could not be copied to '%s'.\n"
114 "Try to run 'adb pull %s <directory>'\n"
115 "to copy it to a directory that can be written.\n",
116 destination.c_str(), src_file_.c_str());
117 }
118 }
119 return status_;
120 }
121
122 private:
SetLineMessage(const std::string & action)123 void SetLineMessage(const std::string& action) {
124 line_message_ = action + " " + android::base::Basename(dest_file_);
125 }
126
SetSrcFile(const std::string path)127 void SetSrcFile(const std::string path) {
128 src_file_ = path;
129 if (!dest_dir_.empty()) {
130 // Only uses device-provided name when user passed a directory.
131 dest_file_ = android::base::Basename(path);
132 SetLineMessage("generating");
133 }
134 }
135
ProcessLine(const std::string & line)136 void ProcessLine(const std::string& line) {
137 if (line.empty()) return;
138
139 if (android::base::StartsWith(line, BUGZ_BEGIN_PREFIX)) {
140 SetSrcFile(&line[strlen(BUGZ_BEGIN_PREFIX)]);
141 } else if (android::base::StartsWith(line, BUGZ_OK_PREFIX)) {
142 SetSrcFile(&line[strlen(BUGZ_OK_PREFIX)]);
143 } else if (android::base::StartsWith(line, BUGZ_FAIL_PREFIX)) {
144 const char* error_message = &line[strlen(BUGZ_FAIL_PREFIX)];
145 fprintf(stderr, "adb: device failed to take a zipped bugreport: %s\n", error_message);
146 status_ = -1;
147 } else if (show_progress_ && android::base::StartsWith(line, BUGZ_PROGRESS_PREFIX)) {
148 // progress_line should have the following format:
149 //
150 // BUGZ_PROGRESS_PREFIX:PROGRESS/TOTAL
151 //
152 size_t idx1 = line.rfind(BUGZ_PROGRESS_PREFIX) + strlen(BUGZ_PROGRESS_PREFIX);
153 size_t idx2 = line.rfind(BUGZ_PROGRESS_SEPARATOR);
154 int progress = std::stoi(line.substr(idx1, (idx2 - idx1)));
155 int total = std::stoi(line.substr(idx2 + 1));
156 int progress_percentage = (progress * 100 / total);
157 if (progress_percentage != 0 && progress_percentage <= last_progress_percentage_) {
158 // Ignore.
159 return;
160 }
161 last_progress_percentage_ = progress_percentage;
162 br_->UpdateProgress(line_message_, progress_percentage);
163 } else {
164 invalid_lines_.push_back(line);
165 }
166 }
167
168 Bugreport* br_;
169
170 // Path of bugreport on device.
171 std::string src_file_;
172
173 // Bugreport destination on host, depending on argument passed on constructor:
174 // - if argument is a directory, dest_dir_ is set with it and dest_file_ will be the name
175 // of the bugreport reported by the device.
176 // - if argument is empty, dest_dir is set as the current directory and dest_file_ will be the
177 // name of the bugreport reported by the device.
178 // - otherwise, dest_dir_ is not set and dest_file_ is set with the value passed on constructor.
179 std::string dest_dir_, dest_file_;
180
181 // Message displayed on LinePrinter, it's updated every time the destination above change.
182 std::string line_message_;
183
184 // Lines sent by bugreportz that contain invalid commands; will be displayed at the end.
185 std::vector<std::string> invalid_lines_;
186
187 // Whether PROGRESS_LINES should be interpreted as progress.
188 bool show_progress_;
189
190 // Overall process of the operation, as returned by Done().
191 int status_;
192
193 // Temporary buffer containing the characters read since the last newline (\n).
194 std::string line_;
195
196 // Last displayed progress.
197 // Since dumpstate progress can recede, only forward progress should be displayed
198 int last_progress_percentage_;
199
200 DISALLOW_COPY_AND_ASSIGN(BugreportStandardStreamsCallback);
201 };
202
DoIt(int argc,const char ** argv)203 int Bugreport::DoIt(int argc, const char** argv) {
204 if (argc > 2) error_exit("usage: adb bugreport [[PATH] | [--stream]]");
205
206 // Gets bugreportz version.
207 std::string bugz_stdout, bugz_stderr;
208 DefaultStandardStreamsCallback version_callback(&bugz_stdout, &bugz_stderr);
209 int status = SendShellCommand("bugreportz -v", false, &version_callback);
210 std::string bugz_version = android::base::Trim(bugz_stderr);
211 std::string bugz_output = android::base::Trim(bugz_stdout);
212 int bugz_ver_major = 0, bugz_ver_minor = 0;
213
214 if (status != 0 || bugz_version.empty()) {
215 D("'bugreportz' -v results: status=%d, stdout='%s', stderr='%s'", status,
216 bugz_output.c_str(), bugz_version.c_str());
217 if (argc == 1) {
218 // Device does not support bugreportz: if called as 'adb bugreport', just falls out to
219 // the flat-file version.
220 fprintf(stderr,
221 "Failed to get bugreportz version, which is only available on devices "
222 "running Android 7.0 or later.\nTrying a plain-text bug report instead.\n");
223 return SendShellCommand("bugreport", false);
224 }
225
226 // But if user explicitly asked for a zipped bug report, fails instead (otherwise calling
227 // 'bugreport' would generate a lot of output the user might not be prepared to handle).
228 fprintf(stderr,
229 "Failed to get bugreportz version: 'bugreportz -v' returned '%s' (code %d).\n"
230 "If the device does not run Android 7.0 or above, try this instead:\n"
231 "\tadb bugreport > bugreport.txt\n",
232 bugz_output.c_str(), status);
233 return status != 0 ? status : -1;
234 }
235 std::sscanf(bugz_version.c_str(), "%d.%d", &bugz_ver_major, &bugz_ver_minor);
236
237 std::string dest_file, dest_dir;
238
239 if (argc == 1) {
240 // No args - use current directory
241 if (!getcwd(&dest_dir)) {
242 perror("adb: getcwd failed");
243 return 1;
244 }
245 } else if (!strcmp(argv[1], "--stream")) {
246 if (bugz_ver_major == 1 && bugz_ver_minor < 2) {
247 fprintf(stderr,
248 "Failed to stream bugreport: bugreportz does not support stream.\n");
249 } else {
250 return SendShellCommand("bugreportz -s", false);
251 }
252 } else {
253 // Check whether argument is a directory or file
254 if (directory_exists(argv[1])) {
255 dest_dir = argv[1];
256 } else {
257 dest_file = argv[1];
258 }
259 }
260
261 if (dest_file.empty()) {
262 // Uses a default value until device provides the proper name
263 dest_file = "bugreport.zip";
264 } else {
265 if (!android::base::EndsWithIgnoreCase(dest_file, ".zip")) {
266 dest_file += ".zip";
267 }
268 }
269
270 bool show_progress = true;
271 std::string bugz_command = "bugreportz -p";
272 if (bugz_version == "1.0") {
273 // 1.0 does not support progress notifications, so print a disclaimer
274 // message instead.
275 fprintf(stderr,
276 "Bugreport is in progress and it could take minutes to complete.\n"
277 "Please be patient and do not cancel or disconnect your device "
278 "until it completes.\n");
279 show_progress = false;
280 bugz_command = "bugreportz";
281 }
282 BugreportStandardStreamsCallback bugz_callback(dest_dir, dest_file, show_progress, this);
283 return SendShellCommand(bugz_command, false, &bugz_callback);
284 }
285
UpdateProgress(const std::string & message,int progress_percentage)286 void Bugreport::UpdateProgress(const std::string& message, int progress_percentage) {
287 line_printer_.Print(
288 android::base::StringPrintf("[%3d%%] %s", progress_percentage, message.c_str()),
289 LinePrinter::INFO);
290 }
291
SendShellCommand(const std::string & command,bool disable_shell_protocol,StandardStreamsCallbackInterface * callback)292 int Bugreport::SendShellCommand(const std::string& command, bool disable_shell_protocol,
293 StandardStreamsCallbackInterface* callback) {
294 return send_shell_command(command, disable_shell_protocol, callback);
295 }
296
DoSyncPull(const std::vector<const char * > & srcs,const char * dst,bool copy_attrs,const char * name)297 bool Bugreport::DoSyncPull(const std::vector<const char*>& srcs, const char* dst, bool copy_attrs,
298 const char* name) {
299 return do_sync_pull(srcs, dst, copy_attrs, CompressionType::None, name);
300 }
301