blob: aabc620d431a00cd7d663ae9cd870973e30b849a [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)
55 : transport(transport) {
56 info_cb_ = info;
57 disable_checks_ = no_checks;
58}
59
60RetCode FastBootDriver::Boot(std::string* response, std::vector<std::string>* info) {
61 return RawCommand(Commands::BOOT, response, info);
62}
63
64RetCode FastBootDriver::Continue(std::string* response, std::vector<std::string>* info) {
65 return RawCommand(Commands::CONTINUE, response, info);
66}
67
68RetCode FastBootDriver::Erase(const std::string& part, std::string* response,
69 std::vector<std::string>* info) {
70 return RawCommand(Commands::ERASE + part, response, info);
71}
72
73RetCode FastBootDriver::Flash(const std::string& part, std::string* response,
74 std::vector<std::string>* info) {
75 return RawCommand(Commands::FLASH + part, response, info);
76}
77
78RetCode FastBootDriver::GetVar(const std::string& key, std::string* val,
79 std::vector<std::string>* info) {
80 return RawCommand(Commands::GET_VAR + key, val, info);
81}
82
83RetCode FastBootDriver::GetVarAll(std::vector<std::string>* response) {
84 std::string tmp;
85 return GetVar("all", &tmp, response);
86}
87
88RetCode FastBootDriver::Powerdown(std::string* response, std::vector<std::string>* info) {
89 return RawCommand(Commands::POWERDOWN, response, info);
90}
91
92RetCode FastBootDriver::Reboot(std::string* response, std::vector<std::string>* info) {
93 return RawCommand(Commands::REBOOT, response, info);
94}
95
96RetCode FastBootDriver::SetActive(const std::string& part, std::string* response,
97 std::vector<std::string>* info) {
98 return RawCommand(Commands::SET_ACTIVE + part, response, info);
99}
100
101RetCode FastBootDriver::Verify(uint32_t num, std::string* response, std::vector<std::string>* info) {
102 std::string cmd = android::base::StringPrintf("%s%08" PRIx32, Commands::VERIFY.c_str(), num);
103 return RawCommand(cmd, response, info);
104}
105
106RetCode FastBootDriver::FlashPartition(const std::string& part, const std::vector<char>& data) {
107 RetCode ret;
108 if ((ret = Download(data))) {
109 return ret;
110 }
111 return RawCommand(Commands::FLASH + part);
112}
113
114RetCode FastBootDriver::FlashPartition(const std::string& part, int fd, uint32_t sz) {
115 RetCode ret;
116 if ((ret = Download(fd, sz))) {
117 return ret;
118 }
119 return RawCommand(Commands::FLASH + part);
120}
121
122RetCode FastBootDriver::FlashPartition(const std::string& part, sparse_file* s) {
123 RetCode ret;
124 if ((ret = Download(s))) {
125 return ret;
126 }
127 return RawCommand(Commands::FLASH + part);
128}
129
130RetCode FastBootDriver::Partitions(std::vector<std::tuple<std::string, uint32_t>>* parts) {
131 std::vector<std::string> all;
132 RetCode ret;
133 if ((ret = GetVarAll(&all))) {
134 return ret;
135 }
136
137 std::regex reg("partition-size[[:s:]]*:[[:s:]]*([[:w:]]+)[[:s:]]*:[[:s:]]*0x([[:d:]]+)");
138 std::smatch sm;
139
140 for (auto& s : all) {
141 if (std::regex_match(s, sm, reg)) {
142 std::string m1(sm[1]);
143 std::string m2(sm[2]);
144 uint32_t tmp = strtol(m2.c_str(), 0, 16);
145 parts->push_back(std::make_tuple(m1, tmp));
146 }
147 }
148 return SUCCESS;
149}
150
151RetCode FastBootDriver::Require(const std::string& var, const std::vector<std::string>& allowed,
152 bool* reqmet, bool invert) {
153 *reqmet = invert;
154 RetCode ret;
155 std::string response;
156 if ((ret = GetVar(var, &response))) {
157 return ret;
158 }
159
160 // Now check if we have a match
161 for (const auto s : allowed) {
162 // If it ends in *, and starting substring match
163 if (response == s || (s.length() && s.back() == '*' &&
164 !response.compare(0, s.length() - 1, s, 0, s.length() - 1))) {
165 *reqmet = !invert;
166 break;
167 }
168 }
169
170 return SUCCESS;
171}
172
173RetCode FastBootDriver::Download(int fd, size_t size, std::string* response,
174 std::vector<std::string>* info) {
175 RetCode ret;
176
177 if ((size <= 0 || size > MAX_DOWNLOAD_SIZE) && !disable_checks_) {
178 error_ = "File is too large to download";
179 return BAD_ARG;
180 }
181
182 uint32_t u32size = static_cast<uint32_t>(size);
183 if ((ret = DownloadCommand(u32size, response, info))) {
184 return ret;
185 }
186
187 // Write the buffer
188 if ((ret = SendBuffer(fd, size))) {
189 return ret;
190 }
191
192 // Wait for response
193 return HandleResponse(response, info);
194}
195
196RetCode FastBootDriver::Download(const std::vector<char>& buf, std::string* response,
197 std::vector<std::string>* info) {
198 return Download(buf.data(), buf.size(), response, info);
199}
200
201RetCode FastBootDriver::Download(const char* buf, uint32_t size, std::string* response,
202 std::vector<std::string>* info) {
203 RetCode ret;
204 error_ = "";
205 if ((size == 0 || size > MAX_DOWNLOAD_SIZE) && !disable_checks_) {
206 error_ = "Buffer is too large or 0 bytes";
207 return BAD_ARG;
208 }
209
210 if ((ret = DownloadCommand(size, response, info))) {
211 return ret;
212 }
213
214 // Write the buffer
215 if ((ret = SendBuffer(buf, size))) {
216 return ret;
217 }
218
219 // Wait for response
220 return HandleResponse(response, info);
221}
222
223RetCode FastBootDriver::Download(sparse_file* s, std::string* response,
224 std::vector<std::string>* info) {
225 error_ = "";
226 int64_t size = sparse_file_len(s, true, false);
227 if (size <= 0 || size > MAX_DOWNLOAD_SIZE) {
228 error_ = "Sparse file is too large or invalid";
229 return BAD_ARG;
230 }
231
232 RetCode ret;
233 uint32_t u32size = static_cast<uint32_t>(size);
234 if ((ret = DownloadCommand(u32size, response, info))) {
235 return ret;
236 }
237
238 struct SparseCBPrivate {
239 FastBootDriver* self;
240 std::vector<char> tpbuf;
241 } cb_priv;
242 cb_priv.self = this;
243
244 auto cb = [](void* priv, const void* buf, size_t len) -> int {
245 SparseCBPrivate* data = static_cast<SparseCBPrivate*>(priv);
246 const char* cbuf = static_cast<const char*>(buf);
247 return data->self->SparseWriteCallback(data->tpbuf, cbuf, len);
248 };
249
250 if (sparse_file_callback(s, true, false, cb, &cb_priv) < 0) {
251 error_ = "Error reading sparse file";
252 return IO_ERROR;
253 }
254
255 // Now flush
256 if (cb_priv.tpbuf.size() && (ret = SendBuffer(cb_priv.tpbuf))) {
257 return ret;
258 }
259
260 return HandleResponse(response, info);
261}
262
263RetCode FastBootDriver::Upload(const std::string& outfile, std::string* response,
264 std::vector<std::string>* info) {
265 RetCode ret;
266 int dsize;
267 if ((ret = RawCommand(Commands::UPLOAD, response, info, &dsize)) || dsize == 0) {
268 error_ = "Upload request failed";
269 return ret;
270 }
271
272 std::vector<char> data;
273 data.resize(dsize);
274
275 if ((ret = ReadBuffer(data))) {
276 return ret;
277 }
278
279 std::ofstream ofs;
280 ofs.open(outfile, std::ofstream::out | std::ofstream::binary);
281 if (ofs.fail()) {
282 error_ = android::base::StringPrintf("Failed to open '%s'", outfile.c_str());
283 return IO_ERROR;
284 }
285 ofs.write(data.data(), data.size());
286 if (ofs.fail() || ofs.bad()) {
287 error_ = android::base::StringPrintf("Writing to '%s' failed", outfile.c_str());
288 return IO_ERROR;
289 }
290 ofs.close();
291
292 return HandleResponse(response, info);
293}
294
295// Helpers
296void FastBootDriver::SetInfoCallback(std::function<void(std::string&)> info) {
297 info_cb_ = info;
298}
299
300const std::string FastBootDriver::RCString(RetCode rc) {
301 switch (rc) {
302 case SUCCESS:
303 return std::string("Success");
304
305 case BAD_ARG:
306 return std::string("Invalid Argument");
307
308 case IO_ERROR:
309 return std::string("I/O Error");
310
311 case BAD_DEV_RESP:
312 return std::string("Invalid Device Response");
313
314 case DEVICE_FAIL:
315 return std::string("Device Error");
316
317 case TIMEOUT:
318 return std::string("Timeout");
319
320 default:
321 return std::string("Unknown Error");
322 }
323}
324
325std::string FastBootDriver::Error() {
326 return error_;
327}
328
329RetCode FastBootDriver::WaitForDisconnect() {
330 return transport->WaitForDisconnect() ? IO_ERROR : SUCCESS;
331}
332
333/****************************** PROTECTED *************************************/
334RetCode FastBootDriver::RawCommand(const std::string& cmd, std::string* response,
335 std::vector<std::string>* info, int* dsize) {
336 error_ = ""; // Clear any pending error
337 if (cmd.size() > FB_COMMAND_SZ && !disable_checks_) {
338 error_ = "Command length to RawCommand() is too long";
339 return BAD_ARG;
340 }
341
342 if (transport->Write(cmd.c_str(), cmd.size()) != static_cast<int>(cmd.size())) {
343 error_ = ErrnoStr("Write to device failed");
344 return IO_ERROR;
345 }
346
347 // Read the response
348 return HandleResponse(response, info, dsize);
349}
350
351RetCode FastBootDriver::DownloadCommand(uint32_t size, std::string* response,
352 std::vector<std::string>* info) {
353 std::string cmd(android::base::StringPrintf("%s%08" PRIx32, Commands::DOWNLOAD.c_str(), size));
354 RetCode ret;
355 if ((ret = RawCommand(cmd, response, info))) {
356 return ret;
357 }
358 return SUCCESS;
359}
360
361RetCode FastBootDriver::HandleResponse(std::string* response, std::vector<std::string>* info,
362 int* dsize) {
363 char status[FB_RESPONSE_SZ + 1];
364 auto start = std::chrono::system_clock::now();
365
366 auto set_response = [response](std::string s) {
367 if (response) *response = std::move(s);
368 };
369 auto add_info = [info](std::string s) {
370 if (info) info->push_back(std::move(s));
371 };
372
373 // erase response
374 set_response("");
375 while ((std::chrono::system_clock::now() - start) < std::chrono::seconds(RESP_TIMEOUT)) {
376 int r = transport->Read(status, FB_RESPONSE_SZ);
377 if (r < 0) {
378 error_ = ErrnoStr("Status read failed");
379 return IO_ERROR;
380 }
381
382 status[r] = '\0'; // Need the null terminator
383 std::string input(status);
384 if (android::base::StartsWith(input, "INFO")) {
385 std::string tmp = input.substr(strlen("INFO"));
386 info_cb_(tmp);
387 add_info(std::move(tmp));
388 } else if (android::base::StartsWith(input, "OKAY")) {
389 set_response(input.substr(strlen("OKAY")));
390 return SUCCESS;
391 } else if (android::base::StartsWith(input, "FAIL")) {
392 error_ = android::base::StringPrintf("remote: '%s'", status + strlen("FAIL"));
393 set_response(input.substr(strlen("FAIL")));
394 return DEVICE_FAIL;
395 } else if (android::base::StartsWith(input, "DATA")) {
396 std::string tmp = input.substr(strlen("DATA"));
397 uint32_t num = strtol(tmp.c_str(), 0, 16);
398 if (num > MAX_DOWNLOAD_SIZE) {
399 error_ = android::base::StringPrintf("Data size too large (%d)", num);
400 return BAD_DEV_RESP;
401 }
402 if (dsize) *dsize = num;
403 set_response(std::move(tmp));
404 return SUCCESS;
405 } else {
406 error_ = android::base::StringPrintf("Device sent unknown status code: %s", status);
407 return BAD_DEV_RESP;
408 }
409
410 } // End of while loop
411
412 return TIMEOUT;
413}
414
415std::string FastBootDriver::ErrnoStr(const std::string& msg) {
416 return android::base::StringPrintf("%s (%s)", msg.c_str(), strerror(errno));
417}
418
419const std::string FastBootDriver::Commands::BOOT = "boot";
420const std::string FastBootDriver::Commands::CONTINUE = "continue";
421const std::string FastBootDriver::Commands::DOWNLOAD = "download:";
422const std::string FastBootDriver::Commands::ERASE = "erase:";
423const std::string FastBootDriver::Commands::FLASH = "flash:";
424const std::string FastBootDriver::Commands::GET_VAR = "getvar:";
425const std::string FastBootDriver::Commands::POWERDOWN = "powerdown";
426const std::string FastBootDriver::Commands::REBOOT = "reboot";
427const std::string FastBootDriver::Commands::SET_ACTIVE = "set_active:";
428const std::string FastBootDriver::Commands::UPLOAD = "upload";
429const std::string FastBootDriver::Commands::VERIFY = "verify:";
430
431/******************************* PRIVATE **************************************/
432RetCode FastBootDriver::SendBuffer(int fd, size_t size) {
433 static constexpr uint32_t MAX_MAP_SIZE = 512 * 1024 * 1024;
434 off64_t offset = 0;
435 uint32_t remaining = size;
436 RetCode ret;
437
438 while (remaining) {
439 // Memory map the file
440 android::FileMap filemap;
441 size_t len = std::min(remaining, MAX_MAP_SIZE);
442
443 if (!filemap.create(NULL, fd, offset, len, true)) {
444 error_ = "Creating filemap failed";
445 return IO_ERROR;
446 }
447
448 if ((ret = SendBuffer(filemap.getDataPtr(), len))) {
449 return ret;
450 }
451
452 remaining -= len;
453 offset += len;
454 }
455
456 return SUCCESS;
457}
458
459RetCode FastBootDriver::SendBuffer(const std::vector<char>& buf) {
460 // Write the buffer
461 return SendBuffer(buf.data(), buf.size());
462}
463
464RetCode FastBootDriver::SendBuffer(const void* buf, size_t size) {
David Anderson0c7bde82018-07-30 12:54:53 -0700465 if (!size) {
466 return SUCCESS;
467 }
468
Aaron Wisnerdb511202018-06-26 15:38:35 -0500469 // Write the buffer
470 ssize_t tmp = transport->Write(buf, size);
471
472 if (tmp < 0) {
473 error_ = ErrnoStr("Write to device failed in SendBuffer()");
474 return IO_ERROR;
475 } else if (static_cast<size_t>(tmp) != size) {
476 error_ = android::base::StringPrintf("Failed to write all %zu bytes", size);
477
478 return IO_ERROR;
479 }
480
481 return SUCCESS;
482}
483
484RetCode FastBootDriver::ReadBuffer(std::vector<char>& buf) {
485 // Read the buffer
486 return ReadBuffer(buf.data(), buf.size());
487}
488
489RetCode FastBootDriver::ReadBuffer(void* buf, size_t size) {
490 // Read the buffer
491 ssize_t tmp = transport->Read(buf, size);
492
493 if (tmp < 0) {
494 error_ = ErrnoStr("Read from device failed in ReadBuffer()");
495 return IO_ERROR;
496 } else if (static_cast<size_t>(tmp) != size) {
497 error_ = android::base::StringPrintf("Failed to read all %zu bytes", size);
498 return IO_ERROR;
499 }
500
501 return SUCCESS;
502}
503
504int FastBootDriver::SparseWriteCallback(std::vector<char>& tpbuf, const char* data, size_t len) {
505 size_t total = 0;
506 size_t to_write = std::min(TRANSPORT_CHUNK_SIZE - tpbuf.size(), len);
507
508 // Handle the residual
509 tpbuf.insert(tpbuf.end(), data, data + to_write);
510 if (tpbuf.size() < TRANSPORT_CHUNK_SIZE) { // Nothing enough to send rn
511 return 0;
512 }
513
514 if (SendBuffer(tpbuf)) {
515 error_ = ErrnoStr("Send failed in SparseWriteCallback()");
516 return -1;
517 }
518 tpbuf.clear();
519 total += to_write;
520
521 // Now we need to send a multiple of chunk size
522 size_t nchunks = (len - total) / TRANSPORT_CHUNK_SIZE;
523 size_t nbytes = TRANSPORT_CHUNK_SIZE * nchunks;
524 if (SendBuffer(data + total, nbytes)) {
525 error_ = ErrnoStr("Send failed in SparseWriteCallback()");
526 return -1;
527 }
528 total += nbytes;
529
530 if (len - total > 0) { // We have residual data to save for next time
531 tpbuf.assign(data + total, data + len);
532 }
533
534 return 0;
535}
536
537} // End namespace fastboot