1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/tools/quic/quic_in_memory_cache.h"
7 #include "base/file_util.h"
8 #include "base/files/file_enumerator.h"
9 #include "base/stl_util.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "net/tools/balsa/balsa_headers.h"
14 using base::StringPiece;
17 // Specifies the directory used during QuicInMemoryCache
18 // construction to seed the cache. Cache directory can be
19 // generated using `wget -p --save-headers <url>
24 std::string FLAGS_quic_in_memory_cache_dir = "";
28 // BalsaVisitor implementation (glue) which caches response bodies.
29 class CachingBalsaVisitor : public NoOpBalsaVisitor {
31 CachingBalsaVisitor() : done_framing_(false) {}
32 virtual void ProcessBodyData(const char* input, size_t size) OVERRIDE {
33 AppendToBody(input, size);
35 virtual void MessageDone() OVERRIDE {
38 virtual void HandleHeaderError(BalsaFrame* framer) OVERRIDE {
41 virtual void HandleHeaderWarning(BalsaFrame* framer) OVERRIDE {
44 virtual void HandleChunkingError(BalsaFrame* framer) OVERRIDE {
47 virtual void HandleBodyError(BalsaFrame* framer) OVERRIDE {
50 void UnhandledError() {
51 LOG(DFATAL) << "Unhandled error framing HTTP.";
53 void AppendToBody(const char* input, size_t size) {
54 body_.append(input, size);
56 bool done_framing() const { return done_framing_; }
57 const string& body() const { return body_; }
67 QuicInMemoryCache* QuicInMemoryCache::GetInstance() {
68 return Singleton<QuicInMemoryCache>::get();
71 const QuicInMemoryCache::Response* QuicInMemoryCache::GetResponse(
72 const BalsaHeaders& request_headers) const {
73 ResponseMap::const_iterator it = responses_.find(GetKey(request_headers));
74 if (it == responses_.end()) {
80 void QuicInMemoryCache::AddSimpleResponse(StringPiece method,
83 StringPiece response_code,
84 StringPiece response_detail,
86 BalsaHeaders request_headers, response_headers;
87 request_headers.SetRequestFirstlineFromStringPieces(method,
90 response_headers.SetRequestFirstlineFromStringPieces(version,
93 response_headers.AppendHeader("content-length",
94 base::IntToString(body.length()));
96 AddResponse(request_headers, response_headers, body);
99 void QuicInMemoryCache::AddResponse(const BalsaHeaders& request_headers,
100 const BalsaHeaders& response_headers,
101 StringPiece response_body) {
102 LOG(INFO) << "Adding response for: " << GetKey(request_headers);
103 if (ContainsKey(responses_, GetKey(request_headers))) {
104 LOG(DFATAL) << "Response for given request already exists!";
107 Response* new_response = new Response();
108 new_response->set_headers(response_headers);
109 new_response->set_body(response_body);
110 responses_[GetKey(request_headers)] = new_response;
113 QuicInMemoryCache::QuicInMemoryCache() {
117 void QuicInMemoryCache::ResetForTests() {
118 STLDeleteValues(&responses_);
122 void QuicInMemoryCache::Initialize() {
123 // If there's no defined cache dir, we have no initialization to do.
124 if (FLAGS_quic_in_memory_cache_dir.empty()) {
125 LOG(WARNING) << "No cache directory found. Skipping initialization.";
128 LOG(INFO) << "Attempting to initialize QuicInMemoryCache from directory: "
129 << FLAGS_quic_in_memory_cache_dir;
131 FilePath directory(FLAGS_quic_in_memory_cache_dir);
132 base::FileEnumerator file_list(directory,
134 base::FileEnumerator::FILES);
136 FilePath file = file_list.Next();
137 while (!file.empty()) {
138 // Need to skip files in .svn directories
139 if (file.value().find("/.svn/") != std::string::npos) {
140 file = file_list.Next();
144 BalsaHeaders request_headers, response_headers;
146 string file_contents;
147 base::ReadFileToString(file, &file_contents);
150 CachingBalsaVisitor caching_visitor;
152 framer.set_balsa_headers(&response_headers);
153 framer.set_balsa_visitor(&caching_visitor);
154 size_t processed = 0;
155 while (processed < file_contents.length() &&
156 !caching_visitor.done_framing()) {
157 processed += framer.ProcessInput(file_contents.c_str() + processed,
158 file_contents.length() - processed);
161 string response_headers_str;
162 response_headers.DumpToString(&response_headers_str);
163 if (!caching_visitor.done_framing()) {
164 LOG(DFATAL) << "Did not frame entire message from file: " << file.value()
165 << " (" << processed << " of " << file_contents.length()
168 if (processed < file_contents.length()) {
169 // Didn't frame whole file. Assume remainder is body.
170 // This sometimes happens as a result of incompatibilities between
171 // BalsaFramer and wget's serialization of HTTP sans content-length.
172 caching_visitor.AppendToBody(file_contents.c_str() + processed,
173 file_contents.length() - processed);
174 processed += file_contents.length();
177 StringPiece base = file.value();
178 if (response_headers.HasHeader("X-Original-Url")) {
179 base = response_headers.GetHeader("X-Original-Url");
180 response_headers.RemoveAllOfHeader("X-Original-Url");
181 // Remove the protocol so that the string is of the form host + path,
182 // which is parsed properly below.
183 if (StringPieceUtils::StartsWithIgnoreCase(base, "https://")) {
184 base.remove_prefix(8);
185 } else if (StringPieceUtils::StartsWithIgnoreCase(base, "http://")) {
186 base.remove_prefix(7);
189 int path_start = base.find_first_of('/');
190 DCHECK_LT(0, path_start);
191 StringPiece host(base.substr(0, path_start));
192 StringPiece path(base.substr(path_start));
193 if (path[path.length() - 1] == ',') {
194 path.remove_suffix(1);
196 // Set up request headers. Assume method is GET and protocol is HTTP/1.1.
197 request_headers.SetRequestFirstlineFromStringPieces("GET",
200 request_headers.ReplaceOrAppendHeader("host", host);
202 LOG(INFO) << "Inserting 'http://" << GetKey(request_headers)
203 << "' into QuicInMemoryCache.";
205 AddResponse(request_headers, response_headers, caching_visitor.body());
207 file = file_list.Next();
211 QuicInMemoryCache::~QuicInMemoryCache() {
212 STLDeleteValues(&responses_);
215 string QuicInMemoryCache::GetKey(const BalsaHeaders& request_headers) const {
216 StringPiece uri = request_headers.request_uri();
219 host = request_headers.GetHeader("host");
220 } else if (StringPieceUtils::StartsWithIgnoreCase(uri, "https://")) {
221 uri.remove_prefix(8);
222 } else if (StringPieceUtils::StartsWithIgnoreCase(uri, "http://")) {
223 uri.remove_prefix(7);
225 return host.as_string() + uri.as_string();