blob: 72ba6194bd2317b98e0180ae868096219f77c8b2 [file] [log] [blame]
Aaron Wisnerdb511202018-06-26 15:38:35 -05001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28#include "fastboot_driver.h"
29
30#include <errno.h>
31#include <fcntl.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <string.h>
35#include <algorithm>
36#include <chrono>
37#include <fstream>
38#include <memory>
39#include <regex>
40#include <vector>
41
42#include <android-base/file.h>
43#include <android-base/stringprintf.h>
44#include <android-base/strings.h>
45#include <android-base/unique_fd.h>
46#include <utils/FileMap.h>
47#include "fastboot_driver.h"
48#include "transport.h"
49
50namespace fastboot {
51
52/*************************** PUBLIC *******************************/
53FastBootDriver::FastBootDriver(Transport* transport, std::function<void(std::string&)> info,
54 bool no_checks)
David Anderson1d887432018-08-27 16:47:32 -070055 : transport_(transport) {
Aaron Wisnerdb511202018-06-26 15:38:35 -050056 info_cb_ = info;
57 disable_checks_ = no_checks;
58}
59
David Anderson1d887432018-08-27 16:47:32 -070060FastBootDriver::~FastBootDriver() {
David Anderson1d887432018-08-27 16:47:32 -070061}
62
Aaron Wisnerdb511202018-06-26 15:38:35 -050063RetCode FastBootDriver::Boot(std::string* response, std::vector<std::string>* info) {
64 return RawCommand(Commands::BOOT, response, info);
65}
66
67RetCode FastBootDriver::Continue(std::string* response, std::vector<std::string>* info) {
68 return RawCommand(Commands::CONTINUE, response, info);
69}
70
71RetCode FastBootDriver::Erase(const std::string& part, std::string* response,
72 std::vector<std::string>* info) {
73 return RawCommand(Commands::ERASE + part, response, info);
74}
75
76RetCode FastBootDriver::Flash(const std::string& part, std::string* response,
77 std::vector<std::string>* info) {
78 return RawCommand(Commands::FLASH + part, response, info);
79}
80
81RetCode FastBootDriver::GetVar(const std::string& key, std::string* val,
82 std::vector<std::string>* info) {
83 return RawCommand(Commands::GET_VAR + key, val, info);
84}
85
86RetCode FastBootDriver::GetVarAll(std::vector<std::string>* response) {
87 std::string tmp;
88 return GetVar("all", &tmp, response);
89}
90
Aaron Wisnerdb511202018-06-26 15:38:35 -050091RetCode FastBootDriver::Reboot(std::string* response, std::vector<std::string>* info) {
92 return RawCommand(Commands::REBOOT, response, info);
93}
94
David Anderson1d887432018-08-27 16:47:32 -070095RetCode FastBootDriver::RebootTo(std::string target, std::string* response,
96 std::vector<std::string>* info) {
97 return RawCommand("reboot-" + target, response, info);
98}
99
Tom Cherry11f12092018-08-29 21:36:28 -0700100RetCode FastBootDriver::SetActive(const std::string& slot, std::string* response,
Aaron Wisnerdb511202018-06-26 15:38:35 -0500101 std::vector<std::string>* info) {
Tom Cherry11f12092018-08-29 21:36:28 -0700102 return RawCommand(Commands::SET_ACTIVE + slot, response, info);
Aaron Wisnerdb511202018-06-26 15:38:35 -0500103}
104
Aaron Wisnerdb511202018-06-26 15:38:35 -0500105RetCode FastBootDriver::FlashPartition(const std::string& part, const std::vector<char>& data) {
106 RetCode ret;
107 if ((ret = Download(data))) {
108 return ret;
109 }
110 return RawCommand(Commands::FLASH + part);
111}
112
113RetCode FastBootDriver::FlashPartition(const std::string& part, int fd, uint32_t sz) {
114 RetCode ret;
115 if ((ret = Download(fd, sz))) {
116 return ret;
117 }
118 return RawCommand(Commands::FLASH + part);
119}
120
121RetCode FastBootDriver::FlashPartition(const std::string& part, sparse_file* s) {
122 RetCode ret;
123 if ((ret = Download(s))) {
124 return ret;
125 }
126 return RawCommand(Commands::FLASH + part);
127}
128
David Anderson6c30f6e2018-09-04 15:57:39 -0700129RetCode FastBootDriver::Partitions(std::vector<std::tuple<std::string, uint64_t>>* parts) {
Aaron Wisnerdb511202018-06-26 15:38:35 -0500130 std::vector<std::string> all;
131 RetCode ret;
132 if ((ret = GetVarAll(&all))) {
133 return ret;
134 }
135
Aaron Wisnerc771ae02018-08-01 12:57:20 -0500136 std::regex reg("partition-size[[:s:]]*:[[:s:]]*([[:w:]]+)[[:s:]]*:[[:s:]]*0x([[:xdigit:]]+)");
Aaron Wisnerdb511202018-06-26 15:38:35 -0500137 std::smatch sm;
138
139 for (auto& s : all) {
140 if (std::regex_match(s, sm, reg)) {
141 std::string m1(sm[1]);
142 std::string m2(sm[2]);
David Anderson6c30f6e2018-09-04 15:57:39 -0700143 uint64_t tmp = strtoll(m2.c_str(), 0, 16);
Aaron Wisnerdb511202018-06-26 15:38:35 -0500144 parts->push_back(std::make_tuple(m1, tmp));
145 }
146 }
147 return SUCCESS;
148}
149
Aaron Wisnerdb511202018-06-26 15:38:35 -0500150RetCode FastBootDriver::Download(int fd, size_t size, std::string* response,
151 std::vector<std::string>* info) {
152 RetCode ret;
153
154 if ((size <= 0 || size > MAX_DOWNLOAD_SIZE) && !disable_checks_) {
155 error_ = "File is too large to download";
156 return BAD_ARG;
157 }
158
159 uint32_t u32size = static_cast<uint32_t>(size);
160 if ((ret = DownloadCommand(u32size, response, info))) {
161 return ret;
162 }
163
164 // Write the buffer
165 if ((ret = SendBuffer(fd, size))) {
166 return ret;
167 }
168
169 // Wait for response
170 return HandleResponse(response, info);
171}
172
173RetCode FastBootDriver::Download(const std::vector<char>& buf, std::string* response,
174 std::vector<std::string>* info) {
Aaron Wisnerdb511202018-06-26 15:38:35 -0500175 RetCode ret;
176 error_ = "";
Tom Cherrydfd85df2018-09-20 14:45:05 -0700177 if ((buf.size() == 0 || buf.size() > MAX_DOWNLOAD_SIZE) && !disable_checks_) {
Aaron Wisnerdb511202018-06-26 15:38:35 -0500178 error_ = "Buffer is too large or 0 bytes";
179 return BAD_ARG;
180 }
181
Tom Cherrydfd85df2018-09-20 14:45:05 -0700182 if ((ret = DownloadCommand(buf.size(), response, info))) {
Aaron Wisnerdb511202018-06-26 15:38:35 -0500183 return ret;
184 }
185
186 // Write the buffer
Tom Cherrydfd85df2018-09-20 14:45:05 -0700187 if ((ret = SendBuffer(buf))) {
Aaron Wisnerdb511202018-06-26 15:38:35 -0500188 return ret;
189 }
190
191 // Wait for response
192 return HandleResponse(response, info);
193}
194
Aaron Wisner9812b582018-08-22 11:01:04 -0500195RetCode FastBootDriver::Download(sparse_file* s, bool use_crc, std::string* response,
Aaron Wisnerdb511202018-06-26 15:38:35 -0500196 std::vector<std::string>* info) {
197 error_ = "";
Aaron Wisner9812b582018-08-22 11:01:04 -0500198 int64_t size = sparse_file_len(s, true, use_crc);
Aaron Wisnerdb511202018-06-26 15:38:35 -0500199 if (size <= 0 || size > MAX_DOWNLOAD_SIZE) {
200 error_ = "Sparse file is too large or invalid";
201 return BAD_ARG;
202 }
203
204 RetCode ret;
205 uint32_t u32size = static_cast<uint32_t>(size);
206 if ((ret = DownloadCommand(u32size, response, info))) {
207 return ret;
208 }
209
210 struct SparseCBPrivate {
211 FastBootDriver* self;
212 std::vector<char> tpbuf;
213 } cb_priv;
214 cb_priv.self = this;
215
216 auto cb = [](void* priv, const void* buf, size_t len) -> int {
217 SparseCBPrivate* data = static_cast<SparseCBPrivate*>(priv);
218 const char* cbuf = static_cast<const char*>(buf);
219 return data->self->SparseWriteCallback(data->tpbuf, cbuf, len);
220 };
221
Aaron Wisner9812b582018-08-22 11:01:04 -0500222 if (sparse_file_callback(s, true, use_crc, cb, &cb_priv) < 0) {
Aaron Wisnerdb511202018-06-26 15:38:35 -0500223 error_ = "Error reading sparse file";
224 return IO_ERROR;
225 }
226
227 // Now flush
228 if (cb_priv.tpbuf.size() && (ret = SendBuffer(cb_priv.tpbuf))) {
229 return ret;
230 }
231
232 return HandleResponse(response, info);
233}
234
235RetCode FastBootDriver::Upload(const std::string& outfile, std::string* response,
236 std::vector<std::string>* info) {
237 RetCode ret;
238 int dsize;
Aaron Wisnerc771ae02018-08-01 12:57:20 -0500239 if ((ret = RawCommand(Commands::UPLOAD, response, info, &dsize))) {
240 error_ = "Upload request failed: " + error_;
Aaron Wisnerdb511202018-06-26 15:38:35 -0500241 return ret;
242 }
243
Aaron Wisnerc771ae02018-08-01 12:57:20 -0500244 if (!dsize) {
245 error_ = "Upload request failed, device reports 0 bytes available";
246 return BAD_DEV_RESP;
247 }
248
Aaron Wisnerdb511202018-06-26 15:38:35 -0500249 std::vector<char> data;
250 data.resize(dsize);
251
252 if ((ret = ReadBuffer(data))) {
253 return ret;
254 }
255
256 std::ofstream ofs;
257 ofs.open(outfile, std::ofstream::out | std::ofstream::binary);
258 if (ofs.fail()) {
259 error_ = android::base::StringPrintf("Failed to open '%s'", outfile.c_str());
260 return IO_ERROR;
261 }
262 ofs.write(data.data(), data.size());
263 if (ofs.fail() || ofs.bad()) {
264 error_ = android::base::StringPrintf("Writing to '%s' failed", outfile.c_str());
265 return IO_ERROR;
266 }
267 ofs.close();
268
269 return HandleResponse(response, info);
270}
271
272// Helpers
273void FastBootDriver::SetInfoCallback(std::function<void(std::string&)> info) {
274 info_cb_ = info;
275}
276
277const std::string FastBootDriver::RCString(RetCode rc) {
278 switch (rc) {
279 case SUCCESS:
280 return std::string("Success");
281
282 case BAD_ARG:
283 return std::string("Invalid Argument");
284
285 case IO_ERROR:
286 return std::string("I/O Error");
287
288 case BAD_DEV_RESP:
289 return std::string("Invalid Device Response");
290
291 case DEVICE_FAIL:
292 return std::string("Device Error");
293
294 case TIMEOUT:
295 return std::string("Timeout");
296
297 default:
298 return std::string("Unknown Error");
299 }
300}
301
302std::string FastBootDriver::Error() {
303 return error_;
304}
305
306RetCode FastBootDriver::WaitForDisconnect() {
David Anderson1d887432018-08-27 16:47:32 -0700307 return transport_->WaitForDisconnect() ? IO_ERROR : SUCCESS;
Aaron Wisnerdb511202018-06-26 15:38:35 -0500308}
309
310/****************************** PROTECTED *************************************/
311RetCode FastBootDriver::RawCommand(const std::string& cmd, std::string* response,
312 std::vector<std::string>* info, int* dsize) {
313 error_ = ""; // Clear any pending error
314 if (cmd.size() > FB_COMMAND_SZ && !disable_checks_) {
315 error_ = "Command length to RawCommand() is too long";
316 return BAD_ARG;
317 }
318
David Anderson1d887432018-08-27 16:47:32 -0700319 if (transport_->Write(cmd.c_str(), cmd.size()) != static_cast<int>(cmd.size())) {
Aaron Wisnerdb511202018-06-26 15:38:35 -0500320 error_ = ErrnoStr("Write to device failed");
321 return IO_ERROR;
322 }
323
324 // Read the response
325 return HandleResponse(response, info, dsize);
326}
327
328RetCode FastBootDriver::DownloadCommand(uint32_t size, std::string* response,
329 std::vector<std::string>* info) {
330 std::string cmd(android::base::StringPrintf("%s%08" PRIx32, Commands::DOWNLOAD.c_str(), size));
331 RetCode ret;
332 if ((ret = RawCommand(cmd, response, info))) {
333 return ret;
334 }
335 return SUCCESS;
336}
337
338RetCode FastBootDriver::HandleResponse(std::string* response, std::vector<std::string>* info,
339 int* dsize) {
340 char status[FB_RESPONSE_SZ + 1];
341 auto start = std::chrono::system_clock::now();
342
343 auto set_response = [response](std::string s) {
344 if (response) *response = std::move(s);
345 };
346 auto add_info = [info](std::string s) {
347 if (info) info->push_back(std::move(s));
348 };
349
350 // erase response
351 set_response("");
352 while ((std::chrono::system_clock::now() - start) < std::chrono::seconds(RESP_TIMEOUT)) {
David Anderson1d887432018-08-27 16:47:32 -0700353 int r = transport_->Read(status, FB_RESPONSE_SZ);
Aaron Wisnerdb511202018-06-26 15:38:35 -0500354 if (r < 0) {
355 error_ = ErrnoStr("Status read failed");
356 return IO_ERROR;
357 }
358
359 status[r] = '\0'; // Need the null terminator
360 std::string input(status);
361 if (android::base::StartsWith(input, "INFO")) {
362 std::string tmp = input.substr(strlen("INFO"));
363 info_cb_(tmp);
364 add_info(std::move(tmp));
365 } else if (android::base::StartsWith(input, "OKAY")) {
366 set_response(input.substr(strlen("OKAY")));
367 return SUCCESS;
368 } else if (android::base::StartsWith(input, "FAIL")) {
369 error_ = android::base::StringPrintf("remote: '%s'", status + strlen("FAIL"));
370 set_response(input.substr(strlen("FAIL")));
371 return DEVICE_FAIL;
372 } else if (android::base::StartsWith(input, "DATA")) {
373 std::string tmp = input.substr(strlen("DATA"));
374 uint32_t num = strtol(tmp.c_str(), 0, 16);
375 if (num > MAX_DOWNLOAD_SIZE) {
376 error_ = android::base::StringPrintf("Data size too large (%d)", num);
377 return BAD_DEV_RESP;
378 }
379 if (dsize) *dsize = num;
380 set_response(std::move(tmp));
381 return SUCCESS;
382 } else {
383 error_ = android::base::StringPrintf("Device sent unknown status code: %s", status);
384 return BAD_DEV_RESP;
385 }
386
387 } // End of while loop
388
389 return TIMEOUT;
390}
391
392std::string FastBootDriver::ErrnoStr(const std::string& msg) {
393 return android::base::StringPrintf("%s (%s)", msg.c_str(), strerror(errno));
394}
395
396const std::string FastBootDriver::Commands::BOOT = "boot";
397const std::string FastBootDriver::Commands::CONTINUE = "continue";
398const std::string FastBootDriver::Commands::DOWNLOAD = "download:";
399const std::string FastBootDriver::Commands::ERASE = "erase:";
400const std::string FastBootDriver::Commands::FLASH = "flash:";
401const std::string FastBootDriver::Commands::GET_VAR = "getvar:";
Aaron Wisnerdb511202018-06-26 15:38:35 -0500402const std::string FastBootDriver::Commands::REBOOT = "reboot";
403const std::string FastBootDriver::Commands::SET_ACTIVE = "set_active:";
404const std::string FastBootDriver::Commands::UPLOAD = "upload";
Aaron Wisnerdb511202018-06-26 15:38:35 -0500405
406/******************************* PRIVATE **************************************/
407RetCode FastBootDriver::SendBuffer(int fd, size_t size) {
408 static constexpr uint32_t MAX_MAP_SIZE = 512 * 1024 * 1024;
409 off64_t offset = 0;
410 uint32_t remaining = size;
411 RetCode ret;
412
413 while (remaining) {
414 // Memory map the file
415 android::FileMap filemap;
416 size_t len = std::min(remaining, MAX_MAP_SIZE);
417
418 if (!filemap.create(NULL, fd, offset, len, true)) {
419 error_ = "Creating filemap failed";
420 return IO_ERROR;
421 }
422
423 if ((ret = SendBuffer(filemap.getDataPtr(), len))) {
424 return ret;
425 }
426
427 remaining -= len;
428 offset += len;
429 }
430
431 return SUCCESS;
432}
433
434RetCode FastBootDriver::SendBuffer(const std::vector<char>& buf) {
435 // Write the buffer
436 return SendBuffer(buf.data(), buf.size());
437}
438
439RetCode FastBootDriver::SendBuffer(const void* buf, size_t size) {
Aaron Wisnerc771ae02018-08-01 12:57:20 -0500440 // ioctl on 0-length buffer causes freezing
David Anderson0c7bde82018-07-30 12:54:53 -0700441 if (!size) {
Aaron Wisnerc771ae02018-08-01 12:57:20 -0500442 return BAD_ARG;
David Anderson0c7bde82018-07-30 12:54:53 -0700443 }
Aaron Wisnerdb511202018-06-26 15:38:35 -0500444 // Write the buffer
David Anderson1d887432018-08-27 16:47:32 -0700445 ssize_t tmp = transport_->Write(buf, size);
Aaron Wisnerdb511202018-06-26 15:38:35 -0500446
447 if (tmp < 0) {
448 error_ = ErrnoStr("Write to device failed in SendBuffer()");
449 return IO_ERROR;
450 } else if (static_cast<size_t>(tmp) != size) {
451 error_ = android::base::StringPrintf("Failed to write all %zu bytes", size);
452
453 return IO_ERROR;
454 }
455
456 return SUCCESS;
457}
458
459RetCode FastBootDriver::ReadBuffer(std::vector<char>& buf) {
460 // Read the buffer
461 return ReadBuffer(buf.data(), buf.size());
462}
463
464RetCode FastBootDriver::ReadBuffer(void* buf, size_t size) {
465 // Read the buffer
David Anderson1d887432018-08-27 16:47:32 -0700466 ssize_t tmp = transport_->Read(buf, size);
Aaron Wisnerdb511202018-06-26 15:38:35 -0500467
468 if (tmp < 0) {
469 error_ = ErrnoStr("Read from device failed in ReadBuffer()");
470 return IO_ERROR;
471 } else if (static_cast<size_t>(tmp) != size) {
472 error_ = android::base::StringPrintf("Failed to read all %zu bytes", size);
473 return IO_ERROR;
474 }
475
476 return SUCCESS;
477}
478
479int FastBootDriver::SparseWriteCallback(std::vector<char>& tpbuf, const char* data, size_t len) {
480 size_t total = 0;
481 size_t to_write = std::min(TRANSPORT_CHUNK_SIZE - tpbuf.size(), len);
482
483 // Handle the residual
484 tpbuf.insert(tpbuf.end(), data, data + to_write);
485 if (tpbuf.size() < TRANSPORT_CHUNK_SIZE) { // Nothing enough to send rn
486 return 0;
487 }
488
489 if (SendBuffer(tpbuf)) {
490 error_ = ErrnoStr("Send failed in SparseWriteCallback()");
491 return -1;
492 }
493 tpbuf.clear();
494 total += to_write;
495
496 // Now we need to send a multiple of chunk size
497 size_t nchunks = (len - total) / TRANSPORT_CHUNK_SIZE;
498 size_t nbytes = TRANSPORT_CHUNK_SIZE * nchunks;
Aaron Wisnerc771ae02018-08-01 12:57:20 -0500499 if (nbytes && SendBuffer(data + total, nbytes)) { // Don't send a ZLP
Aaron Wisnerdb511202018-06-26 15:38:35 -0500500 error_ = ErrnoStr("Send failed in SparseWriteCallback()");
501 return -1;
502 }
503 total += nbytes;
504
505 if (len - total > 0) { // We have residual data to save for next time
506 tpbuf.assign(data + total, data + len);
507 }
508
509 return 0;
510}
511
David Anderson03de6452018-09-04 14:32:54 -0700512Transport* FastBootDriver::set_transport(Transport* transport) {
513 std::swap(transport_, transport);
514 return transport;
David Anderson1d887432018-08-27 16:47:32 -0700515}
516
Aaron Wisnerdb511202018-06-26 15:38:35 -0500517} // End namespace fastboot