Coverage Report

Created: 2026-10-31 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl_fuzzer/proto_fuzzer/transfer_session.cc
Line
Count
Source
1
/*
2
 * Copyright (C) Max Dymond, <cmeister2@gmail.com>, et al.
3
 *
4
 * SPDX-License-Identifier: curl
5
 */
6
7
/// @file
8
/// @brief Ordered easy-handle and retained-option resource ownership.
9
10
#include "proto_fuzzer/transfer_session.h"
11
12
#include <algorithm>
13
#include <cstddef>
14
#include <cstdint>
15
#include <utility>
16
17
#include "proto_fuzzer/api_lifecycle.h"
18
#include "proto_fuzzer/bounded_anonymous_input_file.h"
19
#include "proto_fuzzer/option_apply.h"
20
#include "proto_fuzzer/request_data.h"
21
#include "proto_fuzzer/scenario_limits.h"
22
23
namespace proto_fuzzer {
24
namespace {
25
26
constexpr char kDevNullPath[] = "/dev/null";
27
constexpr char kAltSvcOrigin[] = "altsvc-origin.test";
28
constexpr char kAltSvcLoopbackResolve[] = "*:80:127.0.1.127";
29
30
/// Fail closed before any resolver backend starts ambient DNS work.
31
37
int AbortUnexpectedAltSvcResolve(void*, void*, void*) { return 1; }
32
33
929
bool HasCanonicalAltSvcAuthority(const std::string& host_path) {
34
929
  const std::size_t host_size = sizeof(kAltSvcOrigin) - 1;
35
929
  return host_path.compare(0, host_size, kAltSvcOrigin) == 0 &&
36
929
         (host_path.size() == host_size || host_path[host_size] == '/' || host_path[host_size] == '?' ||
37
15
          host_path[host_size] == '#');
38
929
}
39
40
/// Repeat fixed-target bounds for direct runtime and compatibility callers.
41
void PrepareInputFile(const std::string& contents, std::size_t* remaining_bytes, BoundedAnonymousInputFile* input_file,
42
127k
                      bool guard_netrc = false) {
43
127k
  const std::size_t size = std::min(contents.size(), std::min(scenario_limits::kMaxFileInputBytes, *remaining_bytes));
44
127k
  if (size == 0) {
45
109k
    return;
46
109k
  }
47
17.5k
  if (guard_netrc) {
48
    // Retain a parser-neutral newline when curl's loader drops comment lines.
49
    // Charge only protobuf bytes to the shared budget, as before.
50
6.09k
    std::string guarded_contents(1, '\n');
51
6.09k
    guarded_contents.append(contents.data(), size);
52
6.09k
    if (input_file->Write(reinterpret_cast<const std::uint8_t*>(guarded_contents.data()), guarded_contents.size())) {
53
6.09k
      *remaining_bytes -= size;
54
6.09k
    }
55
11.4k
  } else if (input_file->Write(reinterpret_cast<const std::uint8_t*>(contents.data()), size)) {
56
11.4k
    *remaining_bytes -= size;
57
11.4k
  }
58
17.5k
}
59
60
}  // namespace
61
62
/// Anonymous files are allocated only for file-backed lanes and survive easy
63
/// cleanup.
64
struct TransferSession::ParserInputs {
65
  BoundedAnonymousInputFile file_source{scenario_limits::kMaxFileInputBytes};
66
  BoundedAnonymousInputFile cookie{scenario_limits::kMaxFileInputBytes};
67
  BoundedAnonymousInputFile altsvc{scenario_limits::kMaxFileInputBytes};
68
  BoundedAnonymousInputFile hsts{scenario_limits::kMaxFileInputBytes};
69
  BoundedAnonymousInputFile netrc{scenario_limits::kMaxFileInputBytes + 1};
70
  BoundedAnonymousInputFile crl{scenario_limits::kMaxFileInputBytes};
71
};
72
73
384k
TransferSession::TransferSession() = default;
74
384k
TransferSession::~TransferSession() { Close(); }
75
76
/// Allocate the easy lazily so unused concurrent-transfer slots stay empty.
77
/// @return Whether the session has a usable easy handle.
78
369k
bool TransferSession::Initialize() {
79
369k
  if (!easy_) {
80
369k
    easy_.reset(curl_easy_init());
81
369k
  }
82
369k
  return easy_ != nullptr;
83
369k
}
84
85
/// Borrow the owned easy; callers must not clean it themselves.
86
/// @return Easy handle, or nullptr before successful initialization.
87
900k
CURL* TransferSession::easy() const { return easy_.get(); }
88
89
/// Apply baseline options and retain their CONNECT_TO storage.
90
/// @param scenario Transfer whose scheme, trace_ids, and trace_config select the
91
///                 peer allowlist and trace configuration.
92
369k
void TransferSession::ApplyBaseline(const curl::fuzzer::proto::Scenario& scenario) {
93
369k
  if (easy_) {
94
    // Apply the new pointer before releasing the previous list.
95
369k
    connect_to_ = ApplyBaselineOptions(easy_.get(), scenario.scheme(), scenario.trace_ids(), scenario.trace_config());
96
369k
  }
97
369k
}
98
99
/// Reset pre-transfer configuration while preserving prepared parser files.
100
/// @return False if request or API callback state has already been installed.
101
2.42k
bool TransferSession::ResetConfiguration() {
102
2.42k
  if (!easy_ || request_data_ || api_lifecycle_) {
103
0
    return false;
104
0
  }
105
2.42k
  curl_easy_reset(easy_.get());
106
2.42k
  connect_to_.reset();
107
2.42k
  altsvc_resolve_.reset();
108
2.42k
  return true;
109
2.42k
}
110
111
/// Copy bounded parser inputs into lazily allocated anonymous files.
112
/// @param scenario Source of parser-file bytes; not retained.
113
/// @param mode Select the FILE source or deep HTTP/TLS parser inputs.
114
/// @return False after easy initialization, when paths may be retained.
115
312k
bool TransferSession::PrepareInputFiles(const curl::fuzzer::proto::Scenario& scenario, ScenarioRunMode mode) {
116
312k
  if (easy_) {
117
0
    return false;
118
0
  }
119
312k
  if (mode != ScenarioRunMode::kFileCoverage && mode != ScenarioRunMode::kDeepHttpCoverage &&
120
286k
      mode != ScenarioRunMode::kTlsCoverage) {
121
245k
    return true;
122
245k
  }
123
66.4k
  parser_inputs_ = std::make_unique<ParserInputs>();
124
66.4k
  if (mode == ScenarioRunMode::kFileCoverage) {
125
4.13k
    const std::size_t size = std::min(scenario.file_source().size(), scenario_limits::kMaxFileInputBytes);
126
4.13k
    return parser_inputs_->file_source.Write(reinterpret_cast<const std::uint8_t*>(scenario.file_source().data()),
127
4.13k
                                             size);
128
4.13k
  }
129
62.2k
  std::size_t remaining_bytes = scenario_limits::kMaxFileInputTotalBytes;
130
62.2k
  if (mode == ScenarioRunMode::kDeepHttpCoverage) {
131
21.5k
    PrepareInputFile(scenario.cookie_file(), &remaining_bytes, &parser_inputs_->cookie);
132
21.5k
    PrepareInputFile(scenario.altsvc_file(), &remaining_bytes, &parser_inputs_->altsvc);
133
21.5k
    PrepareInputFile(scenario.hsts_file(), &remaining_bytes, &parser_inputs_->hsts);
134
21.5k
    PrepareInputFile(scenario.netrc_file(), &remaining_bytes, &parser_inputs_->netrc, true);
135
40.6k
  } else {
136
40.6k
    PrepareInputFile(scenario.crl_file(), &remaining_bytes, &parser_inputs_->crl);
137
40.6k
  }
138
62.2k
  return true;
139
66.4k
}
140
141
/// Return the pathname of the prepared FILE source/sink. The path names only
142
/// a descriptor owned by this session and is unavailable in every other lane.
143
/// @return Stable `/proc/self/fd/N` path, or nullptr without a ready source.
144
4.08k
const char* TransferSession::FileSourcePath() const {
145
4.08k
  return parser_inputs_ ? parser_inputs_->file_source.path() : nullptr;
146
4.08k
}
147
148
/// Apply prepared parser paths after baseline and peer installation.
149
313k
void TransferSession::ApplyInputFiles() {
150
313k
  if (!easy_ || !parser_inputs_) {
151
247k
    return;
152
247k
  }
153
66.2k
  if (const char* path = parser_inputs_->cookie.path()) {
154
6.63k
    (void)curl_easy_setopt(easy_.get(), CURLOPT_COOKIEFILE, path);
155
6.63k
  }
156
  // Alt-Svc/HSTS use one option for input and cleanup output. Load first,
157
  // then restore the fixed sink; both loaders retain earlier file entries.
158
66.2k
  if (const char* path = parser_inputs_->altsvc.path()) {
159
929
    (void)curl_easy_setopt(easy_.get(), CURLOPT_ALTSVC, path);
160
929
    (void)curl_easy_setopt(easy_.get(), CURLOPT_ALTSVC, kDevNullPath);
161
929
  }
162
66.2k
  if (const char* path = parser_inputs_->hsts.path()) {
163
1.94k
    (void)curl_easy_setopt(easy_.get(), CURLOPT_HSTS, path);
164
1.94k
    (void)curl_easy_setopt(easy_.get(), CURLOPT_HSTS, kDevNullPath);
165
1.94k
  }
166
66.2k
  if (const char* path = parser_inputs_->netrc.path()) {
167
6.09k
    (void)curl_easy_setopt(easy_.get(), CURLOPT_NETRC_FILE, path);
168
6.09k
    (void)curl_easy_setopt(easy_.get(), CURLOPT_NETRC, CURL_NETRC_REQUIRED);
169
6.09k
  }
170
66.2k
  if (const char* path = parser_inputs_->crl.path()) {
171
1.89k
    (void)curl_easy_setopt(easy_.get(), CURLOPT_CRLFILE, path);
172
1.89k
  }
173
66.2k
}
174
175
/// Enable isolated Alt-Svc routing for the canonical deep-HTTP authority.
176
/// @param host_path Scenario URL authority/path used by this transfer.
177
311k
void TransferSession::ConfigureAltSvcRouting(const std::string& host_path) {
178
311k
  if (!easy_ || !parser_inputs_ || parser_inputs_->altsvc.path() == nullptr ||
179
310k
      !HasCanonicalAltSvcAuthority(host_path)) {
180
310k
    return;
181
310k
  }
182
929
  CurlSlistPtr resolve(curl_slist_append(nullptr, kAltSvcLoopbackResolve));
183
929
  if (!resolve || curl_easy_setopt(easy_.get(), CURLOPT_RESOLVE, resolve.get()) != CURLE_OK) {
184
9
    return;
185
9
  }
186
  // Adopt only after installation; failures leave the previous list alive.
187
920
  altsvc_resolve_ = std::move(resolve);
188
920
  if (curl_easy_setopt(easy_.get(), CURLOPT_RESOLVER_START_FUNCTION, &AbortUnexpectedAltSvcResolve) == CURLE_OK) {
189
    // CONNECT_TO takes precedence over Alt-Svc. Only detach it when the
190
    // wildcard host cache and fail-closed resolver callback are installed.
191
920
    (void)curl_easy_setopt(easy_.get(), CURLOPT_CONNECT_TO, nullptr);
192
920
  }
193
920
}
194
195
/// Install owned request attachments. The Scenario remains borrowed.
196
/// @param scenario Live, unmodified source until session teardown.
197
/// @param apply_resolve_entries Install resolver-lane mappings.
198
/// @return Request owner, or nullptr without an easy or if already installed.
199
ScenarioRequestData* TransferSession::InstallRequestData(const curl::fuzzer::proto::Scenario& scenario,
200
367k
                                                         bool apply_resolve_entries) {
201
367k
  if (!easy_ || request_data_) {
202
0
    return nullptr;
203
0
  }
204
367k
  request_data_.emplace(easy_.get(), scenario, apply_resolve_entries);
205
367k
  return &*request_data_;
206
367k
}
207
208
/// Install API/share state that survives easy cleanup.
209
/// @param plan Live plan until session teardown.
210
/// @param url URL used only during lifecycle construction.
211
/// @return Lifecycle owner, or nullptr if absent/already installed.
212
7.92k
ApiLifecycle* TransferSession::InstallApiLifecycle(const curl::fuzzer::proto::ApiPlan& plan, std::string_view url) {
213
7.92k
  if (!easy_ || api_lifecycle_) {
214
0
    return nullptr;
215
0
  }
216
7.92k
  api_lifecycle_ = std::make_unique<ApiLifecycle>(easy_.get(), plan, url);
217
7.92k
  return api_lifecycle_.get();
218
7.92k
}
219
220
/// Release all resources in their required order. Safe to call repeatedly.
221
441k
void TransferSession::Close() {
222
441k
  request_data_.reset();
223
441k
  easy_.reset();
224
441k
  api_lifecycle_.reset();
225
441k
  altsvc_resolve_.reset();
226
441k
  connect_to_.reset();
227
441k
  parser_inputs_.reset();
228
441k
}
229
230
}  // namespace proto_fuzzer