File: url_request_mock_http_job.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (195 lines) | stat: -rw-r--r-- 6,919 bytes parent folder | download | duplicates (2)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/test/url_request/url_request_mock_http_job.h"

#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/thread_pool.h"
#include "base/threading/thread_restrictions.h"
#include "net/base/filename_util.h"
#include "net/base/net_errors.h"
#include "net/base/url_util.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request_filter.h"
#include "net/url_request/url_request_interceptor.h"

namespace net {

namespace {

const char kMockHostname[] = "mock.http";
const base::FilePath::CharType kMockHeaderFileSuffix[] =
    FILE_PATH_LITERAL(".mock-http-headers");

class MockJobInterceptor : public URLRequestInterceptor {
 public:
  // When |map_all_requests_to_base_path| is true, all request should return the
  // contents of the file at |base_path|. When |map_all_requests_to_base_path|
  // is false, |base_path| is the file path leading to the root of the directory
  // to use as the root of the HTTP server.
  MockJobInterceptor(const base::FilePath& base_path,
                     bool map_all_requests_to_base_path)
      : base_path_(base_path),
        map_all_requests_to_base_path_(map_all_requests_to_base_path) {}

  MockJobInterceptor(const MockJobInterceptor&) = delete;
  MockJobInterceptor& operator=(const MockJobInterceptor&) = delete;

  ~MockJobInterceptor() override = default;

  // URLRequestJobFactory::ProtocolHandler implementation
  std::unique_ptr<URLRequestJob> MaybeInterceptRequest(
      URLRequest* request) const override {
    return std::make_unique<URLRequestMockHTTPJob>(
        request,
        map_all_requests_to_base_path_ ? base_path_ : GetOnDiskPath(request));
  }

 private:
  base::FilePath GetOnDiskPath(URLRequest* request) const {
    // Conceptually we just want to "return base_path_ + request->url().path()".
    // But path in the request URL is in URL space (i.e. %-encoded spaces).
    // So first we convert base FilePath to a URL, then append the URL
    // path to that, and convert the final URL back to a FilePath.
    GURL file_url(FilePathToFileURL(base_path_));
    std::string url = file_url.spec() + request->url().path();
    base::FilePath file_path;
    FileURLToFilePath(GURL(url), &file_path);
    return file_path;
  }

  const base::FilePath base_path_;
  const bool map_all_requests_to_base_path_;
};

std::string DoFileIO(const base::FilePath& file_path) {
  base::FilePath header_file =
      base::FilePath(file_path.value() + kMockHeaderFileSuffix);

  if (!base::PathExists(header_file)) {
    // If there is no mock-http-headers file, fake a 200 OK.
    return "HTTP/1.0 200 OK\n";
  }

  std::string raw_headers;
  base::ReadFileToString(header_file, &raw_headers);
  return raw_headers;
}

// For a given file |path| and |scheme|, return the URL served by the
// URlRequestMockHTTPJob.
GURL GetMockUrlForScheme(const std::string& path, const std::string& scheme) {
  return GURL(scheme + "://" + kMockHostname + "/" + path);
}

}  // namespace

// static
void URLRequestMockHTTPJob::AddUrlHandlers(const base::FilePath& base_path) {
  // Add kMockHostname to URLRequestFilter, for both HTTP and HTTPS.
  URLRequestFilter* filter = URLRequestFilter::GetInstance();
  filter->AddHostnameInterceptor("http", kMockHostname,
                                 CreateInterceptor(base_path));
  filter->AddHostnameInterceptor("https", kMockHostname,
                                 CreateInterceptor(base_path));
}

// static
GURL URLRequestMockHTTPJob::GetMockUrl(const std::string& path) {
  return GetMockUrlForScheme(path, "http");
}

// static
GURL URLRequestMockHTTPJob::GetMockHttpsUrl(const std::string& path) {
  return GetMockUrlForScheme(path, "https");
}

// static
std::unique_ptr<URLRequestInterceptor> URLRequestMockHTTPJob::CreateInterceptor(
    const base::FilePath& base_path) {
  return std::make_unique<MockJobInterceptor>(base_path, false);
}

// static
std::unique_ptr<URLRequestInterceptor>
URLRequestMockHTTPJob::CreateInterceptorForSingleFile(
    const base::FilePath& file) {
  return std::make_unique<MockJobInterceptor>(file, true);
}

URLRequestMockHTTPJob::URLRequestMockHTTPJob(URLRequest* request,
                                             const base::FilePath& file_path)
    : URLRequestTestJobBackedByFile(
          request,
          file_path,
          base::ThreadPool::CreateTaskRunner({base::MayBlock()})) {}

URLRequestMockHTTPJob::~URLRequestMockHTTPJob() = default;

// Public virtual version.
void URLRequestMockHTTPJob::GetResponseInfo(HttpResponseInfo* info) {
  // Forward to private const version.
  GetResponseInfoConst(info);
}

bool URLRequestMockHTTPJob::IsRedirectResponse(
    GURL* location,
    int* http_status_code,
    bool* insecure_scheme_was_upgraded) {
  // Override the URLRequestTestJobBackedByFile implementation to invoke the
  // default one based on HttpResponseInfo.
  return URLRequestJob::IsRedirectResponse(location, http_status_code,
                                           insecure_scheme_was_upgraded);
}

void URLRequestMockHTTPJob::OnReadComplete(net::IOBuffer* buffer, int result) {
  if (result >= 0)
    total_received_bytes_ += result;
}

// Public virtual version.
void URLRequestMockHTTPJob::Start() {
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock()}, base::BindOnce(&DoFileIO, file_path_),
      base::BindOnce(&URLRequestMockHTTPJob::SetHeadersAndStart,
                     weak_ptr_factory_.GetWeakPtr()));
}

void URLRequestMockHTTPJob::SetHeadersAndStart(const std::string& raw_headers) {
  raw_headers_ = raw_headers;
  // Handle CRLF line-endings.
  base::ReplaceSubstringsAfterOffset(&raw_headers_, 0, "\r\n", "\n");
  // ParseRawHeaders expects \0 to end each header line.
  base::ReplaceSubstringsAfterOffset(
      &raw_headers_, 0, "\n", base::StringPiece("\0", 1));
  total_received_bytes_ += raw_headers_.size();
  URLRequestTestJobBackedByFile::Start();
}

// Private const version.
void URLRequestMockHTTPJob::GetResponseInfoConst(HttpResponseInfo* info) const {
  info->headers = base::MakeRefCounted<HttpResponseHeaders>(raw_headers_);
}

int64_t URLRequestMockHTTPJob::GetTotalReceivedBytes() const {
  return total_received_bytes_;
}

bool URLRequestMockHTTPJob::GetMimeType(std::string* mime_type) const {
  HttpResponseInfo info;
  GetResponseInfoConst(&info);
  return info.headers.get() && info.headers->GetMimeType(mime_type);
}

bool URLRequestMockHTTPJob::GetCharset(std::string* charset) {
  HttpResponseInfo info;
  GetResponseInfo(&info);
  return info.headers.get() && info.headers->GetCharset(charset);
}

}  // namespace net