1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/test/url_request/url_request_mock_http_job.h"
6
7 #include "base/files/file_util.h"
8 #include "base/functional/bind.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/task/thread_pool.h"
13 #include "base/threading/thread_restrictions.h"
14 #include "net/base/filename_util.h"
15 #include "net/base/net_errors.h"
16 #include "net/base/url_util.h"
17 #include "net/http/http_response_headers.h"
18 #include "net/url_request/url_request_filter.h"
19 #include "net/url_request/url_request_interceptor.h"
20
21 namespace net {
22
23 namespace {
24
25 const char kMockHostname[] = "mock.http";
26 const base::FilePath::CharType kMockHeaderFileSuffix[] =
27 FILE_PATH_LITERAL(".mock-http-headers");
28
29 class MockJobInterceptor : public URLRequestInterceptor {
30 public:
31 // When |map_all_requests_to_base_path| is true, all request should return the
32 // contents of the file at |base_path|. When |map_all_requests_to_base_path|
33 // is false, |base_path| is the file path leading to the root of the directory
34 // to use as the root of the HTTP server.
MockJobInterceptor(const base::FilePath & base_path,bool map_all_requests_to_base_path)35 MockJobInterceptor(const base::FilePath& base_path,
36 bool map_all_requests_to_base_path)
37 : base_path_(base_path),
38 map_all_requests_to_base_path_(map_all_requests_to_base_path) {}
39
40 MockJobInterceptor(const MockJobInterceptor&) = delete;
41 MockJobInterceptor& operator=(const MockJobInterceptor&) = delete;
42
43 ~MockJobInterceptor() override = default;
44
45 // URLRequestJobFactory::ProtocolHandler implementation
MaybeInterceptRequest(URLRequest * request) const46 std::unique_ptr<URLRequestJob> MaybeInterceptRequest(
47 URLRequest* request) const override {
48 return std::make_unique<URLRequestMockHTTPJob>(
49 request,
50 map_all_requests_to_base_path_ ? base_path_ : GetOnDiskPath(request));
51 }
52
53 private:
GetOnDiskPath(URLRequest * request) const54 base::FilePath GetOnDiskPath(URLRequest* request) const {
55 // Conceptually we just want to "return base_path_ + request->url().path()".
56 // But path in the request URL is in URL space (i.e. %-encoded spaces).
57 // So first we convert base FilePath to a URL, then append the URL
58 // path to that, and convert the final URL back to a FilePath.
59 GURL file_url(FilePathToFileURL(base_path_));
60 std::string url = file_url.spec() + request->url().path();
61 base::FilePath file_path;
62 FileURLToFilePath(GURL(url), &file_path);
63 return file_path;
64 }
65
66 const base::FilePath base_path_;
67 const bool map_all_requests_to_base_path_;
68 };
69
DoFileIO(const base::FilePath & file_path)70 std::string DoFileIO(const base::FilePath& file_path) {
71 base::FilePath header_file =
72 base::FilePath(file_path.value() + kMockHeaderFileSuffix);
73
74 if (!base::PathExists(header_file)) {
75 // If there is no mock-http-headers file, fake a 200 OK.
76 return "HTTP/1.0 200 OK\n";
77 }
78
79 std::string raw_headers;
80 base::ReadFileToString(header_file, &raw_headers);
81 return raw_headers;
82 }
83
84 // For a given file |path| and |scheme|, return the URL served by the
85 // URlRequestMockHTTPJob.
GetMockUrlForScheme(const std::string & path,const std::string & scheme)86 GURL GetMockUrlForScheme(const std::string& path, const std::string& scheme) {
87 return GURL(scheme + "://" + kMockHostname + "/" + path);
88 }
89
90 } // namespace
91
92 // static
AddUrlHandlers(const base::FilePath & base_path)93 void URLRequestMockHTTPJob::AddUrlHandlers(const base::FilePath& base_path) {
94 // Add kMockHostname to URLRequestFilter, for both HTTP and HTTPS.
95 URLRequestFilter* filter = URLRequestFilter::GetInstance();
96 filter->AddHostnameInterceptor("http", kMockHostname,
97 CreateInterceptor(base_path));
98 filter->AddHostnameInterceptor("https", kMockHostname,
99 CreateInterceptor(base_path));
100 }
101
102 // static
GetMockUrl(const std::string & path)103 GURL URLRequestMockHTTPJob::GetMockUrl(const std::string& path) {
104 return GetMockUrlForScheme(path, "http");
105 }
106
107 // static
GetMockHttpsUrl(const std::string & path)108 GURL URLRequestMockHTTPJob::GetMockHttpsUrl(const std::string& path) {
109 return GetMockUrlForScheme(path, "https");
110 }
111
112 // static
CreateInterceptor(const base::FilePath & base_path)113 std::unique_ptr<URLRequestInterceptor> URLRequestMockHTTPJob::CreateInterceptor(
114 const base::FilePath& base_path) {
115 return std::make_unique<MockJobInterceptor>(base_path, false);
116 }
117
118 // static
119 std::unique_ptr<URLRequestInterceptor>
CreateInterceptorForSingleFile(const base::FilePath & file)120 URLRequestMockHTTPJob::CreateInterceptorForSingleFile(
121 const base::FilePath& file) {
122 return std::make_unique<MockJobInterceptor>(file, true);
123 }
124
URLRequestMockHTTPJob(URLRequest * request,const base::FilePath & file_path)125 URLRequestMockHTTPJob::URLRequestMockHTTPJob(URLRequest* request,
126 const base::FilePath& file_path)
127 : URLRequestTestJobBackedByFile(
128 request,
129 file_path,
130 base::ThreadPool::CreateTaskRunner({base::MayBlock()})) {}
131
132 URLRequestMockHTTPJob::~URLRequestMockHTTPJob() = default;
133
134 // Public virtual version.
GetResponseInfo(HttpResponseInfo * info)135 void URLRequestMockHTTPJob::GetResponseInfo(HttpResponseInfo* info) {
136 // Forward to private const version.
137 GetResponseInfoConst(info);
138 }
139
IsRedirectResponse(GURL * location,int * http_status_code,bool * insecure_scheme_was_upgraded)140 bool URLRequestMockHTTPJob::IsRedirectResponse(
141 GURL* location,
142 int* http_status_code,
143 bool* insecure_scheme_was_upgraded) {
144 // Override the URLRequestTestJobBackedByFile implementation to invoke the
145 // default one based on HttpResponseInfo.
146 return URLRequestJob::IsRedirectResponse(location, http_status_code,
147 insecure_scheme_was_upgraded);
148 }
149
OnReadComplete(net::IOBuffer * buffer,int result)150 void URLRequestMockHTTPJob::OnReadComplete(net::IOBuffer* buffer, int result) {
151 if (result >= 0)
152 total_received_bytes_ += result;
153 }
154
155 // Public virtual version.
Start()156 void URLRequestMockHTTPJob::Start() {
157 base::ThreadPool::PostTaskAndReplyWithResult(
158 FROM_HERE, {base::MayBlock()}, base::BindOnce(&DoFileIO, file_path_),
159 base::BindOnce(&URLRequestMockHTTPJob::SetHeadersAndStart,
160 weak_ptr_factory_.GetWeakPtr()));
161 }
162
SetHeadersAndStart(const std::string & raw_headers)163 void URLRequestMockHTTPJob::SetHeadersAndStart(const std::string& raw_headers) {
164 raw_headers_ = raw_headers;
165 // Handle CRLF line-endings.
166 base::ReplaceSubstringsAfterOffset(&raw_headers_, 0, "\r\n", "\n");
167 // ParseRawHeaders expects \0 to end each header line.
168 base::ReplaceSubstringsAfterOffset(
169 &raw_headers_, 0, "\n", base::StringPiece("\0", 1));
170 total_received_bytes_ += raw_headers_.size();
171 URLRequestTestJobBackedByFile::Start();
172 }
173
174 // Private const version.
GetResponseInfoConst(HttpResponseInfo * info) const175 void URLRequestMockHTTPJob::GetResponseInfoConst(HttpResponseInfo* info) const {
176 info->headers = base::MakeRefCounted<HttpResponseHeaders>(raw_headers_);
177 }
178
GetTotalReceivedBytes() const179 int64_t URLRequestMockHTTPJob::GetTotalReceivedBytes() const {
180 return total_received_bytes_;
181 }
182
GetMimeType(std::string * mime_type) const183 bool URLRequestMockHTTPJob::GetMimeType(std::string* mime_type) const {
184 HttpResponseInfo info;
185 GetResponseInfoConst(&info);
186 return info.headers.get() && info.headers->GetMimeType(mime_type);
187 }
188
GetCharset(std::string * charset)189 bool URLRequestMockHTTPJob::GetCharset(std::string* charset) {
190 HttpResponseInfo info;
191 GetResponseInfo(&info);
192 return info.headers.get() && info.headers->GetCharset(charset);
193 }
194
195 } // namespace net
196