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