1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
|
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <iostream>
#include <memory>
#include <string_view>
#include <unordered_map>
#include <vector>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/containers/span.h"
#include "base/files/file_path.h"
#include "base/format_macros.h"
#include "base/hash/md5.h"
#include "base/logging.h"
#include "base/message_loop/message_pump_type.h"
#include "base/pickle.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/task/single_thread_task_executor.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "crypto/obsolete/md5.h"
#include "net/base/io_buffer.h"
#include "net/base/test_completion_callback.h"
#include "net/disk_cache/disk_cache.h"
#include "net/disk_cache/disk_cache_test_util.h"
#include "net/http/http_cache.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/http/http_util.h"
using disk_cache::Backend;
using disk_cache::BackendResult;
using disk_cache::Entry;
using disk_cache::EntryResult;
namespace cachetool {
crypto::obsolete::Md5 MakeMd5HasherForCachetools() {
return {};
}
} // namespace cachetool
namespace {
struct EntryData {
std::string url;
std::string mime_type;
int size;
};
constexpr int kResponseInfoIndex = 0;
constexpr int kResponseContentIndex = 1;
auto kCommandNames = std::to_array(
{"stop", "get_size", "list_keys", "get_stream", "delete_stream",
"delete_key", "update_raw_headers", "list_dups", "set_header"});
// Prints the command line help.
void PrintHelp() {
std::cout << "cachetool <cache_path> <cache_backend_type> <subcommand> "
<< std::endl
<< std::endl;
std::cout << "Available cache backend types: simple, blockfile" << std::endl;
std::cout << "Available subcommands:" << std::endl;
std::cout << " batch: Starts cachetool to process serialized commands "
<< "passed down by the standard input and return commands output "
<< "in the stdout until the stop command is received." << std::endl;
std::cout << " delete_key <key>: Delete key from cache." << std::endl;
std::cout << " delete_stream <key> <index>: Delete a particular stream of a"
<< " given key." << std::endl;
std::cout << " get_size: Calculate the total size of the cache in bytes."
<< std::endl;
std::cout << " get_stream <key> <index>: Print a particular stream for a"
<< " given key." << std::endl;
std::cout << " list_keys: List all keys in the cache." << std::endl;
std::cout << " list_dups: List all resources with duplicate bodies in the "
<< "cache." << std::endl;
std::cout << " update_raw_headers <key>: Update stdin as the key's raw "
<< "response headers." << std::endl;
std::cout << " set_header <key> <name> <value>: Set one of key's raw "
<< "response headers." << std::endl;
std::cout << " stop: Verify that the cache can be opened and return, "
<< "confirming the cache exists and is of the right type."
<< std::endl;
std::cout << "Expected values of <index> are:" << std::endl;
std::cout << " 0 (HTTP response headers)" << std::endl;
std::cout << " 1 (transport encoded content)" << std::endl;
std::cout << " 2 (compiled content)" << std::endl;
}
// Generic command input/output.
class CommandMarshal {
public:
explicit CommandMarshal(Backend* cache_backend)
: cache_backend_(cache_backend) {}
virtual ~CommandMarshal() = default;
// Reads the next command's name to execute.
virtual std::string ReadCommandName() = 0;
// Reads the next parameter as an integer.
virtual int ReadInt() = 0;
// Reads the next parameter as stream index.
int ReadStreamIndex() {
if (has_failed())
return -1;
int index = ReadInt();
if (index < 0 || index > 2) {
ReturnFailure("Invalid stream index.");
return -1;
}
return index;
}
// Reads the next parameter as a string.
virtual std::string ReadString() = 0;
// Reads the next parameter from stdin as string.
virtual std::string ReadBufferedString() = 0;
// Communicates back an integer.
virtual void ReturnInt(int integer) = 0;
// Communicates back a 64-bit integer.
virtual void ReturnInt64(int64_t integer) = 0;
// Communicates back a string.
virtual void ReturnString(const std::string& string) = 0;
// Communicates back a buffer.
virtual void ReturnBuffer(net::GrowableIOBuffer* buffer) = 0;
// Communicates back command failure.
virtual void ReturnFailure(const std::string& error_msg) = 0;
// Communicates back command success.
virtual void ReturnSuccess() { DCHECK(!command_failed_); }
// Returns whether the command has failed.
inline bool has_failed() { return command_failed_; }
// Returns the opened cache backend.
Backend* cache_backend() { return cache_backend_; }
protected:
bool command_failed_ = false;
Backend* const cache_backend_;
};
// Command line input/output that is user readable.
class ProgramArgumentCommandMarshal final : public CommandMarshal {
public:
ProgramArgumentCommandMarshal(Backend* cache_backend,
base::CommandLine::StringVector args)
: CommandMarshal(cache_backend), command_line_args_(args) {}
// Implements CommandMarshal.
std::string ReadCommandName() override {
if (args_id_ == 0)
return ReadString();
else if (args_id_ == command_line_args_.size())
return "stop";
else if (!has_failed())
ReturnFailure("Command line arguments too long.");
return "";
}
// Implements CommandMarshal.
int ReadInt() override {
std::string integer_str = ReadString();
int integer = -1;
if (!base::StringToInt(integer_str, &integer)) {
ReturnFailure("Couldn't parse integer.");
return 0;
}
return integer;
}
// Implements CommandMarshal.
std::string ReadString() override {
if (args_id_ < command_line_args_.size())
return command_line_args_[args_id_++];
if (!has_failed())
ReturnFailure("Command line arguments too short.");
return "";
}
// Implements CommandMarshal.
std::string ReadBufferedString() override {
std::ostringstream raw_headers_stream;
for (std::string line; std::getline(std::cin, line);)
raw_headers_stream << line << std::endl;
return raw_headers_stream.str();
}
// Implements CommandMarshal.
void ReturnInt(int integer) override {
DCHECK(!has_failed());
std::cout << integer << std::endl;
}
// Implements CommandMarshal.
void ReturnInt64(int64_t integer) override {
DCHECK(!has_failed());
std::cout << integer << std::endl;
}
// Implements CommandMarshal.
void ReturnString(const std::string& string) override {
DCHECK(!has_failed());
std::cout << string << std::endl;
}
// Implements CommandMarshal.
void ReturnBuffer(net::GrowableIOBuffer* buffer) override {
DCHECK(!has_failed());
auto span = base::as_chars(buffer->span_before_offset());
std::cout.write(span.data(), span.size());
}
// Implements CommandMarshal.
void ReturnFailure(const std::string& error_msg) override {
DCHECK(!has_failed());
std::cerr << error_msg << std::endl;
command_failed_ = true;
}
private:
const base::CommandLine::StringVector command_line_args_;
size_t args_id_ = 0;
};
// Online command input/output that receives pickled commands from stdin and
// returns their results back in stdout. Send the stop command to properly exit
// cachetool's main loop.
class StreamCommandMarshal final : public CommandMarshal {
public:
explicit StreamCommandMarshal(Backend* cache_backend)
: CommandMarshal(cache_backend) {}
// Implements CommandMarshal.
std::string ReadCommandName() override {
if (has_failed())
return "";
std::cout.flush();
size_t command_id = static_cast<size_t>(std::cin.get());
if (command_id >= kCommandNames.size()) {
ReturnFailure("Unknown command.");
return "";
}
return kCommandNames[command_id];
}
// Implements CommandMarshal.
int ReadInt() override {
if (has_failed())
return -1;
int integer = -1;
std::cin.read(reinterpret_cast<char*>(&integer), sizeof(integer));
return integer;
}
// Implements CommandMarshal.
std::string ReadString() override {
if (has_failed())
return "";
int string_size = ReadInt();
if (string_size <= 0) {
if (string_size < 0)
ReturnFailure("Size of string is negative.");
return "";
}
std::vector<char> tmp_buffer(string_size + 1);
std::cin.read(tmp_buffer.data(), string_size);
tmp_buffer[string_size] = 0;
return std::string(tmp_buffer.data(), string_size);
}
// Implements CommandMarshal.
std::string ReadBufferedString() override { return ReadString(); }
// Implements CommandMarshal.
void ReturnInt(int integer) override {
DCHECK(!command_failed_);
std::cout.write(reinterpret_cast<char*>(&integer), sizeof(integer));
}
// Implements CommandMarshal.
void ReturnInt64(int64_t integer) override {
DCHECK(!has_failed());
std::cout.write(reinterpret_cast<char*>(&integer), sizeof(integer));
}
// Implements CommandMarshal.
void ReturnString(const std::string& string) override {
ReturnInt(string.size());
std::cout.write(string.c_str(), string.size());
}
// Implements CommandMarshal.
void ReturnBuffer(net::GrowableIOBuffer* buffer) override {
ReturnInt(buffer->offset());
auto span = base::as_chars(buffer->span_before_offset());
std::cout.write(span.data(), span.size());
}
// Implements CommandMarshal.
void ReturnFailure(const std::string& error_msg) override {
ReturnString(error_msg);
command_failed_ = true;
}
// Implements CommandMarshal.
void ReturnSuccess() override { ReturnInt(0); }
};
// Gets the cache's size.
void GetSize(CommandMarshal* command_marshal) {
net::TestInt64CompletionCallback cb;
int64_t rv = command_marshal->cache_backend()->CalculateSizeOfAllEntries(
cb.callback());
rv = cb.GetResult(rv);
if (rv < 0)
return command_marshal->ReturnFailure("Couldn't get cache size.");
command_marshal->ReturnSuccess();
command_marshal->ReturnInt64(rv);
}
// Prints all of a cache's keys to stdout.
bool ListKeys(CommandMarshal* command_marshal) {
std::unique_ptr<Backend::Iterator> entry_iterator =
command_marshal->cache_backend()->CreateIterator();
TestEntryResultCompletionCallback cb;
EntryResult result = entry_iterator->OpenNextEntry(cb.callback());
command_marshal->ReturnSuccess();
while ((result = cb.GetResult(std::move(result))).net_error() == net::OK) {
Entry* entry = result.ReleaseEntry();
std::string url = entry->GetKey();
command_marshal->ReturnString(url);
entry->Close();
result = entry_iterator->OpenNextEntry(cb.callback());
}
command_marshal->ReturnString("");
return true;
}
bool GetResponseInfoForEntry(disk_cache::Entry* entry,
net::HttpResponseInfo* response_info) {
int size = entry->GetDataSize(kResponseInfoIndex);
if (size == 0)
return false;
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBufferWithSize>(size);
net::TestCompletionCallback cb;
int bytes_read = 0;
while (true) {
int rv = entry->ReadData(kResponseInfoIndex, bytes_read, buffer.get(), size,
cb.callback());
rv = cb.GetResult(rv);
if (rv < 0) {
entry->Close();
return false;
}
if (rv == 0) {
bool truncated_response_info = false;
if (!net::HttpCache::ParseResponseInfo(buffer->span(), response_info,
&truncated_response_info)) {
return false;
}
return !truncated_response_info;
}
bytes_read += rv;
}
NOTREACHED();
}
std::string GetMD5ForResponseBody(disk_cache::Entry* entry) {
if (entry->GetDataSize(kResponseContentIndex) == 0)
return "";
const int kInitBufferSize = 80 * 1024;
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBufferWithSize>(kInitBufferSize);
net::TestCompletionCallback cb;
crypto::obsolete::Md5 hasher = cachetool::MakeMd5HasherForCachetools();
int bytes_read = 0;
while (true) {
int rv = entry->ReadData(kResponseContentIndex, bytes_read, buffer.get(),
kInitBufferSize, cb.callback());
rv = cb.GetResult(rv);
if (rv < 0) {
entry->Close();
return "";
}
if (rv == 0) {
return base::ToLowerASCII(base::HexEncode(hasher.Finish()));
}
bytes_read += rv;
hasher.Update(buffer->span());
}
NOTREACHED();
}
void PersistResponseInfo(CommandMarshal* command_marshal,
const std::string& key,
const net::HttpResponseInfo& response_info) {
scoped_refptr<net::PickledIOBuffer> data =
base::MakeRefCounted<net::PickledIOBuffer>(response_info.MakePickle(
/*skip_transient_headers=*/false, /*response_truncated=*/false));
TestEntryResultCompletionCallback cb_open;
EntryResult result = command_marshal->cache_backend()->OpenEntry(
key, net::HIGHEST, cb_open.callback());
result = cb_open.GetResult(std::move(result));
CHECK_EQ(result.net_error(), net::OK);
Entry* cache_entry = result.ReleaseEntry();
int data_len = data->size();
net::TestCompletionCallback cb;
int rv = cache_entry->WriteData(kResponseInfoIndex, 0, data.get(), data_len,
cb.callback(), true);
if (cb.GetResult(rv) != data_len)
return command_marshal->ReturnFailure("Couldn't write headers.");
command_marshal->ReturnSuccess();
cache_entry->Close();
}
void ListDups(CommandMarshal* command_marshal) {
std::unique_ptr<Backend::Iterator> entry_iterator =
command_marshal->cache_backend()->CreateIterator();
TestEntryResultCompletionCallback cb;
disk_cache::EntryResult result = entry_iterator->OpenNextEntry(cb.callback());
command_marshal->ReturnSuccess();
std::unordered_map<std::string, std::vector<EntryData>> md5_entries;
int total_entries = 0;
while ((result = cb.GetResult(std::move(result))).net_error() == net::OK) {
Entry* entry = result.ReleaseEntry();
total_entries += 1;
net::HttpResponseInfo response_info;
if (!GetResponseInfoForEntry(entry, &response_info)) {
entry->Close();
entry = nullptr;
result = entry_iterator->OpenNextEntry(cb.callback());
continue;
}
std::string hash = GetMD5ForResponseBody(entry);
if (hash.empty()) {
// Sparse entries and empty bodies are skipped.
entry->Close();
entry = nullptr;
result = entry_iterator->OpenNextEntry(cb.callback());
continue;
}
EntryData entry_data;
entry_data.url = entry->GetKey();
entry_data.size = entry->GetDataSize(kResponseContentIndex);
if (response_info.headers)
response_info.headers->GetMimeType(&entry_data.mime_type);
auto iter = md5_entries.find(hash);
if (iter == md5_entries.end()) {
md5_entries.emplace(hash, std::vector<EntryData>{entry_data});
} else {
iter->second.push_back(entry_data);
}
entry->Close();
entry = nullptr;
result = entry_iterator->OpenNextEntry(cb.callback());
}
// Print the duplicates and collect stats.
int total_duped_entries = 0;
int64_t total_duped_bytes = 0u;
for (const auto& hash_and_entries : md5_entries) {
if (hash_and_entries.second.size() == 1)
continue;
int dups = hash_and_entries.second.size() - 1;
total_duped_entries += dups;
total_duped_bytes += hash_and_entries.second[0].size * dups;
for (const auto& entry : hash_and_entries.second) {
std::string out = base::StringPrintf(
"%d, %s, %s", entry.size, entry.url.c_str(), entry.mime_type.c_str());
command_marshal->ReturnString(out);
}
}
// Print the stats.
net::TestInt64CompletionCallback size_cb;
int64_t rv = command_marshal->cache_backend()->CalculateSizeOfAllEntries(
size_cb.callback());
rv = size_cb.GetResult(rv);
LOG(ERROR) << "Wasted bytes = " << total_duped_bytes;
LOG(ERROR) << "Wasted entries = " << total_duped_entries;
LOG(ERROR) << "Total entries = " << total_entries;
LOG(ERROR) << "Cache size = " << rv;
LOG(ERROR) << "Percentage of cache wasted = " << total_duped_bytes * 100 / rv;
}
// Gets a key's stream to a buffer.
scoped_refptr<net::GrowableIOBuffer> GetStreamForKeyBuffer(
CommandMarshal* command_marshal,
const std::string& key,
int index) {
DCHECK(!command_marshal->has_failed());
TestEntryResultCompletionCallback cb_open;
EntryResult result = command_marshal->cache_backend()->OpenEntry(
key, net::HIGHEST, cb_open.callback());
result = cb_open.GetResult(std::move(result));
if (result.net_error() != net::OK) {
command_marshal->ReturnFailure("Couldn't find key's entry.");
return nullptr;
}
Entry* cache_entry = result.ReleaseEntry();
const int kInitBufferSize = 8192;
scoped_refptr<net::GrowableIOBuffer> buffer =
base::MakeRefCounted<net::GrowableIOBuffer>();
buffer->SetCapacity(kInitBufferSize);
net::TestCompletionCallback cb;
while (true) {
int rv = cache_entry->ReadData(index, buffer->offset(), buffer.get(),
buffer->capacity() - buffer->offset(),
cb.callback());
rv = cb.GetResult(rv);
if (rv < 0) {
cache_entry->Close();
command_marshal->ReturnFailure("Stream read error.");
return nullptr;
}
buffer->set_offset(buffer->offset() + rv);
if (rv == 0)
break;
buffer->SetCapacity(buffer->offset() * 2);
}
cache_entry->Close();
return buffer;
}
// Prints a key's stream to stdout.
void GetStreamForKey(CommandMarshal* command_marshal) {
std::string key = command_marshal->ReadString();
int index = command_marshal->ReadInt();
if (command_marshal->has_failed())
return;
scoped_refptr<net::GrowableIOBuffer> buffer(
GetStreamForKeyBuffer(command_marshal, key, index));
if (command_marshal->has_failed())
return;
if (index == kResponseInfoIndex) {
net::HttpResponseInfo response_info;
bool truncated_response_info = false;
if (!net::HttpCache::ParseResponseInfo(buffer->span_before_offset(),
&response_info,
&truncated_response_info)) {
// This can happen when reading data stored by content::CacheStorage.
std::cerr << "WARNING: Returning empty response info for key: " << key
<< std::endl;
command_marshal->ReturnSuccess();
return command_marshal->ReturnString("");
}
if (truncated_response_info)
std::cerr << "WARNING: Truncated HTTP response." << std::endl;
command_marshal->ReturnSuccess();
command_marshal->ReturnString(
net::HttpUtil::ConvertHeadersBackToHTTPResponse(
response_info.headers->raw_headers()));
} else {
command_marshal->ReturnSuccess();
command_marshal->ReturnBuffer(buffer.get());
}
}
// Sets stdin as the key's raw response headers.
void UpdateRawResponseHeaders(CommandMarshal* command_marshal) {
std::string key = command_marshal->ReadString();
std::string raw_headers = command_marshal->ReadBufferedString();
if (command_marshal->has_failed())
return;
scoped_refptr<net::GrowableIOBuffer> buffer(
GetStreamForKeyBuffer(command_marshal, key, kResponseInfoIndex));
if (command_marshal->has_failed())
return;
net::HttpResponseInfo response_info;
bool truncated_response_info = false;
net::HttpCache::ParseResponseInfo(buffer->span_before_offset(),
&response_info, &truncated_response_info);
if (truncated_response_info)
std::cerr << "WARNING: Truncated HTTP response." << std::endl;
response_info.headers =
base::MakeRefCounted<net::HttpResponseHeaders>(raw_headers);
PersistResponseInfo(command_marshal, key, response_info);
}
// Sets a response header for a key.
void SetHeader(CommandMarshal* command_marshal) {
std::string key = command_marshal->ReadString();
std::string header_name = command_marshal->ReadString();
std::string header_value = command_marshal->ReadString();
if (command_marshal->has_failed())
return;
// Open the existing entry.
scoped_refptr<net::GrowableIOBuffer> buffer(
GetStreamForKeyBuffer(command_marshal, key, kResponseInfoIndex));
if (command_marshal->has_failed())
return;
// Read the entry into |response_info|.
net::HttpResponseInfo response_info;
bool truncated_response_info = false;
if (!net::HttpCache::ParseResponseInfo(buffer->span_before_offset(),
&response_info,
&truncated_response_info)) {
command_marshal->ReturnFailure("Couldn't read response info");
return;
}
if (truncated_response_info)
std::cerr << "WARNING: Truncated HTTP response." << std::endl;
// Update the header.
response_info.headers->SetHeader(header_name, header_value);
// Write the entry.
PersistResponseInfo(command_marshal, key, response_info);
}
// Deletes a specified key stream from the cache.
void DeleteStreamForKey(CommandMarshal* command_marshal) {
std::string key = command_marshal->ReadString();
int index = command_marshal->ReadInt();
if (command_marshal->has_failed())
return;
TestEntryResultCompletionCallback cb_open;
EntryResult result = command_marshal->cache_backend()->OpenEntry(
key, net::HIGHEST, cb_open.callback());
result = cb_open.GetResult(std::move(result));
if (result.net_error() != net::OK)
return command_marshal->ReturnFailure("Couldn't find key's entry.");
Entry* cache_entry = result.ReleaseEntry();
net::TestCompletionCallback cb;
scoped_refptr<net::StringIOBuffer> buffer =
base::MakeRefCounted<net::StringIOBuffer>("");
int rv =
cache_entry->WriteData(index, 0, buffer.get(), 0, cb.callback(), true);
if (cb.GetResult(rv) != net::OK)
return command_marshal->ReturnFailure("Couldn't delete key stream.");
command_marshal->ReturnSuccess();
cache_entry->Close();
}
// Deletes a specified key from the cache.
void DeleteKey(CommandMarshal* command_marshal) {
std::string key = command_marshal->ReadString();
if (command_marshal->has_failed())
return;
net::TestCompletionCallback cb;
int rv = command_marshal->cache_backend()->DoomEntry(key, net::HIGHEST,
cb.callback());
if (cb.GetResult(rv) != net::OK)
command_marshal->ReturnFailure("Couldn't delete key.");
else
command_marshal->ReturnSuccess();
}
// Executes all command from the |command_marshal|.
bool ExecuteCommands(CommandMarshal* command_marshal) {
while (!command_marshal->has_failed()) {
std::string subcommand(command_marshal->ReadCommandName());
if (command_marshal->has_failed())
break;
if (subcommand == "stop") {
command_marshal->ReturnSuccess();
return true;
} else if (subcommand == "batch") {
StreamCommandMarshal stream_command_marshal(
command_marshal->cache_backend());
return ExecuteCommands(&stream_command_marshal);
} else if (subcommand == "delete_key") {
DeleteKey(command_marshal);
} else if (subcommand == "delete_stream") {
DeleteStreamForKey(command_marshal);
} else if (subcommand == "get_size") {
GetSize(command_marshal);
} else if (subcommand == "get_stream") {
GetStreamForKey(command_marshal);
} else if (subcommand == "list_keys") {
ListKeys(command_marshal);
} else if (subcommand == "update_raw_headers") {
UpdateRawResponseHeaders(command_marshal);
} else if (subcommand == "set_header") {
SetHeader(command_marshal);
} else if (subcommand == "list_dups") {
ListDups(command_marshal);
} else {
// The wrong subcommand is originated from the command line.
command_marshal->ReturnFailure("Unknown command.");
PrintHelp();
}
}
return false;
}
} // namespace
int main(int argc, char* argv[]) {
base::AtExitManager at_exit_manager;
base::SingleThreadTaskExecutor io_task_executor(base::MessagePumpType::IO);
base::CommandLine::Init(argc, argv);
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
base::CommandLine::StringVector args = command_line.GetArgs();
if (args.size() < 3U) {
PrintHelp();
return 1;
}
base::ThreadPoolInstance::CreateAndStartWithDefaultParams("cachetool");
base::FilePath cache_path(args[0]);
std::string cache_backend_type(args[1]);
net::BackendType backend_type;
if (cache_backend_type == "simple") {
backend_type = net::CACHE_BACKEND_SIMPLE;
} else if (cache_backend_type == "blockfile") {
backend_type = net::CACHE_BACKEND_BLOCKFILE;
} else {
std::cerr << "Unknown cache type." << std::endl;
PrintHelp();
return 1;
}
TestBackendResultCompletionCallback cb;
BackendResult result = disk_cache::CreateCacheBackend(
net::DISK_CACHE, backend_type, /*file_operations=*/nullptr, cache_path,
INT_MAX, disk_cache::ResetHandling::kNeverReset, /*net_log=*/nullptr,
cb.callback());
result = cb.GetResult(std::move(result));
if (result.net_error != net::OK) {
std::cerr << "Invalid cache." << std::endl;
return 1;
}
std::unique_ptr<Backend> cache_backend = std::move(result.backend);
ProgramArgumentCommandMarshal program_argument_marshal(
cache_backend.get(),
base::CommandLine::StringVector(args.begin() + 2, args.end()));
bool successful_commands = ExecuteCommands(&program_argument_marshal);
base::RunLoop().RunUntilIdle();
cache_backend = nullptr;
disk_cache::FlushCacheThreadForTesting();
base::RunLoop().RunUntilIdle();
return !successful_commands;
}
|