fix(fetch): preserve browser transport semantics across main updates

Adapt shared request bodies, redirect handling and per-transfer response progress to the updated fetch APIs. Keep decoding correct with the new curl build, including encoded-byte accounting, cache timing and dictionary readability.

Vendor curl-sys at the existing curl-rust revision to retain tested browser TLS EOF handling without downgrading main. Keep native body teardown test consumers with the updated helper and isolate the full compressed timing matrix by scenario.
This commit is contained in:
ldm0
2026-11-20 22:47:54 +08:00
parent 637b6cf739
commit 2bc23fc3c3
436 changed files with 189193 additions and 159 deletions
Generated
+1 -1
View File
@@ -2963,9 +2963,9 @@ name = "moli-fetch"
version = "0.1.0"
dependencies = [
"anyhow",
"bytes",
"base64 0.22.1",
"brotlic-sys",
"bytes",
"cidr",
"crossbeam-channel",
"curl",
+4 -1
View File
@@ -124,7 +124,7 @@ url = { path = "vendor/url-2.5.8" }
html5ever = { path = "vendor/html5ever-0.40.1" }
xml5ever = { git = "https://github.com/lexmount/html5ever", rev = "4574311c63e79bba7d4ddb98cb0562d8dad499ee" }
curl = { git = "https://github.com/lexmount/curl-rust", rev = "0392e12475d8d1160d4cae07c172cac02797cc25" }
curl-sys = { git = "https://github.com/lexmount/curl-rust", rev = "0392e12475d8d1160d4cae07c172cac02797cc25" }
curl-sys = { path = "vendor/curl-sys-0.4.91" }
cookie = { git = "https://github.com/ldm0/cookie-rs", branch = "priority" }
v8 = { path = "vendor/v8-152.2.0" }
deno_v8 = { path = "vendor/deno_v8-0.3.0" }
@@ -163,3 +163,6 @@ codegen-units = 1
[profile.test]
debug = 1
[patch."https://github.com/lexmount/curl-rust"]
curl-sys = { path = "vendor/curl-sys-0.4.91" }
+7
View File
@@ -93,6 +93,13 @@ impl ResponseProgress {
timing.body_bytes_received |= bytes > 0;
}
pub(crate) fn record_encoded_response_body_chunk(&self, bytes: usize) {
let mut timing = self.inner.timing.lock();
let sizes = timing.body_sizes.get_or_insert_with(Default::default);
sizes.encoded = sizes.encoded.saturating_add(bytes as u64);
timing.body_bytes_received |= bytes > 0;
}
pub(crate) fn record_decoded_response_body_size(&self, bytes: usize) {
let mut timing = self.inner.timing.lock();
let sizes = timing.body_sizes.get_or_insert_with(Default::default);
@@ -2,7 +2,6 @@
//! requests which may use them. Bytes enter the store only after a readable
//! response completes; a header alone cannot register a dictionary.
mod decoding;
mod fields;
use std::{borrow::Cow, collections::VecDeque, fmt, io::Read, sync::Arc};
@@ -17,7 +16,6 @@ use url::Url;
use crate::{FetchConfig, Request, RequestMode};
pub(crate) use decoding::DictionaryDecoding;
pub(crate) use fields::RegistrationOptions;
const MAX_DICTIONARY_BYTES: usize = 64 * 1024 * 1024;
@@ -392,18 +390,6 @@ impl DictionaryResponse {
}
}
pub(crate) fn headers(&self) -> &[(String, Vec<u8>)] {
&self.headers
}
pub(crate) fn headers_finalized(&self) -> bool {
self.headers_finalized
}
pub(crate) fn bodyless(&self) -> bool {
self.request.head || matches!(self.status, 204 | 205 | 304)
}
pub(crate) fn from_cached(
store: SharedDictionaryStore,
request: &Request,
+2
View File
@@ -1,6 +1,8 @@
use moli_header_field::{HeaderFieldTokenMode, HeaderFieldTokenizer};
fn supported_content_codings() -> impl Iterator<Item = &'static str> {
// The bounded native decoder supplies the same coding set even when the
// linked libcurl lacks Zstandard or external-dictionary support.
["deflate", "gzip", "br", "zstd", "dcb", "dcz"].into_iter()
}
@@ -1,6 +1,6 @@
//! Decode response content with the linked Brotli/zlib/Zstandard libraries.
//! The same stack validates completion and counts wire bytes for ordinary and
//! dictionary-compressed responses, independently of libcurl's decoder build.
//! Bounded content decoding shared by ordinary and dictionary responses.
//! Linked zlib, Brotli and Zstandard decoders validate every negotiated response,
//! including completion, independently of the libcurl build configuration.
use std::{
ffi::c_void,
@@ -11,41 +11,68 @@ use std::{
use anyhow::{Result, anyhow, bail, ensure};
use flate2::{Decompress, FlushDecompress, Status};
use super::Dictionary;
use crate::{Request, compression_dictionary::Dictionary};
const OUTPUT_SIZE: usize = 16 * 1024;
type Output<'a> = dyn FnMut(&[u8]) -> Result<()> + 'a;
pub(crate) struct DictionaryDecoding {
pub(crate) struct ContentDecoding {
dictionary: Option<Arc<Dictionary>>,
stages: Option<Vec<Stage>>,
pub(crate) encoded_bytes: u64,
head: bool,
status: u16,
headers: Vec<(String, Vec<u8>)>,
headers_finalized: bool,
}
impl DictionaryDecoding {
pub(crate) fn new(dictionary: Option<Arc<Dictionary>>) -> Self {
impl ContentDecoding {
pub(crate) fn new(request: &Request) -> Self {
Self {
dictionary,
dictionary: request.compression_dictionary.clone(),
stages: None,
encoded_bytes: 0,
head: request.method == "HEAD",
status: 0,
headers: Vec::new(),
headers_finalized: false,
}
}
pub(crate) fn reset(&mut self) {
self.stages = None;
self.encoded_bytes = 0;
pub(crate) fn header(&mut self, data: &[u8]) -> Result<()> {
if let Some(line) = crate::response::parse_http_response_status_line(data) {
self.status = line.status;
self.headers.clear();
self.stages = None;
self.headers_finalized = false;
return Ok(());
}
if self.headers_finalized {
return Ok(());
}
if let Some(header) = crate::headers::parse_http_response_header_line(data) {
self.headers.push(header);
return Ok(());
}
if self.status >= 200 && data.iter().all(|byte| matches!(byte, b'\r' | b'\n')) {
self.headers_finalized = true;
}
Ok(())
}
pub(crate) fn uses_dictionary(&self) -> bool {
self.dictionary.is_some()
pub(crate) fn needs_readable_dictionary_response(&self) -> bool {
self.dictionary.is_some() && self.headers_finalized && !self.bodyless()
}
pub(crate) fn initialize(&mut self, headers: &[(String, Vec<u8>)]) -> Result<()> {
fn bodyless(&self) -> bool {
self.head || matches!(self.status, 204 | 205 | 304)
}
fn initialize(&mut self) -> Result<()> {
if self.stages.is_some() {
return Ok(());
}
let mut names = Vec::new();
for (_, value) in headers
for (_, value) in self
.headers
.iter()
.filter(|(name, _)| name.eq_ignore_ascii_case("content-encoding"))
{
@@ -67,9 +94,9 @@ impl DictionaryDecoding {
"zstd" => Stage::Zstd(Zstd::new(None)?),
"dcb" | "dcz" => Stage::Dictionary {
brotli: name == "dcb",
dictionary: Arc::clone(self.dictionary.as_ref().ok_or_else(|| {
anyhow!("dictionary compression without a negotiated dictionary")
})?),
dictionary: self.dictionary.clone().ok_or_else(|| {
anyhow!("dictionary content encoding without a selected dictionary")
})?,
prefix: Vec::new(),
decoder: None,
},
@@ -83,9 +110,10 @@ impl DictionaryDecoding {
pub(crate) fn push(&mut self, input: &[u8], output: &mut Output<'_>) -> Result<()> {
ensure!(
self.stages.is_some(),
self.headers_finalized,
"compressed response body arrived before headers"
);
self.initialize()?;
feed(
self.stages.as_mut().expect("initialized decoding stack"),
input,
@@ -93,16 +121,12 @@ impl DictionaryDecoding {
)
}
pub(crate) fn finish(&mut self, headers: &[(String, Vec<u8>)], bodyless: bool) -> Result<()> {
if bodyless {
pub(crate) fn finish(&mut self) -> Result<()> {
// An empty encoded body never invokes a decoder, including for an
// unknown coding. A decoder that received bytes must finish cleanly.
if self.bodyless() || self.stages.is_none() {
return Ok(());
}
// An empty payload never enters a content decoder. HEAD and null-body
// responses likewise do not validate an unused coding declaration.
if self.encoded_bytes == 0 {
return Ok(());
}
self.initialize(headers)?;
for stage in self.stages.as_ref().expect("initialized decoding stack") {
ensure!(stage.finished(), "truncated compressed response");
}
+1
View File
@@ -12,6 +12,7 @@ mod client_hints;
mod compression_dictionary;
mod config;
mod content_coding;
mod content_decoding;
mod cors;
mod cross_origin_resource_policy;
mod dns;
+44 -56
View File
@@ -1559,19 +1559,12 @@ impl RuntimeOwner {
state: &mut OwnerState,
mut completion: RuntimeCurlCompletion,
) {
let cancelled = match &completion.context {
ActiveTransferContext::Buffered(context) => context.job.cancel_handle.is_cancelled(),
ActiveTransferContext::Streaming(context) => context.job.cancel_handle.is_cancelled(),
ActiveTransferContext::StreamingRaw(context) => {
context.job.cancel_handle.is_cancelled()
}
};
if let Some(easy) = completion.easy.as_mut() {
if let Some(error) = easy.get_mut().dictionary_error.take() {
if let Some(error) = easy.get_mut().content_decoding_error.take() {
completion.result = Err(anyhow!(error));
} else if completion.result.is_ok()
&& !self.shutdown_requested.load(Ordering::SeqCst)
&& !cancelled
&& !completion.context.is_cancelled()
{
completion.result = easy.get_mut().finish_dictionary_response();
}
@@ -2887,6 +2880,14 @@ enum ActiveTransferContext {
}
impl ActiveTransferContext {
fn is_cancelled(&self) -> bool {
match self {
Self::Buffered(context) => context.job.cancel_handle.is_cancelled(),
Self::Streaming(context) => context.job.cancel_handle.is_cancelled(),
Self::StreamingRaw(context) => context.job.cancel_handle.is_cancelled(),
}
}
fn into_buffered(self) -> Option<ActiveBufferedTransferContext> {
match self {
Self::Buffered(context) => Some(*context),
@@ -2941,8 +2942,8 @@ pub(crate) struct FetchTransferHandler {
upload_observer: Option<crate::UploadObserver>,
proxy_connect_response_recorder: ProxyConnectResponseRecorder,
dictionary_response: Option<crate::compression_dictionary::DictionaryResponse>,
dictionary_decoding: Option<crate::compression_dictionary::DictionaryDecoding>,
dictionary_error: Option<String>,
content_decoding: Option<crate::content_decoding::ContentDecoding>,
content_decoding_error: Option<String>,
}
enum FetchResponseCollector {
@@ -2989,8 +2990,8 @@ impl FetchTransferHandler {
upload_observer: None,
proxy_connect_response_recorder: ProxyConnectResponseRecorder::default(),
dictionary_response: None,
dictionary_decoding: None,
dictionary_error: None,
content_decoding: None,
content_decoding_error: None,
}
}
@@ -3057,20 +3058,17 @@ impl FetchTransferHandler {
url.clone(),
)
});
self.dictionary_decoding = Some(crate::compression_dictionary::DictionaryDecoding::new(
request.compression_dictionary.clone(),
));
self.dictionary_error = None;
self.content_decoding = Some(crate::content_decoding::ContentDecoding::new(request));
self.content_decoding_error = None;
}
fn finish_dictionary_response(&mut self) -> Result<()> {
let Some(response) = self.dictionary_response.as_mut() else {
return Ok(());
};
if let Some(decoding) = self.dictionary_decoding.as_mut() {
decoding.finish(response.headers(), response.bodyless())?;
if let Some(decoding) = self.content_decoding.as_mut() {
decoding.finish()?;
}
if let Some(response) = self.dictionary_response.as_mut() {
response.finish();
}
response.finish();
Ok(())
}
@@ -3108,7 +3106,7 @@ impl Handler for FetchTransferHandler {
if !data.is_empty() {
self.mark_response_body_received();
}
if self.dictionary_decoding.is_none() {
if self.content_decoding.is_none() {
if let Some(timing) = self.response_progress() {
timing.record_decoded_response_body_size(data.len());
}
@@ -3126,24 +3124,13 @@ impl Handler for FetchTransferHandler {
}
return result;
}
if self.dictionary_error.is_some() {
return Ok(0);
}
let timing = self.response_progress().cloned();
let decoding = self
.dictionary_decoding
.as_mut()
.expect("content decoding selected");
decoding.encoded_bytes = decoding.encoded_bytes.saturating_add(data.len() as u64);
// A decoding failure can abort write before curl reports progress.
// Count the wire bytes at this boundary when we own content decoding.
if let Some(timing) = &timing {
timing.record_encoded_response_body_size(decoding.encoded_bytes);
timing.record_encoded_response_body_chunk(data.len());
}
if let Err(error) = decoding.initialize(
self.dictionary_response
.as_ref()
.map_or(&[], |response| response.headers()),
) {
self.dictionary_error = Some(error.to_string());
if self.content_decoding_error.is_some() {
return Ok(0);
}
let policy = &mut self.dictionary_response;
@@ -3168,14 +3155,14 @@ impl Handler for FetchTransferHandler {
Ok(())
};
let result = self
.dictionary_decoding
.content_decoding
.as_mut()
.expect("dictionary decoding selected")
.expect("native content decoding selected")
.push(data, &mut output);
match result {
Ok(()) => Ok(data.len()),
Err(error) => {
self.dictionary_error = Some(error.to_string());
self.content_decoding_error = Some(error.to_string());
Ok(0)
}
}
@@ -3184,24 +3171,24 @@ impl Handler for FetchTransferHandler {
fn header(&mut self, data: &[u8]) -> bool {
if crate::response::parse_http_response_status_line(data)
.is_some_and(|line| line.status >= 200)
&& let Some(decoding) = self.dictionary_decoding.as_mut()
{
decoding.reset();
self.dictionary_error = None;
self.content_decoding_error = None;
}
if let Some(response) = self.dictionary_response.as_mut() {
response.header(data);
}
if data.iter().all(|byte| matches!(byte, b'\r' | b'\n'))
&& let Some(response) = self.dictionary_response.as_ref()
&& response.headers_finalized()
&& !response.bodyless()
&& let Some(decoding) = self.dictionary_decoding.as_mut()
&& decoding.uses_dictionary()
&& !response.readable()
{
self.dictionary_error =
Some("dictionary response failed its CORS readability check".to_owned());
if let Some(decoding) = self.content_decoding.as_mut() {
if let Err(error) = decoding.header(data) {
self.content_decoding_error = Some(error.to_string());
} else if decoding.needs_readable_dictionary_response()
&& self
.dictionary_response
.as_ref()
.is_none_or(|response| !response.readable())
{
self.content_decoding_error =
Some("dictionary response failed its CORS readability check".to_owned());
}
}
if crate::response::parse_http_response_status_line(data)
.is_some_and(|line| line.status >= 200)
@@ -3223,7 +3210,8 @@ impl Handler for FetchTransferHandler {
if dlnow > 0.0 {
self.mark_response_body_received();
}
if dlnow > 0.0
if self.content_decoding.is_none()
&& dlnow > 0.0
&& let Some(timing) = self.response_progress()
{
timing.record_encoded_response_body_size(dlnow as u64);
@@ -14,13 +14,12 @@ async fn cache_only_requests_preserve_cancellation_before_local_completion() ->
for follow_redirects in [true, false] {
let cancel = FetchCancelHandle::new();
cancel.cancel();
let request = controlled(&server.url(), "only-if-cached")?.with_redirect_handling(
if follow_redirects {
crate::RequestRedirectHandling::Follow
} else {
crate::RequestRedirectHandling::FollowByCaller
},
);
let request = controlled(&server.url(), "only-if-cached")?;
let request = if follow_redirects {
request
} else {
request.with_single_hop()
};
let error = client
.fetch_with_cancel(request, cancel)
.await
@@ -56,11 +55,11 @@ async fn cache_only_misses_never_contact_origin_on_raw_text_html_or_buffered_pat
response.head()
}
1 | 2 => {
let request = request.with_redirect_handling(if path == 1 {
crate::RequestRedirectHandling::Follow
let request = if path == 1 {
request
} else {
crate::RequestRedirectHandling::FollowByCaller
});
request.with_single_hop()
};
let observed = client
.fetch_with_cancel_and_network_metadata(request, cancel.clone())
.await?;
@@ -249,11 +248,7 @@ async fn disk_cache_only_redirects_stop_at_uncached_hops_without_network() -> Re
let mut config = FetchConfig::default();
config.set_http_cache_dir(Some(cache_dir.display().to_string()));
let client = FetchClient::new(&config, new_shared_browser_cookie_store());
let prime = Request::get(&server.url())?.with_redirect_handling(if false {
crate::RequestRedirectHandling::Follow
} else {
crate::RequestRedirectHandling::FollowByCaller
});
let prime = Request::get(&server.url())?.with_single_hop();
assert_eq!(client.fetch_raw(prime).await?.status, 302);
let request = controlled(&server.url(), "only-if-cached")?;
let head = if html {
+5 -5
View File
@@ -3,15 +3,15 @@ use crate::{UploadEvent, UploadObserver};
async fn upload_response(
client: &FetchClient,
mut request: Request,
request: Request,
transport: &str,
cancel: FetchCancelHandle,
) -> Result<u16> {
match transport {
"buffered" => {
request = request.with_single_hop();
Ok(client.fetch_with_cancel(request, cancel).await?.status)
}
"buffered" => Ok(client
.fetch_with_cancel(request.with_single_hop(), cancel)
.await?
.status),
"html" => {
let mut response = client.fetch_html_stream(request).await?;
while response.next_chunk().await.is_some() {}
@@ -1016,7 +1016,7 @@ fn raw_subresource_request_is_memory_cacheable(
// A CORS-managed hop carries the logical request's earlier URLs. It
// can cache this hop without treating the prefix as a followed
// transport redirect; its origin/credential taint is part of the key.
&& (request.redirect_chain().is_empty() || !request.follow_redirects)
&& (request.redirect_chain().is_empty() || !request.transport_follows_redirects())
&& raw_subresource_memory_cacheable_resource_type(request)
&& request.method.eq_ignore_ascii_case("GET")
&& request.body.is_none()
@@ -1491,7 +1491,7 @@ mod tests {
.with_request_origin((&initiator).into())
.with_initiator_url(&initiator);
let per_hop = automatic.clone().with_single_hop();
let key = raw_subresource_memory_cache_key(&per_hop, per_hop.headers())
let key = raw_subresource_memory_cache_key(&per_hop, &per_hop.request_headers)
.expect("cacheable first CORS hop");
let mut cache = SharedMemoryResourceCache::with_limits(usize::MAX, usize::MAX);
cache.insert_raw_subresource(
@@ -1270,7 +1270,7 @@ impl ResourceRequestClient {
));
}
if response.status == 304
&& (!response.redirected || !request.follow_redirects)
&& (!response.redirected || !request.transport_follows_redirects())
&& response.final_url == request.url
&& let Some(cached) = cached
{
@@ -1358,7 +1358,7 @@ impl ResourceRequestClient {
let (body_tx, body_rx) = tokio::sync::mpsc::unbounded_channel();
let (completion_tx, completion_rx) = tokio::sync::oneshot::channel();
let resource_runtime = self.resource_runtime.clone();
let outward_cancel = FetchCancelHandle::new();
let outward_cancel = response.cancellation_handle().child_for_subrequest();
response.share_response_progress(&outward_cancel);
tokio::spawn(async move {
let mut body = Vec::new();
@@ -1396,7 +1396,7 @@ impl ResourceRequestClient {
if completion.as_ref().is_some_and(Result::is_ok) {
let mut materialized = RawResponse::from_head_and_body(response.head(), body)
.with_body_sizes(response.response_timing().body_sizes());
if !request.follow_redirects {
if !request.transport_follows_redirects() {
// The outer CORS loop owns the logical redirect history.
// Retain only this hop's representation, then let each
// consumer attach its own already-validated URL list.
@@ -231,7 +231,7 @@ async fn raw_memory_cache_only_redirects_stop_at_uncached_targets() -> Result<()
// Prime the complete redirect representation independently. The browser
// redirect loop may drop an unread body before its cache tee completes.
assert_eq!(
fetch(&client, request().with_follow_redirects(false), false)
fetch(&client, request().with_single_hop(), false)
.await?
.0
.status,
@@ -1000,7 +1000,6 @@ async fn fetch_response_head_once(
.map(|response| response.head());
}
let cancel_handle = cancel_handle.unwrap_or_default();
let response = loader
.fetch_raw_stream_with_cancel(request, cancel_handle)
.await
@@ -1247,6 +1246,7 @@ mod tests {
redirect_chain: Vec::new(),
from_cache: false,
cache_state: Default::default(),
preload_state: Default::default(),
negotiated_http_version: None,
},
None,
@@ -60,7 +60,7 @@ async fn handle_timing_request(
if url.path() == "/compressed-worker.js" {
let body = r#"self.onmessage = async event => {
const probe = (0, eval)('(' + event.data.source + ')');
postMessage(await probe(event.data.origins, event.data.label));
postMessage(await probe(event.data.origins, event.data.label, event.data.filter));
close();
};"#;
let head = format!(
@@ -399,14 +399,23 @@ fn xhr_resource_timing_reads_internal_headers_before_cors_exposure() {
}
async fn run_resource_timing_fixture(fixture: &str, expected_total: usize) {
run_resource_timing_fixture_scenario(fixture, expected_total, None).await;
}
async fn run_resource_timing_fixture_scenario(
fixture: &str,
expected_total: usize,
scenario: Option<&serde_json::Value>,
) -> serde_json::Value {
let first = timing_server().await;
let second = timing_server().await;
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
let mut page =
new_storage_page_task_executor_test_vm_with_loader(&format!("{}/", first.origin), &loader);
page.eval(&format!(
"globalThis.__fetchOrigins = {}; globalThis.__fetchTimingResult = null;",
"globalThis.__fetchOrigins = {}; globalThis.__fetchTimingResult = null;globalThis.__compressedTimingScenario = {};",
serde_json::to_string(&[&first.origin, &second.origin]).unwrap(),
serde_json::to_string(&scenario).unwrap(),
))
.unwrap();
page.eval(&format!(
@@ -426,13 +435,58 @@ async fn run_resource_timing_fixture(fixture: &str, expected_total: usize) {
.unwrap_or_else(|error| panic!("fetch timing probe returned {result:?}: {error}"));
assert_eq!(result["total"], expected_total);
assert_eq!(result["failures"], serde_json::json!([]));
result
}
#[tokio::test(flavor = "current_thread")]
async fn compressed_resource_timing_sizes_survive_window_child_worker_and_memory_cache() {
run_resource_timing_fixture(
include_str!("../../../tests/fixtures/compressed-request-resource-timing.js"),
let mut names = std::collections::BTreeSet::new();
for realm in ["window", "child", "worker"] {
let apis = if realm == "worker" {
["fetch", "xhr", "sync-xhr"].as_slice()
} else {
["fetch", "xhr"].as_slice()
};
for api in apis {
let modes = if *api == "fetch" {
[
"same",
"cors",
"cors-tao",
"denied",
"opaque",
"opaque-tao",
"cache",
]
.as_slice()
} else {
["same", "cors", "cors-tao", "denied", "cache"].as_slice()
};
for mode in modes {
let scenario = serde_json::json!({"realm": realm, "api": api, "mode": mode});
let total = if *mode == "cache" { 8 } else { 15 };
let result = run_resource_timing_fixture_scenario(
include_str!("../../../tests/fixtures/compressed-request-resource-timing.js"),
total,
Some(&scenario),
)
.await;
let checks = result["names"].as_array().unwrap();
assert_eq!(checks.len(), total, "{scenario}");
for check in checks {
let name = check.as_str().unwrap();
assert!(
name.starts_with(&format!("{realm}: {api}/")),
"{scenario}: {name}"
);
assert!(names.insert(name.to_owned()), "duplicate check: {name}");
}
}
}
}
assert_eq!(
names.len(),
566,
)
.await;
"all Window, child, worker, coding, API and cache cases must run"
);
}
@@ -1,5 +1,5 @@
(async () => {
const probe = async (origins, label) => {
const probe = async (origins, label, filter) => {
const rows = [];
globalThis.__compressedTimingProgress = rows;
const checks = async (name, run) => {
@@ -49,6 +49,7 @@
];
let next = 0;
for (const api of apis) for (const mode of ['same', 'cors', 'cors-tao', 'denied', ...(api === 'fetch' ? ['opaque', 'opaque-tao'] : [])]) for (const spec of specs) {
if (filter && (filter.api !== api || filter.mode !== mode)) continue;
await checks(`${api}/${mode}/${spec.kind}/${spec.chunked ? 'chunked' : 'length'}/${spec.method || 'GET'}`, async () => {
const url = new URL('/compressed', origins[mode === 'same' ? 0 : 1]);
url.searchParams.set('key', `${label}-${++next}`);
@@ -75,6 +76,7 @@
});
}
for (const api of apis) for (const {kind, encoded} of [{kind: 'gzip', encoded: 23}, {kind: 'zstd', encoded: 12}]) {
if (filter && (filter.api !== api || filter.mode !== 'cache')) continue;
const base = `${origins[0]}/compressed?kind=${kind}&cache=1&key=${label}-${api}-cache`;
for (let phase = 0; phase < 4; ++phase) await checks(`${api}/${kind}/cache/${phase}`, async () => {
const url = base + '#phase-' + phase;
@@ -86,28 +88,36 @@
assert(performance.getEntriesByName(url, 'resource').length === 1, 'Duplicate cached timing');
});
}
return {total: rows.length, failures: rows.filter(row => !row.passed)};
return {total: rows.length, failures: rows.filter(row => !row.passed), names: rows.map(row => row.name)};
};
const results = [await probe(__fetchOrigins, 'window')];
const iframe = document.createElement('iframe');
const child = new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(Error('Child timing probe did not finish')), 30000);
const receive = event => {
if (event.source !== iframe.contentWindow || event.data?.kind !== 'compressed-timing') return;
clearTimeout(timer); removeEventListener('message', receive); resolve(event.data.result);
};
addEventListener('message', receive);
});
iframe.srcdoc = '<!doctype html><script>const probe = ' + probe.toString() + '; probe(' + JSON.stringify(__fetchOrigins) + ', "child").then(result => parent.postMessage({kind:"compressed-timing",result}, "*"));</scr' + 'ipt>';
document.body.appendChild(iframe);
try { results.push(await child); } finally { iframe.remove(); }
const worker = new Worker(__fetchOrigins[0] + '/compressed-worker.js');
try {
results.push(await new Promise((resolve, reject) => {
worker.onmessage = event => resolve(event.data);
worker.onerror = event => reject(Error(event.message));
worker.postMessage({source: probe.toString(), origins: __fetchOrigins, label: 'worker'});
}));
} finally { worker.terminate(); }
return JSON.stringify({total: results.reduce((sum, result) => sum + result.total, 0), failures: results.flatMap(result => result.failures)});
const scenario = globalThis.__compressedTimingScenario;
const wants = realm => !scenario || scenario.realm === realm;
const filter = scenario ? {api: scenario.api, mode: scenario.mode} : null;
const results = [];
if (wants('window')) results.push(await probe(__fetchOrigins, 'window', filter));
if (wants('child')) {
const iframe = document.createElement('iframe');
const child = new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(Error('Child timing probe did not finish')), 30000);
const receive = event => {
if (event.source !== iframe.contentWindow || event.data?.kind !== 'compressed-timing') return;
clearTimeout(timer); removeEventListener('message', receive); resolve(event.data.result);
};
addEventListener('message', receive);
});
iframe.srcdoc = '<!doctype html><script>const probe = ' + probe.toString() + '; probe(' + JSON.stringify(__fetchOrigins) + ', "child", ' + JSON.stringify(filter) + ').then(result => parent.postMessage({kind:"compressed-timing",result}, "*"));</scr' + 'ipt>';
document.body.appendChild(iframe);
try { results.push(await child); } finally { iframe.remove(); }
}
if (wants('worker')) {
const worker = new Worker(__fetchOrigins[0] + '/compressed-worker.js');
try {
results.push(await new Promise((resolve, reject) => {
worker.onmessage = event => resolve(event.data);
worker.onerror = event => reject(Error(event.message));
worker.postMessage({source: probe.toString(), origins: __fetchOrigins, label: 'worker', filter});
}));
} finally { worker.terminate(); }
}
return JSON.stringify({total: results.reduce((sum, result) => sum + result.total, 0), failures: results.flatMap(result => result.failures), names: results.flatMap(result => result.names)});
})()
+69
View File
@@ -0,0 +1,69 @@
[package]
name = "curl-sys"
version = "0.4.91+curl-8.23.0"
authors = ["Alex Crichton <alex@alexcrichton.com>", "Stephen M. Coakley <me@stephencoakley.com>"]
links = "curl"
build = "build.rs"
license = "MIT"
repository = "https://github.com/lexmount/curl-rust"
description = "Native bindings to the libcurl library"
documentation = "https://docs.rs/curl-sys"
readme = "MOLI.md"
categories = ["external-ffi-bindings"]
edition = "2018"
exclude = ["curl/docs/", "curl/tests/"]
[badges.maintenance]
status = "passively-maintained"
[lib]
name = "curl_sys"
path = "lib.rs"
[dependencies]
libz-sys = { version = "1.0.18", default-features = false, features = ["libc"] }
libc = "0.2.2"
libnghttp2-sys = { optional = true, version = "0.1.3" }
brotlic-sys = { optional = true, version = "0.2.2" }
[dependencies.rustls-ffi]
version = "0.15"
optional = true
features = ["no_log_capture"]
[target.'cfg(all(unix))'.dependencies]
openssl-sys = { version = "0.9.64", optional = true }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Networking_WinSock"] }
[target.'cfg(target_env = "msvc")'.build-dependencies]
vcpkg = "0.2"
[build-dependencies]
cc = "1.0"
pkg-config = "0.3.3"
[features]
default = ["ssl"]
ssl = ["openssl-sys"]
http2 = ["libnghttp2-sys"]
brotli = ["brotlic-sys"]
mesalink = []
rustls = ["rustls-ffi"]
static-curl = []
browser-response-headers = ["static-curl"]
apple-sectrust = ["ssl", "static-curl"]
windows-static-ssl = []
static-ssl = ["openssl-sys/vendored"]
spnego = []
force-system-lib-on-osx = []
protocol-ftp = []
zlib-ng-compat = ["libz-sys/zlib-ng", "static-curl"]
upkeep_7_62_0 = []
poll_7_68_0 = []
websocket = []
ws_start_frame_8_16_0 = ["websocket"]
ntlm = []
[workspace]
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2014 Carl Lerche
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+19
View File
@@ -0,0 +1,19 @@
# Moli libcurl transport
Based on curl-sys 0.4.91 and libcurl 8.23 from
[lexmount/curl-rust 0392e12](https://github.com/lexmount/curl-rust/tree/0392e12475d8d1160d4cae07c172cac02797cc25/curl-sys).
The Rust curl wrapper remains at that same revision.
This copy preserves Moli's browser TLS EOF behavior across the upgrade:
accept actual transport EOF after the TLS handshake, while rejecting incomplete
HTTPS headers. TLS alerts, socket errors, certificate verification and HTTP/1
and HTTP/2 body framing remain enforced. Regression coverage lives in
`moli-curl/tests/tls_eof.rs`.
Only the native library and public headers are included. The build script does
not initialize Git submodules. On upgrades, port the three documented changes
in `curl/lib/http.c` and `curl/lib/vtls/openssl.c` and run the transport tests.
Keep the pinned main browser-response-headers feature and HTTP/1 parser source.
The remaining native source matches that revision except the three TLS EOF
changes described above.
+833
View File
@@ -0,0 +1,833 @@
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
// curl 8.22 limits config-win32.h to old Visual Studio project builds.
// curl-sys builds libcurl directly with cc, so reuse the platform settings
// as curl_config.h without the build-system guard.
fn write_windows_config(dst: &Path) {
let config = fs::read_to_string("curl/lib/config-win32.h").unwrap();
let mut lines = config.lines();
let mut output = String::new();
let mut removed_version_guard = false;
while let Some(line) = lines.next() {
if line == "#if !defined(_MSC_VER) || _MSC_VER > 1800" {
assert_eq!(
lines.next(),
Some(
"#error This manual configuration requires MSVC 2010-2013 (IDE Project builds)"
)
);
assert_eq!(lines.next(), Some("#endif"));
removed_version_guard = true;
continue;
}
output.push_str(line);
output.push('\n');
}
assert!(removed_version_guard);
fs::write(dst.join("curl_config.h"), output).unwrap();
}
fn main() {
println!("cargo:rerun-if-changed=curl");
println!(
"cargo:rustc-check-cfg=cfg(\
link_brotli,\
libcurl_vendored,\
link_libnghttp2,\
link_libz,\
link_openssl,\
)"
);
let target = env::var("TARGET").unwrap();
let windows = target.contains("windows");
if cfg!(feature = "mesalink") {
println!(
"cargo:warning=MesaLink support has been removed as of curl 7.82.0, will use default TLS backend instead."
);
}
// This feature trumps all others, and is largely set by rustbuild to force
// usage of the system library to ensure that we're always building an
// ABI-compatible Cargo.
if cfg!(feature = "force-system-lib-on-osx") && target.contains("apple") {
return println!("cargo:rustc-flags=-l curl");
}
// If the static-curl feature is disabled, probe for a system-wide libcurl.
if !cfg!(feature = "static-curl") {
// OSX ships libcurl by default, so we just use that version
// so long as it has the right features enabled.
if target.contains("apple") && (!cfg!(feature = "http2") || curl_config_reports_http2()) {
return println!("cargo:rustc-flags=-l curl");
}
// Next, fall back and try to use pkg-config if its available.
if windows {
if try_vcpkg() {
return;
}
} else if try_pkg_config() {
return;
}
}
let dst = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let include = dst.join("include");
let build = dst.join("build");
if windows {
write_windows_config(&dst);
}
println!("cargo:root={}", dst.display());
println!("cargo:include={}", include.display());
println!("cargo:static=1");
println!("cargo:rustc-cfg=libcurl_vendored");
fs::create_dir_all(include.join("curl")).unwrap();
for header in [
"curl.h",
"curlver.h",
"easy.h",
"options.h",
"header.h",
"mprintf.h",
"multi.h",
"stdcheaders.h",
"system.h",
"urlapi.h",
"typecheck-gcc.h",
"websockets.h",
]
.iter()
{
fs::copy(
format!("curl/include/curl/{}", header),
include.join("curl").join(header),
)
.unwrap();
}
let pkgconfig = dst.join("lib/pkgconfig");
fs::create_dir_all(&pkgconfig).unwrap();
let contents = fs::read_to_string("curl/libcurl.pc.in").unwrap();
fs::write(
pkgconfig.join("libcurl.pc"),
contents
.replace("@prefix@", dst.to_str().unwrap())
.replace("@exec_prefix@", "")
.replace("@libdir@", dst.join("lib").to_str().unwrap())
.replace("@includedir@", include.to_str().unwrap())
.replace("@CPPFLAG_CURL_STATICLIB@", "-DCURL_STATICLIB")
.replace("@LIBCURL_LIBS@", "")
.replace("@SUPPORT_FEATURES@", "")
.replace("@SUPPORT_PROTOCOLS@", "")
.replace("@CURLVERSION@", "8.23.0"),
)
.unwrap();
let mut cfg = cc::Build::new();
cfg.out_dir(&build)
.include("curl/lib")
.include("curl/include")
.define("BUILDING_LIBCURL", None)
.define("CURL_DISABLE_DICT", None)
.define("CURL_DISABLE_GOPHER", None)
.define("CURL_DISABLE_IMAP", None)
.define("CURL_DISABLE_LDAP", None)
.define("CURL_DISABLE_LDAPS", None)
.define("CURL_DISABLE_POP3", None)
.define("CURL_DISABLE_RTSP", None)
.define("CURL_DISABLE_SMB", None)
.define("CURL_DISABLE_SMTP", None)
.define("CURL_DISABLE_TELNET", None)
.define("CURL_DISABLE_TFTP", None)
.define("CURL_STATICLIB", None)
.define("USE_IPV6", None)
.define("HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID", None)
.define("HAVE_ASSERT_H", None)
.define("CURL_OS", "\"unknown\"") // TODO
.define("HAVE_ZLIB_H", None)
.define("HAVE_LONGLONG", None)
.define("HAVE_LIBZ", None)
.define("HAVE_BOOL_T", None)
.define("HAVE_STDBOOL_H", None)
.define("HAVE_STDINT_H", None)
.define("USE_RESOLV_THREADED", None)
.file("curl/lib/altsvc.c")
.file("curl/lib/api.c")
.file("curl/lib/bufq.c")
.file("curl/lib/bufref.c")
.file("curl/lib/cf-h1-proxy.c")
.file("curl/lib/cf-haproxy.c")
.file("curl/lib/cf-https-connect.c")
.file("curl/lib/cf-ip-happy.c")
.file("curl/lib/cf-recvbuf.c")
.file("curl/lib/cf-setup.c")
.file("curl/lib/cf-socket.c")
.file("curl/lib/cfilters.c")
.file("curl/lib/conncache.c")
.file("curl/lib/connect.c")
.file("curl/lib/content_encoding.c")
.file("curl/lib/cookie.c")
.file("curl/lib/creds.c")
.file("curl/lib/cshutdn.c")
.file("curl/lib/curl_addrinfo.c")
.file("curl/lib/curl_ed25519.c")
.file("curl/lib/curl_fopen.c")
.file("curl/lib/curl_get_line.c")
.file("curl/lib/curl_memrchr.c")
.file("curl/lib/curl_range.c")
.file("curl/lib/curl_sha512_256.c")
.file("curl/lib/curl_share.c")
.file("curl/lib/curl_threads.c")
.file("curl/lib/curl_trc.c")
.file("curl/lib/curlx/base64.c")
.file("curl/lib/curlx/basename.c")
.file("curl/lib/curlx/dynbuf.c")
.file("curl/lib/curlx/win32-fopen.c")
.file("curl/lib/curlx/inet_ntop.c")
.file("curl/lib/curlx/inet_pton.c")
.file("curl/lib/curlx/nonblock.c")
.file("curl/lib/curlx/snprintf.c")
.file("curl/lib/curlx/strcopy.c")
.file("curl/lib/curlx/strdup.c")
.file("curl/lib/curlx/strerr.c")
.file("curl/lib/curlx/strparse.c")
.file("curl/lib/curlx/timediff.c")
.file("curl/lib/curlx/timeval.c")
.file("curl/lib/curlx/wait.c")
.file("curl/lib/curlx/warnless.c")
.file("curl/lib/cw-out.c")
.file("curl/lib/cw-pause.c")
.file("curl/lib/dict.c")
.file("curl/lib/dynhds.c")
.file("curl/lib/easy.c")
.file("curl/lib/escape.c")
.file("curl/lib/file.c")
.file("curl/lib/fileinfo.c")
.file("curl/lib/formdata.c")
.file("curl/lib/ftp.c")
.file("curl/lib/getenv.c")
.file("curl/lib/getinfo.c")
.file("curl/lib/gopher.c")
.file("curl/lib/hash.c")
.file("curl/lib/headers.c")
.file("curl/lib/hmac.c")
.file("curl/lib/hsts.c")
.file(http_source(&dst))
.file("curl/lib/http1.c")
.file("curl/lib/http_aws_sigv4.c")
.file("curl/lib/http_chunks.c")
.file("curl/lib/http_digest.c")
.file("curl/lib/http_httpsig.c")
.file("curl/lib/http_proxy.c")
.file("curl/lib/idn.c")
.file("curl/lib/if2ip.c")
.file("curl/lib/imap.c")
.file("curl/lib/ldap.c")
.file("curl/lib/llist.c")
.file("curl/lib/macos.c")
.file("curl/lib/md5.c")
.file("curl/lib/mime.c")
.file("curl/lib/mprintf.c")
.file("curl/lib/mqtt.c")
.file("curl/lib/multi.c")
.file("curl/lib/multi_ev.c")
.file("curl/lib/multi_ntfy.c")
.file("curl/lib/netrc.c")
.file("curl/lib/parsedate.c")
.file("curl/lib/peer.c")
.file("curl/lib/pop3.c")
.file("curl/lib/progress.c")
.file("curl/lib/protocol.c")
.file("curl/lib/proxy.c")
.file("curl/lib/ptrarray.c")
.file("curl/lib/rand.c")
.file("curl/lib/ratelimit.c")
.file("curl/lib/request.c")
.file("curl/lib/rtsp.c")
.file("curl/lib/select.c")
.file("curl/lib/sendf.c")
.file("curl/lib/setopt.c")
.file("curl/lib/sha256.c")
.file("curl/lib/slist.c")
.file("curl/lib/smtp.c")
.file("curl/lib/socketpair.c")
.file("curl/lib/socks.c")
.file("curl/lib/splay.c")
.file("curl/lib/strcase.c")
.file("curl/lib/strequal.c")
.file("curl/lib/strerror.c")
.file("curl/lib/telnet.c")
.file("curl/lib/tftp.c")
.file("curl/lib/thrdpool.c")
.file("curl/lib/thrdqueue.c")
.file("curl/lib/transfer.c")
.file("curl/lib/u8_strset.c")
.file("curl/lib/u32_ptrset.c")
.file("curl/lib/uint-bset.c")
.file("curl/lib/uint-spbset.c")
.file("curl/lib/uint-table.c")
.file("curl/lib/url.c")
.file("curl/lib/urlapi.c")
.file("curl/lib/vauth/digest.c")
.file("curl/lib/vauth/vauth.c")
.file("curl/lib/vdns/asyn-base.c")
.file("curl/lib/vdns/asyn-thrdd.c")
.file("curl/lib/vdns/cf-dns.c")
.file("curl/lib/vdns/dnscache.c")
.file("curl/lib/vdns/doh.c")
.file("curl/lib/vdns/hostip.c")
.file("curl/lib/vdns/hostip6.c")
.file("curl/lib/version.c")
.file("curl/lib/vquic/vquic-tls.c")
.file("curl/lib/vquic/vquic.c")
.file("curl/lib/vssh/vssh.c")
.file("curl/lib/vtls/hostcheck.c")
.file("curl/lib/vtls/keylog.c")
.file("curl/lib/vtls/vtls.c")
.file("curl/lib/vtls/vtls_config.c")
.file("curl/lib/vtls/vtls_scache.c")
.file(websocket_source(&dst))
.define("HAVE_GETADDRINFO", None)
.define("HAVE_GETPEERNAME", None)
.define("HAVE_GETSOCKNAME", None)
.warnings(false);
if cfg!(feature = "ntlm") {
cfg.file("curl/lib/curl_endian.c")
.file("curl/lib/curl_gethostname.c")
.file("curl/lib/curl_ntlm_core.c")
.file("curl/lib/http_ntlm.c")
.file("curl/lib/md4.c")
.file("curl/lib/vauth/ntlm.c")
.file("curl/lib/vauth/ntlm_sspi.c");
} else {
cfg.define("CURL_DISABLE_NTLM", None);
}
if cfg!(feature = "protocol-ftp") {
cfg.file("curl/lib/curl_fnmatch.c")
.file("curl/lib/ftp.c")
.file("curl/lib/ftplistparser.c")
.file("curl/lib/pingpong.c");
} else {
cfg.define("CURL_DISABLE_FTP", None);
}
if cfg!(feature = "http2") {
cfg.define("USE_NGHTTP2", None)
.define("NGHTTP2_STATICLIB", None)
.file("curl/lib/cf-h2-proxy.c")
.file("curl/lib/http2.c");
println!("cargo:rustc-cfg=link_libnghttp2");
if let Some(path) = env::var_os("DEP_NGHTTP2_ROOT") {
let path = PathBuf::from(path);
cfg.include(path.join("include"));
}
}
if cfg!(feature = "brotli") {
cfg.define("HAVE_BROTLI", None)
.include(find_brotli_include());
println!("cargo:rustc-cfg=link_brotli");
}
println!("cargo:rustc-cfg=link_libz");
if let Some(path) = env::var_os("DEP_Z_INCLUDE") {
cfg.include(path);
}
if cfg!(feature = "spnego") {
cfg.define("USE_SPNEGO", None)
.file("curl/lib/http_negotiate.c")
.file("curl/lib/vauth/vauth.c");
}
// Configure TLS backend. Since Cargo does not support mutually exclusive
// features, make sure we only compile one vtls.
if cfg!(feature = "rustls") {
cfg.define("USE_RUSTLS", None)
.file("curl/lib/vtls/cipher_suite.c")
.file("curl/lib/vtls/rustls.c")
.file("curl/lib/vtls/x509asn1.c")
.include(env::var_os("DEP_RUSTLS_FFI_INCLUDE").unwrap());
} else if cfg!(feature = "windows-static-ssl") {
if windows {
cfg.define("USE_OPENSSL", None)
.file("curl/lib/vtls/openssl.c");
// We need both openssl and zlib
// Those can be installed with
// ```shell
// git clone https://github.com/microsoft/vcpkg
// cd vcpkg
// ./bootstrap-vcpkg.bat -disableMetrics
// ./vcpkg.exe integrate install
// ./vcpkg.exe install openssl:x64-windows-static-md
// ```
#[cfg(target_env = "msvc")]
vcpkg::Config::new().find_package("openssl").ok();
#[cfg(target_env = "msvc")]
vcpkg::Config::new().find_package("zlib").ok();
} else {
panic!("Not available on non windows platform")
}
} else if cfg!(feature = "ssl") {
if windows {
// For windows, spnego feature is auto on in case ssl feature is on.
// Please see definition of USE_SPNEGO in curl_setup.h for more info.
cfg.define("USE_WINDOWS_SSPI", None)
.define("USE_SCHANNEL", None)
.file("curl/lib/http_negotiate.c")
.file("curl/lib/curl_sspi.c")
.file("curl/lib/socks_sspi.c")
.file("curl/lib/vauth/krb5_sspi.c")
.file("curl/lib/vauth/spnego_sspi.c")
.file("curl/lib/vauth/vauth.c")
.file("curl/lib/vtls/schannel.c")
.file("curl/lib/vtls/schannel_verify.c")
.file("curl/lib/vtls/x509asn1.c");
} else {
cfg.define("USE_OPENSSL", None)
.file("curl/lib/vtls/openssl.c");
if target.contains("-apple-") && cfg!(feature = "apple-sectrust") {
cfg.define("USE_APPLE_SECTRUST", None)
.file("curl/lib/vtls/apple.c");
}
println!("cargo:rustc-cfg=link_openssl");
if let Some(path) = env::var_os("DEP_OPENSSL_INCLUDE") {
cfg.include(path);
}
}
}
// Configure platform-specific details.
if windows {
cfg.define("HAVE_CONFIG_H", None)
.include(&dst)
.define("WIN32", None)
.define("USE_THREADS_WIN32", None)
.define("HAVE_IOCTLSOCKET_FIONBIO", None)
.define("USE_WINSOCK", None)
.file("curl/lib/bufref.c")
.file("curl/lib/vauth/digest_sspi.c")
.file("curl/lib/curlx/multibyte.c")
.file("curl/lib/curlx/version_win32.c")
.file("curl/lib/curlx/winapi.c");
if cfg!(feature = "spnego") {
cfg.file("curl/lib/vauth/spnego_sspi.c");
}
} else {
cfg.define("RECV_TYPE_ARG1", "int")
.define("HAVE_PTHREAD_H", None)
.define("HAVE_ARPA_INET_H", None)
.define("HAVE_ERRNO_H", None)
.define("HAVE_FCNTL_H", None)
.define("HAVE_NETDB_H", None)
.define("HAVE_NETINET_IN_H", None)
.define("HAVE_NETINET_TCP_H", None)
.define("HAVE_POLL_H", None)
.define("HAVE_FCNTL_O_NONBLOCK", None)
.define("HAVE_SYS_SELECT_H", None)
.define("HAVE_SYS_STAT_H", None)
.define("HAVE_SYS_TIME_H", None)
.define("HAVE_UNISTD_H", None)
.define("HAVE_RECV", None)
.define("HAVE_SELECT", None)
.define("HAVE_SEND", None)
.define("HAVE_SOCKET", None)
.define("HAVE_STERRROR_R", None)
.define("HAVE_SOCKETPAIR", None)
.define("HAVE_STRUCT_TIMEVAL", None)
.define("HAVE_SYS_UN_H", None)
.define("HAVE_THREADS_POSIX", None)
.define("USE_UNIX_SOCKETS", None)
.define("RECV_TYPE_ARG2", "void*")
.define("RECV_TYPE_ARG3", "size_t")
.define("RECV_TYPE_ARG4", "int")
.define("RECV_TYPE_RETV", "ssize_t")
.define("SEND_QUAL_ARG2", "const")
.define("SEND_TYPE_ARG1", "int")
.define("SEND_TYPE_ARG2", "void*")
.define("SEND_TYPE_ARG3", "size_t")
.define("SEND_TYPE_ARG4", "int")
.define("SEND_TYPE_RETV", "ssize_t")
.define("SIZEOF_CURL_OFF_T", "8")
.define("SIZEOF_INT", "4")
.define("SIZEOF_SHORT", "2");
if target.contains("-apple-") {
cfg.define("__APPLE__", None)
.define("HAVE_MACH_ABSOLUTE_TIME", None)
// Rust's `std` provides the necessary symbols since:
// https://github.com/rust-lang/rust/pull/138944
.define("HAVE_BUILTIN_AVAILABLE", None);
} else {
cfg.define("HAVE_CLOCK_GETTIME_MONOTONIC", None)
.define("HAVE_GETTIMEOFDAY", None)
// poll() on various versions of macOS are janky, so only use it
// on non-macOS unix-likes. This matches the official default
// build configuration as well.
.define("HAVE_POLL_FINE", None);
}
if cfg!(feature = "spnego") {
cfg.define("HAVE_GSSAPI", None)
.file("curl/lib/curl_gssapi.c")
.file("curl/lib/socks_gssapi.c")
.file("curl/lib/vauth/spnego_gssapi.c");
if let Some(path) = env::var_os("GSSAPI_ROOT") {
let path = PathBuf::from(path);
cfg.include(path.join("include"));
}
// Link against the MIT gssapi library. It might be desirable to add support for
// choosing between MIT and Heimdal libraries in the future.
println!("cargo:rustc-link-lib=gssapi_krb5");
}
let width = env::var("CARGO_CFG_TARGET_POINTER_WIDTH")
.unwrap()
.parse::<usize>()
.unwrap();
cfg.define("SIZEOF_SSIZE_T", Some(&(width / 8).to_string()[..]));
cfg.define("SIZEOF_SIZE_T", Some(&(width / 8).to_string()[..]));
cfg.define("SIZEOF_LONG", Some(&(width / 8).to_string()[..]));
cfg.flag("-fvisibility=hidden");
}
cfg.compile("curl");
if windows {
println!("cargo:rustc-link-lib=ws2_32");
println!("cargo:rustc-link-lib=crypt32");
println!("cargo:rustc-link-lib=iphlpapi");
println!("cargo:rustc-link-lib=advapi32");
println!("cargo:rustc-link-lib=secur32");
println!("cargo:rustc-link-lib=bcrypt");
}
// Illumos/Solaris requires explicit linking with libnsl
if target.contains("solaris") {
println!("cargo:rustc-link-lib=nsl");
}
if target.contains("-apple-") {
println!("cargo:rustc-link-lib=framework=Security");
println!("cargo:rustc-link-lib=framework=CoreFoundation");
println!("cargo:rustc-link-lib=framework=CoreServices");
println!("cargo:rustc-link-lib=framework=SystemConfiguration");
}
}
#[cfg(not(target_env = "msvc"))]
fn try_vcpkg() -> bool {
false
}
#[cfg(target_env = "msvc")]
fn try_vcpkg() -> bool {
// the import library for the dll is called libcurl_imp
let mut successful_probe_details = match vcpkg::Config::new()
.lib_names("libcurl_imp", "libcurl")
.emit_includes(true)
.probe("curl")
{
Ok(details) => Some(details),
Err(e) => {
println!("first run of vcpkg did not find libcurl: {}", e);
None
}
};
if successful_probe_details.is_none() {
match vcpkg::Config::new()
.lib_name("libcurl")
.emit_includes(true)
.probe("curl")
{
Ok(details) => successful_probe_details = Some(details),
Err(e) => println!("second run of vcpkg did not find libcurl: {}", e),
}
}
if successful_probe_details.is_some() {
// Found libcurl which depends on openssl, libssh2 and zlib
// in the a default vcpkg installation. Probe for them
// but do not fail if they are not present as we may be working
// with a customized vcpkg installation.
vcpkg::Config::new()
.lib_name("libeay32")
.lib_name("ssleay32")
.probe("openssl")
.ok();
vcpkg::probe_package("libssh2").ok();
vcpkg::Config::new()
.lib_names("zlib", "zlib1")
.probe("zlib")
.ok();
println!("cargo:rustc-link-lib=crypt32");
println!("cargo:rustc-link-lib=gdi32");
println!("cargo:rustc-link-lib=user32");
println!("cargo:rustc-link-lib=wldap32");
return true;
}
false
}
fn try_pkg_config() -> bool {
let mut cfg = pkg_config::Config::new();
cfg.cargo_metadata(false);
let lib = match cfg.probe("libcurl") {
Ok(lib) => lib,
Err(e) => {
println!(
"Couldn't find libcurl from pkgconfig ({:?}), \
compiling it from source...",
e
);
return false;
}
};
// Not all system builds of libcurl have http2 features enabled, so if we've
// got a http2-requested build then we may fall back to a build from source.
if cfg!(feature = "http2") && !curl_config_reports_http2() {
return false;
}
// Re-find the library to print cargo's metadata, then print some extra
// metadata as well.
cfg.cargo_metadata(true).probe("libcurl").unwrap();
for path in lib.include_paths.iter() {
println!("cargo:include={}", path.display());
}
true
}
fn websocket_source(dst: &Path) -> PathBuf {
let source = PathBuf::from("curl/lib/ws.c");
if !cfg!(feature = "websocket") {
return source;
}
// libcurl accepts an HTTP/1.0 101 response, but its HTTP persistence
// default then closes the upgraded connection when CONNECT_ONLY finishes.
// Preserve the accepted WebSocket just as for HTTP/1.1. Generate this one
// patched translation unit without modifying the pinned upstream submodule
// or requiring a patch executable on Windows. Recheck on libcurl updates.
let before = " k->upgr101 = UPGR101_RECEIVED;\n k->header = FALSE; /* we will not get more responses */\n";
let after = " k->upgr101 = UPGR101_RECEIVED;\n k->header = FALSE; /* we will not get more responses */\n\n /* HTTP persistence no longer governs an accepted protocol upgrade. */\n if(k->httpversion == 10)\n connkeep(data->conn);\n";
let mut contents = fs::read_to_string(&source).unwrap().replace("\r\n", "\n");
assert_eq!(
contents.matches(before).count(),
1,
"recheck the HTTP/1.0 WebSocket upgrade patch against bundled libcurl"
);
contents = contents.replacen(before, after, 1);
// recvbuf has a soft allocation limit. Slurping until the socket blocks
// can prefetch an entire stream before returning one payload chunk and
// prevent the caller from applying receive backpressure. Read one bounded
// buffer chunk instead, then let the WebSocket decoder return to the caller.
// Newer libcurl queues automatic PONGs. Flush them before another read:
// a peer may wait for the PONG before sending any application payload.
let before = " result = Curl_bufq_slurp(&ws->recvbuf, nw_in_recv, data, &n);";
let after = r#" if(!data->set.ws_raw_mode && !ws->using_reader && ws->pending.type) {
result = ws_flush(data, ws, Curl_api_is_in_callback(data));
if(result && result != CURLE_AGAIN)
goto out;
}
result = Curl_bufq_sipn(&ws->recvbuf, 0, nw_in_recv, data, &n);"#;
assert_eq!(
contents.matches(before).count(),
1,
"recheck the WebSocket receive prefetch patch against bundled libcurl"
);
let patched = dst.join("ws.c");
fs::write(&patched, contents.replacen(before, after, 1)).unwrap();
patched
}
fn http_source(dst: &Path) -> PathBuf {
let source = PathBuf::from("curl/lib/http.c");
if !cfg!(feature = "browser-response-headers") {
return source;
}
// Keep the upstream submodule untouched, as for websocket_source. Only
// HTTP/1 response parsing uses the browser's CR-delimited field segments;
// HTTP/2 and HTTP/3 still use libcurl's strict header validation.
println!("cargo:rerun-if-changed=http_browser_headers.c");
let mut contents = fs::read_to_string(source).unwrap().replace("\r\n", "\n");
let anchor = "static CURLcode http_parse_headers(struct Curl_easy *data,";
assert_eq!(contents.matches(anchor).count(), 1);
contents = contents.replacen(
anchor,
&format!("{}\n{anchor}", include_str!("http_browser_headers.c")),
1,
);
for before in [
"result = http_rw_hd(data, curlx_dyn_ptr(&data->state.headerb),",
"result = http_rw_hd(data, hd, hlen, buf, blen, &consumed);",
] {
assert_eq!(
contents.matches(before).count(),
1,
"recheck browser HTTP/1 response parsing against bundled libcurl"
);
contents = contents.replacen(
before,
&before.replace("http_rw_hd(", "http_rw_hd_browser("),
1,
);
}
let before = " return checkhttpprefix(data, s, len);\n}";
assert_eq!(contents.matches(before).count(), 1);
contents = contents.replacen(
before,
r#" if(conn->scheme->protocol & PROTO_FAMILY_HTTP) {
size_t slop = 0;
/* Chromium locates the status line within four leading bytes. */
while(len && *s == '\r' && slop < 4) {
s++;
len--;
slop++;
}
}
return checkhttpprefix(data, s, len);
}"#,
1,
);
let before = " result = Curl_http_write_resp_hds(data, buf, blen, &consumed);\n";
assert_eq!(contents.matches(before).count(), 1);
contents = contents.replacen(
before,
&format!(
"{before}{}",
r#" if(!result && is_eos && data->req.header &&
(data->conn->scheme->protocol & PROTO_FAMILY_HTTP) &&
data->req.httpversion < 20 && data->req.httpcode >= 200) {
result = http_finish_browser_headers(data);
goto out;
}
"#
),
1,
);
let patched = dst.join("http.c");
fs::write(&patched, contents).unwrap();
patched
}
fn curl_config_reports_http2() -> bool {
let output = Command::new("curl-config").arg("--features").output();
let output = match output {
Ok(out) => out,
Err(e) => {
println!("failed to run curl-config ({}), building from source", e);
return false;
}
};
if !output.status.success() {
println!("curl-config failed: {}", output.status);
return false;
}
let stdout = String::from_utf8_lossy(&output.stdout);
if !stdout.contains("HTTP2") {
println!(
"failed to find http-2 feature enabled in pkg-config-found \
libcurl, building from source"
);
return false;
}
true
}
fn find_brotli_include() -> PathBuf {
let manifest_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
let workspace_root = manifest_dir.parent().unwrap().to_path_buf();
let mut roots = vec![workspace_root.join("vendor"), manifest_dir.join("vendor")];
if let Some(cargo_home) = cargo_home() {
roots.push(cargo_home.join("registry").join("src"));
roots.push(cargo_home.join("git").join("checkouts"));
}
for root in roots {
if let Some(path) = brotli_include_in(&root) {
return path;
}
}
panic!(
"failed to locate brotlic-sys headers; searched workspace vendor/ and cargo registry sources"
);
}
fn cargo_home() -> Option<PathBuf> {
env::var_os("CARGO_HOME")
.map(PathBuf::from)
.or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".cargo")))
}
fn brotli_include_in(root: &Path) -> Option<PathBuf> {
fn candidate(dir: &Path) -> Option<PathBuf> {
let include = dir.join("brotli").join("c").join("include");
if dir
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.starts_with("brotlic-sys-"))
&& include.join("brotli").join("decode.h").exists()
{
Some(include)
} else {
None
}
}
let entries = fs::read_dir(root).ok()?;
for entry in entries.flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
if let Some(include) = candidate(&path) {
return Some(include);
}
let children = match fs::read_dir(&path) {
Ok(children) => children,
Err(_) => continue,
};
for child in children.flatten() {
let child_path = child.path();
if !child_path.is_dir() {
continue;
}
if let Some(include) = candidate(&child_path) {
return Some(include);
}
}
}
None
}
+22
View File
@@ -0,0 +1,22 @@
COPYRIGHT AND PERMISSION NOTICE
Copyright (c) 1996 - 2026, Daniel Stenberg, <daniel@haxx.se>, and many
contributors, see the THANKS file.
All rights reserved.
Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization of the copyright holder.
+50
View File
@@ -0,0 +1,50 @@
_ _ ____ _
___| | | | _ \| |
/ __| | | | |_) | |
| (__| |_| | _ <| |___
\___|\___/|_| \_\_____|
README
Curl is a command line tool for transferring data specified with URL
syntax. Find out how to use curl by reading the curl.1 man page or the
MANUAL document. Find out how to install Curl by reading the INSTALL
document.
libcurl is the library curl is using to do its job. It is readily
available to be used by your software. Read the libcurl.3 man page to
learn how.
You find answers to the most frequent questions we get in the FAQ.md
document.
Study the COPYING file for distribution terms.
Those documents and more can be found in the docs/ directory.
CONTACT
If you have problems, questions, ideas or suggestions, please contact us
by posting to a suitable mailing list. See https://curl.se/mail/
All contributors to the project are listed in the THANKS document.
WEBSITE
Visit the curl website for the latest news and downloads:
https://curl.se/
GIT
To download the latest source code off the GIT server, do this:
git clone https://github.com/curl/curl
(you get a directory named curl, filled with the source code)
SECURITY PROBLEMS
Report suspected security problems privately and not in public.
https://curl.se/dev/vuln-disclosure.html
+628
View File
@@ -0,0 +1,628 @@
curl and libcurl 8.23.0
Public curl releases: 276
Command line options: 278
curl_easy_setopt() options: 312
Public functions in libcurl: 100
Authors: 1547
Contributors: 3844
This release includes the following changes:
o lib: CURL_GLOBAL_WIN32 -> CURL_GLOBAL_WINSOCK [64]
o SMB: drop support [63]
o tool_cb_wrt: inject the no-clobber number before the extension [21]
o tool_cb_wrt: try up to .9999 when no-clobbering [46]
This release includes the following bugfixes:
o apple-sectrust: check ocsp copy alloc [292]
o apple: shorten versions in `__builtin_available()` calls [251]
o apple: sync hash init calls, add comments [217]
o apple: sync up version guard macro style [263]
o base64: avoid repeated input loads when encoding [114]
o base64: optimize decode lookup table and quantum loop [88]
o build: convert HAS_TIME_T_UNSIGNED to a compile-time check [65]
o build: drop `HTTP_ONLY` option [23]
o capsule: reject a capsule that can never be buffered [84]
o cf-h1-proxy: reset chunk state on new request [146]
o cf-h1-proxy: stricter status line parsing [145]
o cf-https-connect: re-arm the timer for the hard eyeballs timeout [222]
o cf-ngtcp2-cmn: fix possible `-Wdeclaration-after-statement` [296]
o cf-ngtcp2-proxy: check for stream close on rx win update [159]
o cf-ngtcp2-proxy: fix rx flow control [174]
o cf-socket: adjust NO_SYN_RETRANSMISSIONS for older Windows [275]
o cf-socket: clamp keepalive seconds-to-milliseconds conversions [167]
o cfilters: fail a send that reports more written than requested [194]
o clang-tidy: merge nested `if()`s [39]
o cmake/Find*: drop deprecated compatibility config variables [259]
o cmake: enable C++ library for GCC in AWS-LC/BoringSSL static builds [232]
o cmake: link llvm stdc++ lib to AWS-LC/BoringSSL-specific feature detections only [271]
o config2setopts: always set the security options for SCP/SFTP [67]
o config2setopts: rename define for maximum cookie header length [248]
o conncache: avoid evicting connect-only connections [79]
o conncache: never discard a connection still in use [208]
o conncache: remove bundle dest [50]
o connect: do not busy-loop in blocking connect without a timeout [240]
o connect: keep IP info and connect time when connect fails [195]
o connectdata: use less curltime [34]
o cookie: accept and ignore empty property names in Set-Cookie [234]
o cookie: accept and ignore values for 'secure' and 'httponly' [187]
o cookie: accept slightly longer lines in cookie jars [105]
o cookie: cookies for a PSL domain from jar just limits tailmatch [176]
o cookie: ignore individual cookie errors when loading [6]
o cpool: do not use admin handle for conn lookup [299]
o cshutdown: make it smaller [60]
o cshutdown: use ptrarray instead of llist [156]
o curl-openssl.m4: sync LibreSSL detection method with rest of forks [218]
o curl_addrinfo: drop redundant parentheses [41]
o curl_easy_send/recv: check pointer arg [175]
o curl_fopen: restore the uid and gid checks [70]
o curl_formadd.md: mention the strlen() for names as well [29]
o curl_multi_perform: doc update [148]
o curl_setup.h: drop compatibility raw C flag `ENABLE_IPV6` [260]
o CURLINFO_EFFECTIVE_URL.md: mention a short lifetime [116]
o CURLOPT*ISSUERCERT*: not verified cryptographically [28]
o CURLOPT_POSTFIELDSIZE.md: improve wording [144]
o CURLOPT_SHARE.md: remove bad explanation for cookie sharing [7]
o CURLOPT_SSL_CTX_FUNCTION.md: client cert caveats [87]
o curlx_fopen: add macro to cast file mode [245]
o cw-out: avoid O(n^2) work while buffering paused output [74]
o cw-out: recheck callbacks for each call [134]
o cw-pause: fix O(N^2) list traversal in cw_pause_flush [137]
o DEPENDENCIES.md: fix release date for valgrind 3.0.0 to 2005-08-03
o DEPRECATE.md: reflect SMB removal [252]
o DEPRECATE: Common Name support in TLS certificates for OpenSSL [172]
o digest: check peer equality for staleness [24]
o digest: fix maximum length quoted value parsing [22]
o digest: parse without storing 'value' in local buffer [20]
o digest: quote the digest-uri param as well [85]
o dnscache/conncache tweaks [75]
o dnscache: check hostname on lookup [209]
o dnscache: compare full hostnames when lookup keys are truncated [301]
o docs: add the missing .html to the url-encode book link [3]
o docs: document and align the blocking situations [163]
o docs: note CAINFO/SSL_VERIFYPEER/SSL_VERIFYSTATUS effect on LDAP [188]
o docs: SSL session import/file updates [199]
o doh: reject undersized HTTPS RDATA [11]
o dynhds: check size overflows [198]
o dynhds: grow header array geometrically [73]
o easy: change event pollset construction [242]
o easy: duplicating a zero byte memory area needs no malloc [91]
o easy: make ca_cache_timeout standalone [51]
o easy: validate buffer pointer in curl_easy_recv and curl_easy_send [152]
o ECH: rework config, add test cases [220]
o escape: polish encoding and decoding for speed [37]
o escape: use hex-pair lookup in curl_easy_escape [77]
o examples: clean up crawler link parsing resources [119]
o fnmatch: replace recursive matcher with iterative greedy algorithm [72]
o formdata: reject a negative content length in curl_formadd [128]
o ftp: require TLS on the data connection for implicit FTPS [126]
o ftp: tighten use_ssl check for conn reuse [19]
o ftp: URL encode file names when wildcarding [61]
o ftplistparser: no more overwriting set.write_func [100]
o ftplistparser: when wildcarding, skip files with slashes [125]
o ftpserver.pl: fix warnings when running test 804 [257]
o getinfo: make sure CURLINFO_EFFECTIVE_URL does not contain creds [107]
o getinfo: make sure CURLINFO_REDIRECT_URL does not contain creds [94]
o getparam: switch off CONNECT headers when using -J [4]
o glob: reduce the number of allocations for URLs that don't need globbing. [109]
o global_init: tidy up, simplify, fix issues [43]
o gnutls: hardening [230]
o GnuTLS: remove our own OCSP signature verification [266]
o gtls: no early return on verify fail [149]
o h3-proxy: teardown fix [182]
o happy eyeballs: bound work from many duplicate/failing addresses [80]
o hash: change key arguments to const [14]
o hash: vary bucket placement across process runs [108]
o headers: avoid O(n^2) rescans in curl_easy_nextheader() [81]
o hsts: cap max-age to two years [47]
o hsts: on load, only remove exact duplicates [56]
o HTTP-CONNECT: do not react to 401 responses [31]
o http2: changes in error handling [53]
o http2: don't send a CURLE_SEND_ERROR after a valid http2 response [71]
o http2: fix reset after 1xx response [289]
o http2: init some callbacks for HTTP/2 push easy handles [191]
o http2: initialize URL handle for server pushes [104]
o http2: limit trailers and headers count [211]
o http2: update a refused stream's error after GOAWAY [102]
o http2: use stream in userdata [246]
o http: abide to close-rules when transfer-encoding off [132]
o http: ignore Proxy-Authenticate unless the response comes from a proxy [120]
o http: only enable Negotiate/NTLM to allowed origins [99]
o http: reject empty header names [241]
o http: reject resumed uploads [16]
o http_aws_sigv4: fix the s3express service name [273]
o http_chunks: accept exactly 17 characters chunk-size [170]
o http_chunks: limit trailers size [212]
o httpsig-key.md: correct the generating Ed25519 keys commands [97]
o httpsrr+ech: check target and port [133]
o if2ip: check interface name case sensitive [158]
o imap: close the connection on premature done instead of finalizing [197]
o imap: compare selected mailbox names case-sensitively [57]
o imap: do size checks using 64-bit math [291]
o inet_pton: reject a colon that ends an IPv6 address [179]
o IPFS.md: replace sunset link, allowlist another one to avoid `mdlinkcheck` hang [168]
o KNOWN_BUGS: drop the curl-config private details entry [290]
o KNOWN_BUGS: drop the empty error buffer entry, it no longer happens [66]
o ldap: base64-encode a non-SAFE DN and reject a control-byte type name [55]
o ldap: tidy up variable scope, merge nested `#if`s [206]
o lib557: exclude three floating point test cases for VS2013 and earlier [249]
o lib: connection shutdown, cleanup code [92]
o lib: make private functions static and remove unused code [83]
o lib: reject internal handles in the multi/easy public API [103]
o lib: replace `CURLX_FILE_MODE()` with `mode_t` cast [205]
o libssh2: match hashed known_hosts entries by host [30]
o libssh2: skip repeat checkp() for already-absent hashed key types [82]
o libssh: work with empty priv_key [143]
o mbedtls: fix ticket handling [52]
o mbedtls: pass correct length for PEM/DER key blobs [177]
o mbedtls: resend length check [140]
o mdlinkcheck: pass `--retry-max-time` to avoid server-controlled long retry times [161]
o mime: bound Curl_mime_duppart() recursion depth [164]
o mime: bound Curl_mime_prepare_headers() recursion depth [76]
o mime: do curl_mime_free() non-recursively [48]
o mprintf: acknowledge %F [300]
o mprintf: avoid scanning strings twice for unbounded %s [110]
o mprintf: make mprintf() and mfprintf() return -1 on error [279]
o mprintf: stage output and emit it in runs [38]
o mprintf: use size_t width for the bare Windows %I modifier [178]
o mqtt: drain queued output before advancing the state machine [118]
o mqtt: remaininglength check for 32-bit systems [150]
o mqttd: work around bogus VS2019 32-bit compiler warning [202]
o mulit_ev: remove socket references on forget [89]
o multi-event: fix timeout of pending transfers [111]
o multi: adjust the cleanup order in multi_done [135]
o multi: is_finished() fix [239]
o multi: reduce struct size with small cleanups [25]
o multi: remove redundant completion message list [32]
o multi: store timeout epoch as whole seconds [36]
o multi_ntfy: fix handling of more than 128 notifications in a batch [86]
o multi_ntfy: recheck callback on dispatch [228]
o multi_ntfy: replace enabled bitset with inline flags [44]
o multihandle: some easy shrinks [33]
o netrc: empty quoted values now produce a valid empty string [62]
o netrc: survive comment-only .netrc file [93]
o ngtcp2: shrink max sendbuf [13]
o ngtcp2: use stream in userdata [185]
o openldap: hand it a dup'd socket, not curl's own
o openssl/gtls: reject CRLfile with native CA store, matching rustls [27]
o openssl: fix OpenSSL v4.1 no-deprecated build [190]
o openssl: hardening [227]
o openssl: support X509 store caching when CApath is configured [264]
o openssl: use non-deprecated API for MD5/MD4 [69]
o os400: document curl_formadd_CCSID multi-chunk peculiarity [5]
o os400: restore HAVE_FCHMOD [181]
o os400: use correct free function [189]
o ossl_verifyhost: remove assumption of null-termination of ASN1_STRING. [26]
o output-dir.md: expand on its behavior [151]
o parsedate: find day names, months and time zones faster [68]
o parsedate: remove the unused leading three letters [106]
o parsedate: validate NULL date pointer in curl_getdate [213]
o peer: compare zoneid case sensitive [229]
o peer: parsing a zoneid as number fix [139]
o peer: preserve ipv6 props from "connect-to" [155]
o perf-tests: output two-digital decimals always [96]
o pingpong: add a max loop counter for Curl_pp_readresp [113]
o pingpong: guard sendleft against a send reporting more than requested [196]
o pingpong: schedule server response timeouts for the socket API [221]
o pytest: adjust threshold in test_20_11_crazy_pings for arm64 [237]
o pytest: check server status without ssl verify [154]
o pytest: fixture fixes [193]
o pytest: set `PerSourcePenalties no` when sshd supports it [169]
o pytest: silence pytest warnings [261]
o pytest: start all servers early [214]
o retry.md: clarify that the server can override retry delay time [184]
o Revert "setopt: clear the 'custom' CA booleans when set to NULL" [235]
o rtsp: accept a Content-Length body on methods that expected none [115]
o rtsp: do not send a learned session id to another origin [10]
o runtests: add extra room for mininum number of tests in sliced jobs [201]
o runtests: Added runnernums in order to have O(1) lookup [45]
o runtests: unset `CURL_MEMDEBUG` for curl requests made to the CI API [258]
o rustls: break recv loop on empty plain text [298]
o rustls: consume CURLOPT_SSLCERT_BLOB / CURLOPT_SSLKEY_BLOB [219]
o schannel: auto_client_cert conn matching [17]
o schannel: clear borrowed sslContext on close [15]
o schannel: fix `-Wextra-semi-stmt` with clang and extra debug enabled [267]
o schannel: fix compiler warning `-Wstrict-aliasing` in ALPN code [243]
o schannel: fix guard for old MSVC workaround [204]
o schannel: handle empty tokens during renegotiation [183]
o schannel: retain close_notify records across send retries [302]
o sectrust: add guards for rest of Apple OS flavors [250]
o share link: forget connection [223]
o socketpair: fix accept loop [210]
o socketpair: use `pipe2()` on Apple OSes (requires SDK 27) [262]
o socks: support CURLAUTH_ONLY in CURLOPT_SOCKS5_AUTH [124]
o socks: track SOCKS5 authentication per socket, not per connection [171]
o socksd: count connections per test, widen the method2 sentinel
o ssl: dedup ssl_fsslctx [35]
o ssls: validate input arguments in import, export, and unpack [136]
o strparse: speed up number parsing [129]
o sws: fix connection-monitor for connections closed before a request [153]
o telnet: make it work through proxy tunnels [112]
o test 1605: move from unit to libtest [49]
o test/servers.pm: restrict h2/3 port reuse [203]
o test1119, 1167: disable MSYS2 argument conversion [254]
o test1399: improve reliability [9]
o test1679: unset `SSL_CERT_FILE`, use `TESTNUMBER` [58]
o test2007: bump to use SHA256 public key hash (was: MD5) [226]
o test2007: set `MSYS2_ARG_CONV_EXCL` to avoid flaky failures [216]
o test2072: enable on Cygwin/MSYS2 [256]
o test428: skip when running on older MSYS2 versions [276]
o test: restore the old test 1609 as 3271 [162]
o testcurl.pl: drop support for building c-ares from embedded source tree [253]
o tests/http: use @classmethod when appropriate [231]
o tests: add SFTP connection reuse tests [224]
o tests: clean up Python test code [130]
o tests: fix typos in a comment [247]
o tests: require valgrind 3+ (2007-08-03) [282]
o tftp: verify direction in a few places [101]
o tool: (re)set SSL verification in --libcurl output [1]
o tool: add Unicode and long-filename support to `--create-dir` (Windows) [141]
o tool: buffer headers before remote filename selection [98]
o tool: handling of "synthetic" errors [233]
o tool_doswin: recognize superscript numbers as reserved [117]
o tool_easysrc: reset the handle between --next operations [90]
o tool_getparam: do not print the value of a redacted argument [127]
o tool_getparam: restore --socks5-gssapi-service [200]
o tool_help: guard category[2] access when category is bare "-" [59]
o tool_ipfs: keep the path percent-encoded when rewriting to the gateway [138]
o tool_operate: clear the retry flag when the output file fails [122]
o tool_util: add Unicode support to `tool_execpath()` [142]
o u8_strset, u32_ptrset: fix boundaries handling [131]
o uint-bset: skip unused slots when counting
o uint-table: add remove-max precaution [165]
o unit1399: check microsecond precision across redirects [225]
o unit1664: add workaround for VS2019 16.3 - VS2022 17.4 x64 miscompile [272]
o url: check syntax before applying default-protocol [147]
o url: CURLOPT_INTERFACE fix connection reuse match [186]
o url: match connections without force reuse and candidates [95]
o url: ntlm/negotiate, prohibit connection reuse on follows [18]
o urlapi: make curl_url_dup() copy the guessed_scheme flag [166]
o urlapi: normalize legacy numeric IPv4 hosts set via CURLUPART_HOST [180]
o urlapi: return NULL from curl_url_dup() when given a NULL handle [160]
o urlapi: run the urlparser perf test faster [54]
o urldata: remove conn->given [40]
o urldata: remove ssl_primary_config from easy handle [78]
o urldata: shrink connectdata negotiate states [207]
o vdns: announce resolver start before the HTTPS RR query is sent [173]
o vquic: fix preprocessor check for old Darwin versions [8]
o vquic: use `CURLX_FILE_MODE()` in `Curl_qlogdir()` [238]
o vssh: do not busy-loop in blocking state machine without a timeout [121]
o vtls: fix Curl_cert_hostcheck when the pattern is not a C string [12]
o vtls_scache: remember lock state locally [297]
o warnless: dedupe Intel compiler warning suppression pragmas [42]
o wcurl: import v2026.10.12 [236]
o websocket: auto PONG with client reader fix [215]
o websocket: error on EOS with incomplete frame [244]
o wolfssl: remove BIO destroy callback [157]
o ws: check pointer args in curl_ws_recv [192]
o ws: do not auto-pong in raw mode [123]
o x509: stricter parsing [2]
This release includes the following known bugs:
See https://curl.se/docs/knownbugs.html
For all changes ever done in curl:
See https://curl.se/changes.html
Planned upcoming removals include:
o Common Name support in TLS certificates for OpenSSL
o HTTP/2 Server Push
o local crypto implementations
o NTLM
See https://curl.se/dev/deprecate.html
This release would not have looked like this without help, code, reports and
advice from friends like these:
1rhino2 on hackerone, Adam Shirt, Adrien Rey-Jarthon, Alexander Köplinger,
Andreas Westin, Anthropic, Artem Prilutskiy, aschank on github,
Aviv Engelberg, Axel Mierczuk, Bobbeh Rhino, bupt-Yy-young on github,
Charles Muehlberger, Christian Hesse, Christian Ullrich, Dan Fandrich,
Daniel Lang, Daniel McCarney, Daniel S. Roche, Daniel Stenberg, Daniel Wade,
dataisland, David Benjamin, David Bures, dependabot[bot],
Fengxiaoxx on github, Fernando Gallardo, Filippo Tedeschi, Florent Castelli,
Fredrik Blau, GPT-6.1 Sol, Hasan Flayyih Abdullah, Huang Yiheng,
Ilias Aberkane, İlyas Serdar Dursun, jared-m-cohen-civ on github, jdymitarai,
Johannes Schindelin, Jorge Rocamora, Joshua Rogers, JuanCarlosgg on github,
KayanoLiam on github, Kuroda Kayn, ldm0, Luna Tong, Maksim Hayder,
Marcel Raad, Martin Dukek, Max Dymond, Mihai-Gabriel Marin, minnnjuuu,
Mohammed K. Fathy, Muhamad Arga Reksapati, Nicolas Grekas, ns-ylambert,
Paolo Ganci, Patrick Monnerat, rawsun007, Ray Satiro, Rémi NICOLE,
Renan Pimentel, renovate[bot], Rhino, Richard Payne, Ron Kuper,
Roshan Ramani, Rudolf Polzer, Samuel Henrique, Sebastian Raase, Skye Soss,
Stanislav Fort, Stefan Eissing, Stephen Psaradellis, szedenik-adam on github,
tawmoto on github, Thanniru Sai Teja, Tip ten Brink, Tyler Yankee, Un1q32,
Viktor Szakats, Wonyoung Jung, xhon-pelushi, Yechan Bae, yuwk
(84 contributors)
References to bug reports and discussions on issues:
[1] = https://curl.se/bug/?i=22701
[2] = https://curl.se/bug/?i=22799
[3] = https://curl.se/bug/?i=22811
[4] = https://curl.se/bug/?i=22838
[5] = https://curl.se/bug/?i=22887
[6] = https://curl.se/bug/?i=22840
[7] = https://curl.se/bug/?i=22788
[8] = https://curl.se/bug/?i=22797
[9] = https://curl.se/bug/?i=22798
[10] = https://curl.se/bug/?i=22920
[11] = https://curl.se/bug/?i=22791
[12] = https://curl.se/bug/?i=22795
[13] = https://curl.se/bug/?i=22786
[14] = https://curl.se/bug/?i=22886
[15] = https://curl.se/bug/?i=22720
[16] = https://curl.se/bug/?i=22703
[17] = https://curl.se/bug/?i=22827
[18] = https://curl.se/bug/?i=22884
[19] = https://curl.se/bug/?i=22823
[20] = https://curl.se/bug/?i=22831
[21] = https://curl.se/bug/?i=22787
[22] = https://curl.se/bug/?i=22830
[23] = https://curl.se/bug/?i=22740
[24] = https://curl.se/bug/?i=22828
[25] = https://curl.se/bug/?i=22807
[26] = https://curl.se/bug/?i=22822
[27] = https://curl.se/bug/?i=22826
[28] = https://curl.se/bug/?i=22825
[29] = https://curl.se/bug/?i=22926
[30] = https://curl.se/bug/?i=22874
[31] = https://curl.se/bug/?i=22817
[32] = https://curl.se/bug/?i=22805
[33] = https://curl.se/bug/?i=22801
[34] = https://curl.se/bug/?i=22815
[35] = https://curl.se/bug/?i=22876
[36] = https://curl.se/bug/?i=22806
[37] = https://curl.se/bug/?i=22780
[38] = https://curl.se/bug/?i=22766
[39] = https://curl.se/bug/?i=22793
[40] = https://curl.se/bug/?i=22875
[41] = https://curl.se/bug/?i=22810
[42] = https://curl.se/bug/?i=22796
[43] = https://curl.se/bug/?i=22746
[44] = https://curl.se/bug/?i=22804
[45] = https://curl.se/bug/?i=22753
[46] = https://curl.se/bug/?i=22784
[47] = https://curl.se/bug/?i=22878
[48] = https://curl.se/bug/?i=22927
[49] = https://curl.se/bug/?i=22928
[50] = https://curl.se/bug/?i=22873
[51] = https://curl.se/bug/?i=22877
[52] = https://curl.se/bug/?i=22871
[53] = https://curl.se/bug/?i=22870
[54] = https://curl.se/bug/?i=22924
[55] = https://curl.se/bug/?i=22945
[56] = https://curl.se/bug/?i=22869
[57] = https://curl.se/bug/?i=22868
[58] = https://curl.se/bug/?i=22866
[59] = https://curl.se/bug/?i=22957
[60] = https://curl.se/bug/?i=22862
[61] = https://curl.se/bug/?i=22860
[62] = https://issues.oss-fuzz.com/issues/560352522
[63] = https://curl.se/bug/?i=22652
[64] = https://curl.se/bug/?i=22819
[65] = https://curl.se/bug/?i=22849
[66] = https://curl.se/bug/?i=544
[67] = https://curl.se/bug/?i=22839
[68] = https://curl.se/bug/?i=22981
[69] = https://curl.se/bug/?i=22221
[70] = https://curl.se/bug/?i=22843
[71] = https://curl.se/bug/?i=22984
[72] = https://curl.se/bug/?i=22911
[73] = https://curl.se/bug/?i=22910
[74] = https://curl.se/bug/?i=22896
[75] = https://curl.se/bug/?i=22900
[76] = https://curl.se/bug/?i=22971
[77] = https://curl.se/bug/?i=23021
[78] = https://curl.se/bug/?i=22901
[79] = https://curl.se/bug/?i=22902
[80] = https://curl.se/bug/?i=22897
[81] = https://curl.se/bug/?i=22898
[82] = https://curl.se/bug/?i=22905
[83] = https://curl.se/bug/?i=22906
[84] = https://curl.se/bug/?i=22998
[85] = https://curl.se/bug/?i=23018
[86] = https://curl.se/bug/?i=22963
[87] = https://curl.se/bug/?i=22899
[88] = https://curl.se/bug/?i=22903
[89] = https://curl.se/bug/?i=22895
[90] = https://curl.se/bug/?i=22890
[91] = https://curl.se/bug/?i=22893
[92] = https://curl.se/bug/?i=22888
[93] = https://curl.se/bug/?i=22889
[94] = https://curl.se/bug/?i=23020
[95] = https://curl.se/bug/?i=22857
[96] = https://curl.se/bug/?i=22982
[97] = https://curl.se/bug/?i=22961
[98] = https://curl.se/bug/?i=22977
[99] = https://curl.se/bug/?i=23012
[100] = https://curl.se/bug/?i=22969
[101] = https://curl.se/bug/?i=22974
[102] = https://curl.se/bug/?i=22923
[103] = https://curl.se/bug/?i=22917
[104] = https://curl.se/bug/?i=22970
[105] = https://curl.se/bug/?i=22964
[106] = https://curl.se/bug/?i=23013
[107] = https://curl.se/bug/?i=23016
[108] = https://curl.se/bug/?i=22916
[109] = https://curl.se/bug/?i=22947
[110] = https://curl.se/bug/?i=23019
[111] = https://curl.se/bug/?i=22942
[112] = https://curl.se/bug/?i=22941
[113] = https://curl.se/bug/?i=22932
[114] = https://curl.se/bug/?i=23017
[115] = https://curl.se/bug/?i=12414
[116] = https://curl.se/bug/?i=23015
[117] = https://curl.se/bug/?i=23011
[118] = https://issues.oss-fuzz.com/issues/563679840, https://issues.oss-fuzz.com/issues/559825608
[119] = https://curl.se/bug/?i=23008
[120] = https://curl.se/bug/?i=23002
[121] = https://curl.se/bug/?i=23005
[122] = https://curl.se/bug/?i=23001
[123] = https://curl.se/bug/?i=23040
[124] = https://curl.se/bug/?i=23003
[125] = https://curl.se/bug/?i=23089
[126] = https://curl.se/bug/?i=22995
[127] = https://curl.se/bug/?i=22997
[128] = https://curl.se/bug/?i=22996
[129] = https://curl.se/bug/?i=22993
[130] = https://curl.se/bug/?i=23290
[131] = https://curl.se/bug/?i=22991
[132] = https://curl.se/bug/?i=22950
[133] = https://curl.se/bug/?i=23086
[134] = https://curl.se/bug/?i=23085
[135] = https://curl.se/bug/?i=23370
[136] = https://curl.se/bug/?i=23062
[137] = https://curl.se/bug/?i=22968
[138] = https://curl.se/bug/?i=22944
[139] = https://curl.se/bug/?i=23060
[140] = https://curl.se/bug/?i=23083
[141] = https://curl.se/bug/?i=23289
[142] = https://curl.se/bug/?i=23287
[143] = https://curl.se/bug/?i=23080
[144] = https://curl.se/bug/?i=23078
[145] = https://curl.se/bug/?i=23068
[146] = https://curl.se/bug/?i=23069
[147] = https://curl.se/bug/?i=23273
[148] = https://curl.se/bug/?i=23283
[149] = https://curl.se/bug/?i=23061
[150] = https://curl.se/bug/?i=23071
[151] = https://curl.se/bug/?i=23067
[152] = https://curl.se/bug/?i=23063
[153] = https://curl.se/bug/?i=23072
[154] = https://curl.se/bug/?i=23064
[155] = https://curl.se/bug/?i=23055
[156] = https://curl.se/bug/?i=23234
[157] = https://curl.se/bug/?i=23058
[158] = https://curl.se/bug/?i=23056
[159] = https://curl.se/bug/?i=23054
[160] = https://curl.se/bug/?i=23051
[161] = https://curl.se/bug/?i=23245
[162] = https://curl.se/bug/?i=23052
[163] = https://curl.se/bug/?i=23006
[164] = https://curl.se/bug/?i=23023
[165] = https://curl.se/bug/?i=23034
[166] = https://curl.se/bug/?i=23043
[167] = https://curl.se/bug/?i=23045
[168] = https://curl.se/bug/?i=23245
[169] = https://curl.se/bug/?i=23259
[170] = https://curl.se/bug/?i=23334
[171] = https://curl.se/bug/?i=23014
[172] = https://curl.se/bug/?i=23280
[173] = https://curl.se/bug/?i=23037
[174] = https://curl.se/bug/?i=23038
[175] = https://curl.se/bug/?i=23035
[176] = https://curl.se/bug/?i=23261
[177] = https://curl.se/bug/?i=23274
[178] = https://curl.se/bug/?i=23030
[179] = https://curl.se/bug/?i=23028
[180] = https://curl.se/bug/?i=23027
[181] = https://curl.se/bug/?i=23026
[182] = https://curl.se/bug/?i=23327
[183] = https://github.com/git-for-windows/git/issues/6457
[184] = https://curl.se/bug/?i=23249
[185] = https://curl.se/bug/?i=23267
[186] = https://curl.se/bug/?i=23326
[187] = https://curl.se/bug/?i=23265
[188] = https://curl.se/bug/?i=23303
[189] = https://curl.se/bug/?i=23216
[190] = https://curl.se/bug/?i=23215
[191] = https://curl.se/bug/?i=23183
[192] = https://curl.se/bug/?i=23050
[193] = https://curl.se/bug/?i=23313
[194] = https://curl.se/bug/?i=23324
[195] = https://curl.se/bug/?i=23318
[196] = https://curl.se/bug/?i=23323
[197] = https://curl.se/bug/?i=23322
[198] = https://curl.se/bug/?i=23210
[199] = https://curl.se/bug/?i=23220
[200] = https://curl.se/bug/?i=23344
[201] = https://curl.se/bug/?i=23211
[202] = https://curl.se/bug/?i=23317
[203] = https://curl.se/bug/?i=23208
[204] = https://curl.se/bug/?i=23315
[205] = https://curl.se/bug/?i=23181
[206] = https://curl.se/bug/?i=23314
[207] = https://curl.se/bug/?i=23192
[208] = https://curl.se/bug/?i=23189
[209] = https://curl.se/bug/?i=23169
[210] = https://curl.se/bug/?i=23166
[211] = https://curl.se/bug/?i=23165
[212] = https://curl.se/bug/?i=23162
[213] = https://curl.se/bug/?i=23156
[214] = https://curl.se/bug/?i=23310
[215] = https://curl.se/bug/?i=23296
[216] = https://curl.se/bug/?i=23146
[217] = https://curl.se/bug/?i=23199
[218] = https://curl.se/bug/?i=23197
[219] = https://curl.se/bug/?i=23196
[220] = https://curl.se/bug/?i=23136
[221] = https://curl.se/bug/?i=23025
[222] = https://curl.se/bug/?i=23238
[223] = https://hackerone.com/reports/3971585
[224] = https://curl.se/bug/?i=23254
[225] = https://curl.se/bug/?i=23258
[226] = https://curl.se/bug/?i=23184
[227] = https://curl.se/bug/?i=23299
[228] = https://curl.se/bug/?i=23167
[229] = https://curl.se/bug/?i=23164
[230] = https://curl.se/bug/?i=23297
[231] = https://curl.se/bug/?i=23148
[232] = https://curl.se/bug/?i=23179
[233] = https://curl.se/bug/?i=23300
[234] = https://curl.se/bug/?i=23302
[235] = https://curl.se/bug/?i=22614
[236] = https://curl.se/bug/?i=23382
[237] = https://curl.se/bug/?i=23298
[238] = https://curl.se/bug/?i=23171
[239] = https://curl.se/bug/?i=23295
[240] = https://curl.se/bug/?i=23024
[241] = https://curl.se/bug/?i=23292
[242] = https://curl.se/bug/?i=23212
[243] = https://curl.se/bug/?i=23163
[244] = https://curl.se/bug/?i=23188
[245] = https://curl.se/bug/?i=23157
[246] = https://curl.se/bug/?i=23262
[247] = https://curl.se/bug/?i=23153
[248] = https://curl.se/bug/?i=23288
[249] = https://curl.se/bug/?i=23377
[250] = https://curl.se/bug/?i=23149
[251] = https://curl.se/bug/?i=23150
[252] = https://curl.se/bug/?i=23147
[253] = https://curl.se/bug/?i=23374
[254] = https://curl.se/bug/?i=23339
[256] = https://curl.se/bug/?i=23142
[257] = https://curl.se/bug/?i=23140
[258] = https://curl.se/bug/?i=23306
[259] = https://curl.se/bug/?i=23139
[260] = https://curl.se/bug/?i=23138
[261] = https://curl.se/bug/?i=23135
[262] = https://curl.se/bug/?i=23126
[263] = https://curl.se/bug/?i=23133
[264] = https://curl.se/bug/?i=23363
[266] = https://curl.se/bug/?i=23312
[267] = https://curl.se/bug/?i=23129
[271] = https://curl.se/bug/?i=23122
[272] = https://curl.se/bug/?i=23306
[273] = https://curl.se/bug/?i=23120
[275] = https://curl.se/bug/?i=23084
[276] = https://curl.se/bug/?i=23345
[279] = https://curl.se/bug/?i=23112
[282] = https://curl.se/bug/?i=23111
[289] = https://curl.se/bug/?i=23104
[290] = https://curl.se/bug/?i=23102
[291] = https://curl.se/bug/?i=23100
[292] = https://curl.se/bug/?i=23099
[296] = https://curl.se/bug/?i=23094
[297] = https://curl.se/bug/?i=23091
[298] = https://curl.se/bug/?i=23092
[299] = https://curl.se/bug/?i=23090
[300] = https://curl.se/bug/?i=22719
[301] = https://curl.se/bug/?i=23350
[302] = https://curl.se/bug/?i=23368
+28
View File
@@ -0,0 +1,28 @@
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
# SPDX-License-Identifier: curl
#
###########################################################################
SUBDIRS = curl
EXTRA_DIST = README.md
AUTOMAKE_OPTIONS = foreign no-dependencies
+20
View File
@@ -0,0 +1,20 @@
<!--
Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
SPDX-License-Identifier: curl
-->
# include
Public include files for libcurl, external users.
They are all placed in the curl subdirectory here for better fit in any kind of
environment. You must include files from here using...
#include <curl/curl.h>
... style and point the compiler's include path to the directory holding the
curl subdirectory. It makes it more likely to survive future modifications.
The public curl include files can be shared freely between different platforms
and different architectures.
+43
View File
@@ -0,0 +1,43 @@
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
# SPDX-License-Identifier: curl
#
###########################################################################
pkginclude_HEADERS = \
curl.h curlver.h easy.h mprintf.h stdcheaders.h multi.h \
typecheck-gcc.h system.h urlapi.h options.h header.h websockets.h
pkgincludedir = $(includedir)/curl
CHECKSRC = $(CS_$(V))
CS_0 = @echo " RUN " $@;
CS_1 =
CS_ = $(CS_0)
checksrc:
$(CHECKSRC)@PERL@ $(top_srcdir)/scripts/checksrc.pl -D$(top_srcdir)/include/curl $(pkginclude_HEADERS)
if NOT_CURL_CI
if DEBUGBUILD
# for debug builds, we scan the sources on all regular make invokes
all-local: checksrc
endif
endif
File diff suppressed because it is too large Load Diff
+77
View File
@@ -0,0 +1,77 @@
#ifndef CURLINC_CURLVER_H
#define CURLINC_CURLVER_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
/* This header file contains nothing but libcurl version info, generated by
a script at release-time. This was made its own header file in 7.11.2 */
/* This is the global package copyright */
#define LIBCURL_COPYRIGHT "Daniel Stenberg, <daniel@haxx.se>."
/* This is the version number of the libcurl package from which this header
file origins: */
#define LIBCURL_VERSION "8.23.0-DEV"
/* The numeric version number is also available "in parts" by using these
defines: */
#define LIBCURL_VERSION_MAJOR 8
#define LIBCURL_VERSION_MINOR 23
#define LIBCURL_VERSION_PATCH 0
/* This is the numeric version of the libcurl version number, meant for easier
parsing and comparisons by programs. The LIBCURL_VERSION_NUM define always
follows this syntax:
0xXXYYZZ
Where XX, YY and ZZ are the main version, release and patch numbers in
hexadecimal (using 8 bits each). All three numbers are always represented
using two digits. Version 1.2 would appear as "0x010200" while 9.11.7
appears as "0x090b07".
This 6-digit (24 bits) hexadecimal number does not show pre-release number,
and it is always a greater number in a more recent release. It makes
comparisons with greater than and less than work.
Note: This define is the full hex number and _does not_ use the
CURL_VERSION_BITS() macro since curl's own configure script greps for it
and needs it to contain the full number. */
#define LIBCURL_VERSION_NUM 0x081700
/*
* This is the date and time when the full source package was created. The
* timestamp is not stored in git, as the timestamp is properly set in the
* tarballs by the maketgz script.
*
* The format of the date follows this template:
*
* "2007-11-23"
*/
#define LIBCURL_TIMESTAMP "[unreleased]"
#define CURL_VERSION_BITS(x, y, z) ((x) << 16 | (y) << 8 | (z))
#define CURL_AT_LEAST_VERSION(x, y, z) \
(LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z))
#endif /* CURLINC_CURLVER_H */
+123
View File
@@ -0,0 +1,123 @@
#ifndef CURLINC_EASY_H
#define CURLINC_EASY_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
/* Flag bits in the curl_blob struct: */
#define CURL_BLOB_COPY 1 /* tell libcurl to copy the data */
#define CURL_BLOB_NOCOPY 0 /* tell libcurl to NOT copy the data */
struct curl_blob {
void *data;
size_t len;
unsigned int flags; /* bit 0 is defined, the rest are reserved and should be
left zeroes */
};
CURL_EXTERN CURL *curl_easy_init(void);
CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...);
CURL_EXTERN CURLcode curl_easy_perform(CURL *curl);
CURL_EXTERN void curl_easy_cleanup(CURL *curl);
/*
* NAME curl_easy_getinfo()
*
* DESCRIPTION
*
* Request internal information from the curl session with this function.
* The third argument MUST be pointing to the specific type of the used option
* which is documented in each man page of the option. The data pointed to
* is filled in accordingly and can be relied upon only if the function
* returns CURLE_OK. This function is intended to get used *AFTER* a performed
* transfer, all results from this function are undefined until the transfer
* is completed.
*/
CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...);
/*
* NAME curl_easy_duphandle()
*
* DESCRIPTION
*
* Creates a new curl session handle with the same options set for the handle
* passed in. Duplicating a handle could only be a matter of cloning data and
* options, internal state info and things like persistent connections cannot
* be transferred. It is useful in multi-threaded applications when you can run
* curl_easy_duphandle() for each new thread to avoid a series of identical
* curl_easy_setopt() invokes in every thread.
*/
CURL_EXTERN CURL *curl_easy_duphandle(CURL *curl);
/*
* NAME curl_easy_reset()
*
* DESCRIPTION
*
* Re-initializes a curl handle to the default values. This puts back the
* handle to the same state as it was in when it was created.
*
* It does keep: live connections, the Session ID cache, the DNS cache and the
* cookies.
*/
CURL_EXTERN void curl_easy_reset(CURL *curl);
/*
* NAME curl_easy_recv()
*
* DESCRIPTION
*
* Receives data from the connected socket. Use after successful
* curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
*/
CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen,
size_t *n);
/*
* NAME curl_easy_send()
*
* DESCRIPTION
*
* Sends data over the connected socket. Use after successful
* curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
*/
CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer,
size_t buflen, size_t *n);
/*
* NAME curl_easy_upkeep()
*
* DESCRIPTION
*
* Performs connection upkeep for the given session handle.
*/
CURL_EXTERN CURLcode curl_easy_upkeep(CURL *curl);
#ifdef __cplusplus
} /* end of extern "C" */
#endif
#endif
+74
View File
@@ -0,0 +1,74 @@
#ifndef CURLINC_HEADER_H
#define CURLINC_HEADER_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
struct curl_header {
char *name; /* this might not use the same case */
char *value;
size_t amount; /* number of headers using this name */
size_t index; /* ... of this instance, 0 or higher */
unsigned int origin; /* see bits below */
void *anchor; /* handle privately used by libcurl */
};
/* 'origin' bits */
#define CURLH_HEADER (1 << 0) /* plain server header */
#define CURLH_TRAILER (1 << 1) /* trailers */
#define CURLH_CONNECT (1 << 2) /* CONNECT headers */
#define CURLH_1XX (1 << 3) /* 1xx headers */
#define CURLH_PSEUDO (1 << 4) /* pseudo headers */
typedef enum {
CURLHE_OK,
CURLHE_BADINDEX, /* header exists but not with this index */
CURLHE_MISSING, /* no such header exists */
CURLHE_NOHEADERS, /* no headers at all exist (yet) */
CURLHE_NOREQUEST, /* no request with this number was used */
CURLHE_OUT_OF_MEMORY, /* out of memory while processing */
CURLHE_BAD_ARGUMENT, /* a function argument was not okay */
CURLHE_NOT_BUILT_IN /* if API was disabled in the build */
} CURLHcode;
CURL_EXTERN CURLHcode curl_easy_header(CURL *curl,
const char *name,
size_t nameindex,
unsigned int origin,
int request,
struct curl_header **hout);
CURL_EXTERN struct curl_header *curl_easy_nextheader(CURL *curl,
unsigned int origin,
int request,
struct curl_header *prev);
#ifdef __cplusplus
} /* end of extern "C" */
#endif
#endif /* CURLINC_HEADER_H */
+85
View File
@@ -0,0 +1,85 @@
#ifndef CURLINC_MPRINTF_H
#define CURLINC_MPRINTF_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include <stdarg.h>
#include <stdio.h> /* needed for FILE */
#include "curl.h" /* for CURL_EXTERN */
#ifdef __cplusplus
extern "C" {
#endif
#ifndef CURL_TEMP_PRINTF
#if (defined(__GNUC__) || defined(__clang__) || \
defined(__IAR_SYSTEMS_ICC__)) && \
defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
!defined(CURL_NO_FMT_CHECKS)
#if defined(__MINGW32__) && !defined(__clang__)
#ifdef __MINGW_PRINTF_FORMAT /* mingw-w64 3.0.0+. Needs stdio.h. */
#define CURL_TEMP_PRINTF(fmt, arg) \
__attribute__((format(__MINGW_PRINTF_FORMAT, fmt, arg)))
#else
#define CURL_TEMP_PRINTF(fmt, arg)
#endif
#else
#define CURL_TEMP_PRINTF(fmt, arg) \
__attribute__((format(printf, fmt, arg)))
#endif
#else
#define CURL_TEMP_PRINTF(fmt, arg)
#endif
#endif
CURL_EXTERN int curl_mprintf(const char *format, ...)
CURL_TEMP_PRINTF(1, 2);
CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...)
CURL_TEMP_PRINTF(2, 3);
CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...)
CURL_TEMP_PRINTF(2, 3);
CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength,
const char *format, ...)
CURL_TEMP_PRINTF(3, 4);
CURL_EXTERN int curl_mvprintf(const char *format, va_list args)
CURL_TEMP_PRINTF(1, 0);
CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args)
CURL_TEMP_PRINTF(2, 0);
CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args)
CURL_TEMP_PRINTF(2, 0);
CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength,
const char *format, va_list args)
CURL_TEMP_PRINTF(3, 0);
CURL_EXTERN char *curl_maprintf(const char *format, ...)
CURL_TEMP_PRINTF(1, 2);
CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args)
CURL_TEMP_PRINTF(1, 0);
#undef CURL_TEMP_PRINTF
#ifdef __cplusplus
} /* end of extern "C" */
#endif
#endif /* CURLINC_MPRINTF_H */
+561
View File
@@ -0,0 +1,561 @@
#ifndef CURLINC_MULTI_H
#define CURLINC_MULTI_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
/*
* This is an "external" header file. Do not give away any internals here!
*
* GOALS
*
* o Enable a "pull" interface. The application that uses libcurl decides where
* and when to ask libcurl to get/send data.
*
* o Enable multiple simultaneous transfers in the same thread without making
* it complicated for the application.
*
* o Enable the application to select() on its own file descriptors and curl's
* file descriptors simultaneous easily.
*
*/
/*
* This header file should not really need to include "curl.h" since curl.h
* itself includes this file and we expect user applications to do #include
* <curl/curl.h> without the need for especially including multi.h.
*
* For some reason we added this include here at one point, and rather than to
* break existing (wrongly written) libcurl applications, we leave it as-is
* but with this warning attached.
*/
#include "curl.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void CURLM;
typedef enum {
CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or
curl_multi_socket*() soon */
CURLM_OK,
CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */
CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */
CURLM_OUT_OF_MEMORY, /* if you ever get this, you are in deep sh*t */
CURLM_INTERNAL_ERROR, /* this is a libcurl bug */
CURLM_BAD_SOCKET, /* the passed in socket argument did not match */
CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */
CURLM_ADDED_ALREADY, /* an easy handle already added to a multi handle was
attempted to get added - again */
CURLM_RECURSIVE_API_CALL, /* an api function was called from inside a
callback */
CURLM_WAKEUP_FAILURE, /* wakeup is unavailable or failed */
CURLM_BAD_FUNCTION_ARGUMENT, /* function called with a bad parameter */
CURLM_ABORTED_BY_CALLBACK,
CURLM_UNRECOVERABLE_POLL,
CURLM_LAST
} CURLMcode;
/* You can check for CURLM_CALL_MULTI_SOCKET too in the same style it works
for curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */
#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM
/* bitmask bits for CURLMOPT_PIPELINING */
#define CURLPIPE_NOTHING 0L
#define CURLPIPE_HTTP1 1L
#define CURLPIPE_MULTIPLEX 2L
typedef enum {
CURLMSG_NONE, /* first, not used */
CURLMSG_DONE, /* This easy handle has completed. 'result' contains
the CURLcode of the transfer */
CURLMSG_LAST /* last, not used */
} CURLMSG;
struct CURLMsg {
CURLMSG msg; /* what this message means */
CURL *easy_handle; /* the handle it concerns */
union {
void *whatever; /* message-specific data */
CURLcode result; /* return code for transfer */
} data;
};
typedef struct CURLMsg CURLMsg;
/* Based on poll(2) structure and values.
* We do not use pollfd and POLL* constants explicitly
* to cover platforms without poll(). */
#define CURL_WAIT_POLLIN 0x0001
#define CURL_WAIT_POLLPRI 0x0002
#define CURL_WAIT_POLLOUT 0x0004
struct curl_waitfd {
curl_socket_t fd;
short events;
short revents;
};
/*
* Name: curl_multi_init()
*
* Desc: initialize multi-style curl usage
*
* Returns: a new CURLM handle to use in all 'curl_multi' functions.
*/
CURL_EXTERN CURLM *curl_multi_init(void);
/*
* Name: curl_multi_add_handle()
*
* Desc: add a standard curl handle to the multi stack
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *m,
CURL *curl);
/*
* Name: curl_multi_remove_handle()
*
* Desc: removes a curl handle from the multi stack again
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *m,
CURL *curl);
/*
* Name: curl_multi_fdset()
*
* Desc: Ask curl for its fd_set sets. The app can use these to select() or
* poll() on. We want curl_multi_perform() called as soon as one of
* them are ready.
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *m,
fd_set *read_fd_set,
fd_set *write_fd_set,
fd_set *exc_fd_set,
int *max_fd);
/*
* Name: curl_multi_wait()
*
* Desc: Poll on all fds within a CURLM set as well as any
* additional fds passed to the function.
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_wait(CURLM *m,
struct curl_waitfd extra_fds[],
unsigned int extra_nfds,
int timeout_ms,
int *ret);
/*
* Name: curl_multi_poll()
*
* Desc: Poll on all fds within a CURLM set as well as any
* additional fds passed to the function.
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_poll(CURLM *m,
struct curl_waitfd extra_fds[],
unsigned int extra_nfds,
int timeout_ms,
int *ret);
/*
* Name: curl_multi_wakeup()
*
* Desc: wakes up a sleeping curl_multi_poll call.
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_wakeup(CURLM *m);
/*
* Name: curl_multi_perform()
*
* Desc: When the app thinks there is data available for curl it calls this
* function to read/write whatever there is right now. This returns
* as soon as the reads and writes are done. This function does not
* require that there actually is data available for reading or that
* data can be written, it can be called. It returns the number of
* handles that still transfer data in the second argument's
* integer-pointer.
*
* Returns: CURLMcode type, general multi error code. *NOTE* that this only
* returns errors etc regarding the whole multi stack. There might
* still have occurred problems on individual transfers even when
* this returns OK.
*/
CURL_EXTERN CURLMcode curl_multi_perform(CURLM *m,
int *running_handles);
/*
* Name: curl_multi_cleanup()
*
* Desc: Cleans up and removes a whole multi stack. It does not free or
* touch any individual easy handles in any way. We need to define
* in what state those handles are going to be if this function is
* called in the middle of a transfer.
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *m);
/*
* Name: curl_multi_info_read()
*
* Desc: Ask the multi handle if there is any messages/informationals from
* the individual transfers. Messages include informationals such as
* error code from the transfer or the fact that a transfer is
* completed. More details on these should be written down as well.
*
* Repeated calls to this function return a new struct each time,
* until a special "end of msgs" struct is returned as a signal that
* there is no more to get at this point.
*
* The data the returned pointer points to does not survive calling
* curl_multi_cleanup().
*
* The 'CURLMsg' struct is meant to be simple and only contain basic
* information. If more involved information is wanted, we provide
* the particular "transfer handle" in that struct and that
* should/could/would be used in subsequent curl_easy_getinfo() calls
* (or similar). The point being that we must never expose complex
* structs to applications, as then we undoubtably get backwards
* compatibility problems in the future.
*
* Returns: A pointer to a filled-in struct, or NULL if it failed or ran out
* of structs. It also writes the number of messages left in the
* queue (after this read) in the integer the second argument points
* to.
*/
CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *m,
int *msgs_in_queue);
/*
* Name: curl_multi_strerror()
*
* Desc: The curl_multi_strerror function may be used to turn a CURLMcode
* value into the equivalent human readable error string. This is
* useful for printing meaningful error messages.
*
* Returns: A pointer to a null-terminated error message.
*/
CURL_EXTERN const char *curl_multi_strerror(CURLMcode error);
/*
* Name: curl_multi_socket() and
* curl_multi_socket_all()
*
* Desc: An alternative version of curl_multi_perform() that allows the
* application to pass in one of the file descriptors that have been
* detected to have "action" on them and let libcurl perform.
* See man page for details.
*/
#define CURL_POLL_NONE 0
#define CURL_POLL_IN 1
#define CURL_POLL_OUT 2
#define CURL_POLL_INOUT 3
#define CURL_POLL_REMOVE 4
#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD
#define CURL_CSELECT_IN 0x01
#define CURL_CSELECT_OUT 0x02
#define CURL_CSELECT_ERR 0x04
typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */
curl_socket_t s, /* socket */
int what, /* see above */
void *userp, /* private callback
pointer */
void *socketp); /* private socket
pointer */
/*
* Name: curl_multi_timer_callback
*
* Desc: Called by libcurl whenever the library detects a change in the
* maximum number of milliseconds the app is allowed to wait before
* curl_multi_socket() or curl_multi_perform() must be called
* (to allow libcurl's timed events to take place).
*
* Returns: The callback should return zero.
*/
typedef int (*curl_multi_timer_callback)(CURLM *m, /* multi handle */
long timeout_ms, /* see above */
void *userp); /* private callback
pointer */
CURL_EXTERN CURLMcode CURL_DEPRECATED(7.19.5, "Use curl_multi_socket_action()")
curl_multi_socket(CURLM *m, curl_socket_t s, int *running_handles);
CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *m,
curl_socket_t s,
int ev_bitmask,
int *running_handles);
CURL_EXTERN CURLMcode CURL_DEPRECATED(7.19.5, "Use curl_multi_socket_action()")
curl_multi_socket_all(CURLM *m, int *running_handles);
#ifndef CURL_ALLOW_OLD_MULTI_SOCKET
/* This macro below was added in 7.16.3 to push users who recompile to use
* the new curl_multi_socket_action() instead of the old curl_multi_socket()
*/
#define curl_multi_socket(x, y, z) curl_multi_socket_action(x, y, 0, z)
#endif
/*
* Name: curl_multi_timeout()
*
* Desc: Returns the maximum number of milliseconds the app is allowed to
* wait before curl_multi_socket() or curl_multi_perform() must be
* called (to allow libcurl's timed events to take place).
*
* Returns: CURLM error code.
*/
CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *m,
long *timeout_ms);
typedef enum {
/* This is the socket callback function pointer */
CURLOPT(CURLMOPT_SOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 1),
/* This is the argument passed to the socket callback */
CURLOPT(CURLMOPT_SOCKETDATA, CURLOPTTYPE_OBJECTPOINT, 2),
/* set to 1 to enable pipelining for this multi handle */
CURLOPT(CURLMOPT_PIPELINING, CURLOPTTYPE_LONG, 3),
/* This is the timer callback function pointer */
CURLOPT(CURLMOPT_TIMERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 4),
/* This is the argument passed to the timer callback */
CURLOPT(CURLMOPT_TIMERDATA, CURLOPTTYPE_OBJECTPOINT, 5),
/* maximum number of entries in the connection cache */
CURLOPT(CURLMOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 6),
/* maximum number of (pipelining) connections to one host */
CURLOPT(CURLMOPT_MAX_HOST_CONNECTIONS, CURLOPTTYPE_LONG, 7),
/* maximum number of requests in a pipeline */
CURLOPT(CURLMOPT_MAX_PIPELINE_LENGTH, CURLOPTTYPE_LONG, 8),
/* a connection with a content-length longer than this
is not considered for pipelining */
CURLOPT(CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 9),
/* a connection with a chunk length longer than this
is not considered for pipelining */
CURLOPT(CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 10),
/* a list of site names(+port) that are blocked from pipelining */
CURLOPT(CURLMOPT_PIPELINING_SITE_BL, CURLOPTTYPE_OBJECTPOINT, 11),
/* a list of server types that are blocked from pipelining */
CURLOPT(CURLMOPT_PIPELINING_SERVER_BL, CURLOPTTYPE_OBJECTPOINT, 12),
/* maximum number of open connections in total */
CURLOPT(CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPTTYPE_LONG, 13),
/* This is the server push callback function pointer */
CURLOPT(CURLMOPT_PUSHFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 14),
/* This is the argument passed to the server push callback */
CURLOPT(CURLMOPT_PUSHDATA, CURLOPTTYPE_OBJECTPOINT, 15),
/* maximum number of concurrent streams to support on a connection */
CURLOPT(CURLMOPT_MAX_CONCURRENT_STREAMS, CURLOPTTYPE_LONG, 16),
/* network has changed, adjust caches/connection reuse */
CURLOPT(CURLMOPT_NETWORK_CHANGED, CURLOPTTYPE_LONG, 17),
/* This is the notify callback function pointer */
CURLOPT(CURLMOPT_NOTIFYFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 18),
/* This is the argument passed to the notify callback */
CURLOPT(CURLMOPT_NOTIFYDATA, CURLOPTTYPE_OBJECTPOINT, 19),
/* maximum number of threads used with threaded DNS resolver */
CURLOPT(CURLMOPT_RESOLVE_THREADS_MAX, CURLOPTTYPE_LONG, 20),
/* set to 1L for not joining threads when multi is cleaned up */
CURLOPT(CURLMOPT_QUICK_EXIT, CURLOPTTYPE_LONG, 21),
CURLMOPT_LASTENTRY /* the last unused */
} CURLMoption;
/* Definition of bits for the CURLMOPT_NETWORK_CHANGED argument: */
/* - CURLMNWC_CLEAR_ALL tells libcurl to clear "everything" that could be
associated with this network, including both connections and DNS data. */
#define CURLMNWC_CLEAR_ALL (1L << 0)
/* - CURLMNWC_CLEAR_CONNS tells libcurl to prevent further reuse of existing
connections. Connections that are idle are closed. Ongoing transfers do
continue with the connection they have. */
#define CURLMNWC_CLEAR_CONNS (1L << 1)
/* - CURLMNWC_CLEAR_DNS tells libcurl to clear the DNS cache associated with
this multi handle. Ongoing transfers keep using their already resolved
addresses, but future name resolutions are performed again. */
#define CURLMNWC_CLEAR_DNS (1L << 2)
/*
* Name: curl_multi_setopt()
*
* Desc: Sets options for the multi handle.
*
* Returns: CURLM error code.
*/
CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *m,
CURLMoption option, ...);
/*
* Name: curl_multi_assign()
*
* Desc: This function sets an association in the multi handle between the
* given socket and a private pointer of the application. This is
* (only) useful for curl_multi_socket uses.
*
* Returns: CURLM error code.
*/
CURL_EXTERN CURLMcode curl_multi_assign(CURLM *m,
curl_socket_t sockfd, void *sockp);
/*
* Name: curl_multi_get_handles()
*
* Desc: Returns an allocated array holding all handles currently added to
* the multi handle. Marks the final entry with a NULL pointer. If
* there is no easy handle added to the multi handle, this function
* returns an array with the first entry as a NULL pointer.
*
* Returns: NULL on failure, otherwise a CURL **array pointer
*/
CURL_EXTERN CURL **curl_multi_get_handles(CURLM *m);
typedef enum {
CURLMINFO_NONE, /* first, never use this */
/* The number of easy handles currently managed by the multi handle,
* e.g. have been added but not yet removed. */
CURLMINFO_XFERS_CURRENT = 1,
/* The number of easy handles running, e.g. not done and not queueing. */
CURLMINFO_XFERS_RUNNING = 2,
/* The number of easy handles waiting to start, e.g. for a connection
* to become available due to limits on parallelism, max connections
* or other factors. */
CURLMINFO_XFERS_PENDING = 3,
/* The number of easy handles finished, waiting for their results to
* be read via `curl_multi_info_read()`. */
CURLMINFO_XFERS_DONE = 4,
/* The total number of easy handles added to the multi handle, ever. */
CURLMINFO_XFERS_ADDED = 5,
CURLMINFO_LASTENTRY /* the last unused */
} CURLMinfo_offt;
/*
* Name: curl_multi_get_offt()
*
* Desc: Retrieves a numeric value for the `CURLMINFO_*` enums.
*
* Returns: CULRM_OK or error when value could not be obtained.
*/
CURL_EXTERN CURLMcode curl_multi_get_offt(CURLM *m,
CURLMinfo_offt info,
curl_off_t *pvalue);
/*
* Name: curl_push_callback
*
* Desc: This callback gets called when a new stream is being pushed by the
* server. It approves or denies the new stream. It can also decide
* to completely fail the connection.
*
* Returns: CURL_PUSH_OK, CURL_PUSH_DENY or CURL_PUSH_ERROROUT
*/
#define CURL_PUSH_OK 0
#define CURL_PUSH_DENY 1
#define CURL_PUSH_ERROROUT 2 /* added in 7.72.0 */
struct curl_pushheaders; /* forward declaration only */
CURL_EXTERN char *curl_pushheader_bynum(struct curl_pushheaders *h,
size_t num);
CURL_EXTERN char *curl_pushheader_byname(struct curl_pushheaders *h,
const char *name);
typedef int (*curl_push_callback)(CURL *parent,
CURL *easy,
size_t num_headers,
struct curl_pushheaders *headers,
void *userp);
/*
* Name: curl_multi_waitfds()
*
* Desc: Ask curl for fds for polling. The app can use these to poll on.
* We want curl_multi_perform() called as soon as one of them are
* ready. Passing zero size allows to get a number of fds.
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_waitfds(CURLM *m,
struct curl_waitfd *ufds,
unsigned int size,
unsigned int *fd_count);
/*
* Notifications dispatched by a multi handle, when enabled.
*/
#define CURLMNOTIFY_INFO_READ 0
#define CURLMNOTIFY_EASY_DONE 1
#define CURLMNOTIFY_LAST 2 /* last, not used */
/*
* Callback to install via CURLMOPT_NOTIFYFUNCTION.
*/
typedef void (*curl_notify_callback)(CURLM *m,
unsigned int notification,
CURL *easy,
void *user_data);
CURL_EXTERN CURLMcode curl_multi_notify_disable(CURLM *m,
unsigned int notification);
CURL_EXTERN CURLMcode curl_multi_notify_enable(CURLM *m,
unsigned int notification);
#ifdef __cplusplus
} /* end of extern "C" */
#endif
#endif
+70
View File
@@ -0,0 +1,70 @@
#ifndef CURLINC_OPTIONS_H
#define CURLINC_OPTIONS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
CURLOT_LONG, /* long (a range of values) */
CURLOT_VALUES, /* (a defined set or bitmask) */
CURLOT_OFF_T, /* curl_off_t (a range of values) */
CURLOT_OBJECT, /* pointer (void *) */
CURLOT_STRING, /* (char * to null-terminated buffer) */
CURLOT_SLIST, /* (struct curl_slist *) */
CURLOT_CBPTR, /* (void * passed as-is to a callback) */
CURLOT_BLOB, /* blob (struct curl_blob *) */
CURLOT_FUNCTION /* function pointer */
} curl_easytype;
/* Flag bits */
/* "alias" means it is provided for old programs to remain functional,
we prefer another name */
#define CURLOT_FLAG_ALIAS (1 << 0)
/* The CURLOPTTYPE_* id ranges can still be used to figure out what type/size
to use for curl_easy_setopt() for the given id */
struct curl_easyoption {
const char *name;
CURLoption id;
curl_easytype type;
unsigned int flags;
};
CURL_EXTERN const struct curl_easyoption *
curl_easy_option_by_name(const char *name);
CURL_EXTERN const struct curl_easyoption *
curl_easy_option_by_id(CURLoption id);
CURL_EXTERN const struct curl_easyoption *
curl_easy_option_next(const struct curl_easyoption *prev);
#ifdef __cplusplus
} /* end of extern "C" */
#endif
#endif /* CURLINC_OPTIONS_H */
+35
View File
@@ -0,0 +1,35 @@
#ifndef CURLINC_STDCHEADERS_H
#define CURLINC_STDCHEADERS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include <sys/types.h>
size_t fread(void *, size_t, size_t, FILE *);
size_t fwrite(const void *, size_t, size_t, FILE *);
int strcasecmp(const char *, const char *);
int strncasecmp(const char *, const char *, size_t);
#endif /* CURLINC_STDCHEADERS_H */
+399
View File
@@ -0,0 +1,399 @@
#ifndef CURLINC_SYSTEM_H
#define CURLINC_SYSTEM_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
/*
* Try to keep one section per platform, compiler and architecture, otherwise,
* if an existing section is reused for a different one and later on the
* original is adjusted, probably the piggybacking one can be adversely
* changed.
*
* In order to differentiate between platforms/compilers/architectures use
* only compiler built-in predefined preprocessor symbols.
*
* curl_off_t
* ----------
*
* For any given platform/compiler curl_off_t MUST be typedef'ed to a 64-bit
* wide signed integral data type. The width of this data type must remain
* constant and independent of any possible large file support settings.
*
* As a general rule, curl_off_t shall not be mapped to off_t. This rule shall
* only be violated if off_t is the only 64-bit data type available and the
* size of off_t is independent of large file support settings. Keep your
* build on the safe side avoiding an off_t gating. If you have a 64-bit
* off_t then take for sure that another 64-bit data type exists, dig deeper
* to find it.
*
*/
#ifdef __DJGPP__
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__BORLANDC__)
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__POCC__)
# ifdef _MSC_VER
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# else
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__LCC__)
# ifdef __MCST__ /* MCST eLbrus Compiler Collection */
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
# else /* Local (or Little) C Compiler */
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# endif
#elif defined(macintosh)
# include <ConditionalMacros.h>
# if TYPE_LONGLONG
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# else
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
#elif defined(__TANDEM)
# ifndef __LP64
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# else
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
# endif
#elif defined(UNDER_CE)
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__MINGW32__)
# include <inttypes.h>
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T PRId64
# define CURL_FORMAT_CURL_OFF_TU PRIu64
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_PULL_SYS_TYPES_H 1
#elif defined(__VMS)
# ifdef __VAX
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# else
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
#elif defined(__OS400__)
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
#elif defined(__MVS__)
# ifdef _LONG_LONG
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# else /* _LP64 and default */
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
#elif defined(__370__)
# if defined(__IBMC__) || defined(__IBMCPP__)
# ifdef _LONG_LONG
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# else /* _LP64 and default */
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
# endif
#elif defined(TPF)
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__TINYC__) /* also known as tcc */
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) /* Oracle Solaris Studio */
# if !defined(__LP64) && (defined(__ILP32) || \
defined(__i386) || \
defined(__sparcv8) || \
defined(__sparcv8plus))
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(__LP64) || \
defined(__amd64) || defined(__sparcv9)
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
#elif defined(__xlc__) /* IBM xlc compiler */
# ifndef _LP64
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# else
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
#elif defined(__hpux) /* HP aCC compiler */
# ifndef _LP64
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# else
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
/* ===================================== */
/* KEEP MSVC THE PENULTIMATE ENTRY */
/* ===================================== */
#elif defined(_MSC_VER)
# if _MSC_VER >= 1800
# include <inttypes.h>
# define CURL_FORMAT_CURL_OFF_T PRId64
# define CURL_FORMAT_CURL_OFF_TU PRIu64
# else
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# endif
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# define CURL_TYPEOF_CURL_SOCKLEN_T int
/* ===================================== */
/* KEEP GENERIC GCC THE LAST ENTRY */
/* ===================================== */
#elif defined(__GNUC__) && !defined(_SCO_DS)
# if !defined(__LP64__) && \
(defined(__ILP32__) || defined(__i386__) || defined(__hppa__) || \
defined(__ppc__) || defined(__powerpc__) || defined(__arm__) || \
defined(__sparc__) || defined(__mips__) || defined(__sh__) || \
defined(__XTENSA__) || \
(defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 4) || \
(defined(__LONG_MAX__) && __LONG_MAX__ == 2147483647L))
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# if (__GNUC__ >= 4) || \
((__GNUC__ == 3) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 4))
# define CURL_POPCOUNT64(x) __builtin_popcountll(x)
# define CURL_CTZ64(x) __builtin_ctzll(x)
# endif
# elif defined(__LP64__) || \
defined(__x86_64__) || defined(__ppc64__) || defined(__sparc64__) || \
defined(__e2k__) || \
(defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 8) || \
(defined(__LONG_MAX__) && __LONG_MAX__ == 9223372036854775807L)
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# if (__GNUC__ >= 4) || \
((__GNUC__ == 3) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 4))
# define CURL_POPCOUNT64(x) __builtin_popcountl(x)
# define CURL_CTZ64(x) __builtin_ctzl(x)
# endif
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
#else
/* generic "safe guess" on old 32-bit style */
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
#endif
#ifdef _AIX
/* AIX needs <sys/poll.h> */
#define CURL_PULL_SYS_POLL_H
#endif
/* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file
sys/types.h is required here to properly make type definitions below. */
#ifdef CURL_PULL_SYS_TYPES_H
# include <sys/types.h>
#endif
/* CURL_PULL_SYS_SOCKET_H is defined above when inclusion of header file
sys/socket.h is required here to properly make type definitions below. */
#ifdef CURL_PULL_SYS_SOCKET_H
# include <sys/socket.h>
#endif
/* CURL_PULL_SYS_POLL_H is defined above when inclusion of header file
sys/poll.h is required here to properly make type definitions below. */
#ifdef CURL_PULL_SYS_POLL_H
# include <sys/poll.h>
#endif
/* Data type definition of curl_socklen_t. */
#ifdef CURL_TYPEOF_CURL_SOCKLEN_T
typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t;
#endif
/* Data type definition of curl_off_t. */
#ifdef CURL_TYPEOF_CURL_OFF_T
typedef CURL_TYPEOF_CURL_OFF_T curl_off_t;
#endif
#endif /* CURLINC_SYSTEM_H */
+964
View File
@@ -0,0 +1,964 @@
#ifndef CURLINC_TYPECHECK_GCC_H
#define CURLINC_TYPECHECK_GCC_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
/* wraps curl_easy_setopt() with type checking */
/* To add a new kind of warning, add an
* if(curlcheck_sometype_option(_curl_opt))
* if(!curlcheck_sometype(value))
* Wcurl_easy_setopt_err_sometype();
* block and define curlcheck_sometype_option, curlcheck_sometype and
* Wcurl_easy_setopt_err_sometype below
*
* NOTE: We use two nested 'if' statements here instead of the && operator, in
* order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x
* when compiling with -Wlogical-op.
*
* To add an option that uses the same type as an existing option, you need
* to extend the appropriate _curl_*_option macro
*/
#define curl_easy_setopt(handle, option, value) \
__extension__({ \
if(__builtin_constant_p(option)) { \
CURL_IGNORE_DEPRECATION( \
if(curlcheck_long_option(option)) \
if(!curlcheck_long(value)) \
Wcurl_easy_setopt_err_long(); \
if(curlcheck_off_t_option(option)) \
if(!curlcheck_off_t(value)) \
Wcurl_easy_setopt_err_curl_off_t(); \
if(curlcheck_string_option(option)) \
if(!curlcheck_string(value)) \
Wcurl_easy_setopt_err_string(); \
if((option) == CURLOPT_PRIVATE) { } \
if(curlcheck_write_cb_option(option)) \
if(!curlcheck_write_cb(value)) \
Wcurl_easy_setopt_err_write_callback(); \
if(curlcheck_curl_option(option)) \
if(!curlcheck_curl(value)) \
Wcurl_easy_setopt_err_curl(); \
if((option) == CURLOPT_RESOLVER_START_FUNCTION) \
if(!curlcheck_resolver_start_callback(value)) \
Wcurl_easy_setopt_err_resolver_start_callback(); \
if((option) == CURLOPT_READFUNCTION) \
if(!curlcheck_read_cb(value)) \
Wcurl_easy_setopt_err_read_cb(); \
if((option) == CURLOPT_IOCTLFUNCTION) \
if(!curlcheck_ioctl_cb(value)) \
Wcurl_easy_setopt_err_ioctl_cb(); \
if((option) == CURLOPT_SOCKOPTFUNCTION) \
if(!curlcheck_sockopt_cb(value)) \
Wcurl_easy_setopt_err_sockopt_cb(); \
if((option) == CURLOPT_OPENSOCKETFUNCTION) \
if(!curlcheck_opensocket_cb(value)) \
Wcurl_easy_setopt_err_opensocket_cb(); \
if((option) == CURLOPT_PROGRESSFUNCTION) \
if(!curlcheck_progress_cb(value)) \
Wcurl_easy_setopt_err_progress_cb(); \
if((option) == CURLOPT_XFERINFOFUNCTION) \
if(!curlcheck_xferinfo_cb(value)) \
Wcurl_easy_setopt_err_xferinfo_cb(); \
if((option) == CURLOPT_DEBUGFUNCTION) \
if(!curlcheck_debug_cb(value)) \
Wcurl_easy_setopt_err_debug_cb(); \
if((option) == CURLOPT_SSL_CTX_FUNCTION) \
if(!curlcheck_ssl_ctx_cb(value)) \
Wcurl_easy_setopt_err_ssl_ctx_cb(); \
if(curlcheck_conv_cb_option(option)) \
if(!curlcheck_conv_cb(value)) \
Wcurl_easy_setopt_err_conv_cb(); \
if((option) == CURLOPT_SEEKFUNCTION) \
if(!curlcheck_seek_cb(value)) \
Wcurl_easy_setopt_err_seek_cb(); \
if((option) == CURLOPT_CHUNK_BGN_FUNCTION) \
if(!curlcheck_chunk_bgn_cb(value)) \
Wcurl_easy_setopt_err_chunk_bgn_cb(); \
if((option) == CURLOPT_CHUNK_END_FUNCTION) \
if(!curlcheck_chunk_end_cb(value)) \
Wcurl_easy_setopt_err_chunk_end_cb(); \
if((option) == CURLOPT_CLOSESOCKETFUNCTION) \
if(!curlcheck_close_socket_cb(value)) \
Wcurl_easy_setopt_err_close_socket_cb(); \
if((option) == CURLOPT_FNMATCH_FUNCTION) \
if(!curlcheck_fnmatch_cb(value)) \
Wcurl_easy_setopt_err_fnmatch_cb(); \
if((option) == CURLOPT_HSTSREADFUNCTION) \
if(!curlcheck_hstsread_cb(value)) \
Wcurl_easy_setopt_err_hstsread_cb(); \
if((option) == CURLOPT_HSTSWRITEFUNCTION) \
if(!curlcheck_hstswrite_cb(value)) \
Wcurl_easy_setopt_err_hstswrite_cb(); \
if((option) == CURLOPT_SSH_HOSTKEYFUNCTION) \
if(!curlcheck_ssh_hostkey_cb(value)) \
Wcurl_easy_setopt_err_ssh_hostkey_cb(); \
if((option) == CURLOPT_SSH_KEYFUNCTION) \
if(!curlcheck_ssh_key_cb(value)) \
Wcurl_easy_setopt_err_ssh_key_cb(); \
if((option) == CURLOPT_INTERLEAVEFUNCTION) \
if(!curlcheck_interleave_cb(value)) \
Wcurl_easy_setopt_err_interleave_cb(); \
if((option) == CURLOPT_PREREQFUNCTION) \
if(!curlcheck_prereq_cb(value)) \
Wcurl_easy_setopt_err_prereq_cb(); \
if((option) == CURLOPT_TRAILERFUNCTION) \
if(!curlcheck_trailer_cb(value)) \
Wcurl_easy_setopt_err_trailer_cb(); \
if(curlcheck_cb_data_option(option)) \
if(!curlcheck_cb_data(value)) \
Wcurl_easy_setopt_err_cb_data(); \
if((option) == CURLOPT_ERRORBUFFER) \
if(!curlcheck_error_buffer(value)) \
Wcurl_easy_setopt_err_error_buffer(); \
if((option) == CURLOPT_CURLU) \
if(!curlcheck_ptr((value), CURLU)) \
Wcurl_easy_setopt_err_curlu(); \
if((option) == CURLOPT_STDERR) \
if(!curlcheck_FILE(value)) \
Wcurl_easy_setopt_err_FILE(); \
if(curlcheck_postfields_option(option)) \
if(!curlcheck_postfields(value)) \
Wcurl_easy_setopt_err_postfields(); \
if((option) == CURLOPT_HTTPPOST) \
if(!curlcheck_arr((value), struct curl_httppost)) \
Wcurl_easy_setopt_err_curl_httpost(); \
if((option) == CURLOPT_MIMEPOST) \
if(!curlcheck_ptr((value), curl_mime)) \
Wcurl_easy_setopt_err_curl_mimepost(); \
if(curlcheck_slist_option(option)) \
if(!curlcheck_arr((value), struct curl_slist)) \
Wcurl_easy_setopt_err_curl_slist(); \
if((option) == CURLOPT_SHARE) \
if(!curlcheck_ptr((value), CURLSH)) \
Wcurl_easy_setopt_err_CURLSH(); \
) \
} \
(curl_easy_setopt)(handle, option, value); \
})
/* wraps curl_easy_getinfo() with type checking */
#define curl_easy_getinfo(handle, info, arg) \
__extension__({ \
if(__builtin_constant_p(info)) { \
CURL_IGNORE_DEPRECATION( \
if(curlcheck_string_info(info)) \
if(!curlcheck_arr((arg), char *)) \
Wcurl_easy_getinfo_err_string(); \
if(curlcheck_long_info(info)) \
if(!curlcheck_arr((arg), long)) \
Wcurl_easy_getinfo_err_long(); \
if(curlcheck_double_info(info)) \
if(!curlcheck_arr((arg), double)) \
Wcurl_easy_getinfo_err_double(); \
if(curlcheck_slist_info(info)) \
if(!curlcheck_arr((arg), struct curl_slist *)) \
Wcurl_easy_getinfo_err_curl_slist(); \
if(curlcheck_tlssessioninfo_info(info)) \
if(!curlcheck_arr((arg), struct curl_tlssessioninfo *)) \
Wcurl_easy_getinfo_err_curl_tlssessioninfo(); \
if(curlcheck_certinfo_info(info)) \
if(!curlcheck_arr((arg), struct curl_certinfo *)) \
Wcurl_easy_getinfo_err_curl_certinfo(); \
if(curlcheck_socket_info(info)) \
if(!curlcheck_arr((arg), curl_socket_t)) \
Wcurl_easy_getinfo_err_curl_socket(); \
if(curlcheck_off_t_info(info)) \
if(!curlcheck_arr((arg), curl_off_t)) \
Wcurl_easy_getinfo_err_curl_off_t(); \
) \
} \
(curl_easy_getinfo)(handle, info, arg); \
})
#define curl_multi_setopt(handle, option, value) \
__extension__({ \
if(__builtin_constant_p(option)) { \
if(curlcheck_long_option(option)) \
if(!curlcheck_long(value)) \
Wcurl_multi_setopt_err_long(); \
if(curlcheck_off_t_option(option)) \
if(!curlcheck_off_t(value)) \
Wcurl_multi_setopt_err_curl_off_t(); \
if(curlcheck_multicb_data_option(option)) \
if(!curlcheck_cb_data(value)) \
Wcurl_multi_setopt_err_cb_data(); \
if(curlcheck_charpp_option(option)) \
if(!curlcheck_ptrptr(value, char)) \
Wcurl_multi_setopt_err_charpp(); \
if((option) == CURLMOPT_NOTIFYFUNCTION) \
if(!curlcheck_multinotify_cb(value)) \
Wcurl_multi_setopt_err_notifycb(); \
if((option) == CURLMOPT_PUSHFUNCTION) \
if(!curlcheck_multipush_cb(value)) \
Wcurl_multi_setopt_err_pushcb(); \
if((option) == CURLMOPT_SOCKETFUNCTION) \
if(!curlcheck_multisocket_cb(value)) \
Wcurl_multi_setopt_err_socketcb(); \
if((option) == CURLMOPT_TIMERFUNCTION) \
if(!curlcheck_multitimer_cb(value)) \
Wcurl_multi_setopt_err_timercb(); \
} \
(curl_multi_setopt)(handle, option, value); \
})
/* evaluates to true if the option takes a data argument to pass to a
callback */
#define curlcheck_multicb_data_option(option) \
((option) == CURLMOPT_NOTIFYDATA || \
(option) == CURLMOPT_PUSHDATA || \
(option) == CURLMOPT_SOCKETDATA || \
(option) == CURLMOPT_TIMERDATA || \
0)
/* evaluates to true if the option takes a char ** argument */
#define curlcheck_charpp_option(option) \
((option) == CURLMOPT_PIPELINING_SERVER_BL || \
(option) == CURLMOPT_PIPELINING_SITE_BL || \
0)
/* evaluates to true if expr is of type curl_multi_timer_callback */
#define curlcheck_multitimer_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_multi_timer_callback))
/* evaluates to true if expr is of type curl_socket_callback */
#define curlcheck_multisocket_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_socket_callback))
/* evaluates to true if expr is of type curl_push_callback */
#define curlcheck_multipush_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_push_callback))
/* evaluates to true if expr is of type curl_push_callback */
#define curlcheck_multinotify_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_notify_callback))
/*
* Make sure that the functions are called with three arguments
*/
#define curl_share_setopt(share, opt, param) \
(curl_share_setopt)(share, opt, param)
/* the actual warnings, triggered by calling the Wcurl_easy_setopt_err*
* functions */
/* To define a new warning, use _CURL_WARNING(identifier, "message") */
#define CURLWARNING(id, message) \
static void __attribute__((__warning__(message))) \
__attribute__((__unused__)) __attribute__((__noinline__)) \
id(void) { __asm__(""); }
CURLWARNING(Wcurl_multi_setopt_err_long,
"curl_multi_setopt expects a long argument")
CURLWARNING(Wcurl_multi_setopt_err_curl_off_t,
"curl_multi_setopt expects a curl_off_t argument")
CURLWARNING(Wcurl_multi_setopt_err_cb_data,
"curl_multi_setopt expects a 'void *' argument")
CURLWARNING(Wcurl_multi_setopt_err_charpp,
"curl_multi_setopt expects a 'char **' argument")
CURLWARNING(Wcurl_multi_setopt_err_pushcb,
"curl_multi_setopt expects a curl_push_callback argument")
CURLWARNING(Wcurl_multi_setopt_err_notifycb,
"curl_multi_setopt expects a curl_notify_callback argument")
CURLWARNING(Wcurl_multi_setopt_err_socketcb,
"curl_multi_setopt expects a curl_socket_callback argument")
CURLWARNING(Wcurl_multi_setopt_err_timercb,
"curl_multi_setopt expects a curl_multi_timer_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_long,
"curl_easy_setopt expects a long argument")
CURLWARNING(Wcurl_easy_setopt_err_curl_off_t,
"curl_easy_setopt expects a curl_off_t argument")
CURLWARNING(Wcurl_easy_setopt_err_string,
"curl_easy_setopt expects a "
"string ('char *' or char[]) argument")
CURLWARNING(Wcurl_easy_setopt_err_write_callback,
"curl_easy_setopt expects a curl_write_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_resolver_start_callback,
"curl_easy_setopt expects a "
"curl_resolver_start_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_read_cb,
"curl_easy_setopt expects a curl_read_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_ioctl_cb,
"curl_easy_setopt expects a curl_ioctl_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_sockopt_cb,
"curl_easy_setopt expects a curl_sockopt_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_opensocket_cb,
"curl_easy_setopt expects a "
"curl_opensocket_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_progress_cb,
"curl_easy_setopt expects a curl_progress_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_xferinfo_cb,
"curl_easy_setopt expects a curl_xferinfo_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_debug_cb,
"curl_easy_setopt expects a curl_debug_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_ssl_ctx_cb,
"curl_easy_setopt expects a curl_ssl_ctx_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_conv_cb,
"curl_easy_setopt expects a curl_conv_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_seek_cb,
"curl_easy_setopt expects a curl_seek_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_cb_data,
"curl_easy_setopt expects a "
"private data pointer as argument")
CURLWARNING(Wcurl_easy_setopt_err_chunk_bgn_cb,
"curl_easy_setopt expects a curl_chunk_bgn_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_chunk_end_cb,
"curl_easy_setopt expects a curl_chunk_end_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_close_socket_cb,
"curl_easy_setopt expects a curl_closesocket_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_fnmatch_cb,
"curl_easy_setopt expects a curl_fnmatch_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_hstsread_cb,
"curl_easy_setopt expects a curl_hstsread_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_hstswrite_cb,
"curl_easy_setopt expects a curl_hstswrite_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_ssh_key_cb,
"curl_easy_setopt expects a curl_sshkeycallback argument")
CURLWARNING(Wcurl_easy_setopt_err_ssh_hostkey_cb,
"curl_easy_setopt expects a curl_sshhostkeycallback argument")
CURLWARNING(Wcurl_easy_setopt_err_interleave_cb,
"curl_easy_setopt expects a curl_interleave_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_prereq_cb,
"curl_easy_setopt expects a curl_prereq_callback argument")
CURLWARNING(Wcurl_easy_setopt_err_trailer_cb,
"curl_easy_setopt expects a curl_trailerfunc_ok argument")
CURLWARNING(Wcurl_easy_setopt_err_error_buffer,
"curl_easy_setopt expects a "
"char buffer of CURL_ERROR_SIZE as argument")
CURLWARNING(Wcurl_easy_setopt_err_curlu,
"curl_easy_setopt expects a 'CURLU *' argument")
CURLWARNING(Wcurl_easy_setopt_err_curl,
"curl_easy_setopt expects a 'CURL *' argument")
CURLWARNING(Wcurl_easy_setopt_err_FILE,
"curl_easy_setopt expects a 'FILE *' argument")
CURLWARNING(Wcurl_easy_setopt_err_postfields,
"curl_easy_setopt expects a 'void *' or 'char *' argument")
CURLWARNING(Wcurl_easy_setopt_err_curl_httpost,
"curl_easy_setopt expects a 'struct curl_httppost *' "
"argument")
CURLWARNING(Wcurl_easy_setopt_err_curl_mimepost,
"curl_easy_setopt expects a 'curl_mime *' "
"argument")
CURLWARNING(Wcurl_easy_setopt_err_curl_slist,
"curl_easy_setopt expects a 'struct curl_slist *' argument")
CURLWARNING(Wcurl_easy_setopt_err_CURLSH,
"curl_easy_setopt expects a CURLSH* argument")
CURLWARNING(Wcurl_easy_getinfo_err_string,
"curl_easy_getinfo expects a pointer to 'char *'")
CURLWARNING(Wcurl_easy_getinfo_err_long,
"curl_easy_getinfo expects a pointer to long")
CURLWARNING(Wcurl_easy_getinfo_err_double,
"curl_easy_getinfo expects a pointer to double")
CURLWARNING(Wcurl_easy_getinfo_err_curl_slist,
"curl_easy_getinfo expects a pointer to 'struct curl_slist *'")
CURLWARNING(Wcurl_easy_getinfo_err_curl_tlssessioninfo,
"curl_easy_getinfo expects a pointer to "
"'struct curl_tlssessioninfo *'")
CURLWARNING(Wcurl_easy_getinfo_err_curl_certinfo,
"curl_easy_getinfo expects a pointer to "
"'struct curl_certinfo *'")
CURLWARNING(Wcurl_easy_getinfo_err_curl_socket,
"curl_easy_getinfo expects a pointer to curl_socket_t")
CURLWARNING(Wcurl_easy_getinfo_err_curl_off_t,
"curl_easy_getinfo expects a pointer to curl_off_t")
/* groups of curl_easy_setops options that take the same type of argument */
/* evaluates to true if option takes a long argument */
#define curlcheck_long_option(option) \
(0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT)
#define curlcheck_off_t_option(option) \
(((option) > CURLOPTTYPE_OFF_T) && ((option) < CURLOPTTYPE_BLOB))
/* option takes a CURL * argument */
#define curlcheck_curl_option(option) \
((option) == CURLOPT_STREAM_DEPENDS || \
(option) == CURLOPT_STREAM_DEPENDS_E || \
0)
/* evaluates to true if option takes a char* argument */
#define curlcheck_string_option(option) \
((option) == CURLOPT_ABSTRACT_UNIX_SOCKET || \
(option) == CURLOPT_ACCEPT_ENCODING || \
(option) == CURLOPT_ALTSVC || \
(option) == CURLOPT_CAINFO || \
(option) == CURLOPT_CAPATH || \
(option) == CURLOPT_COOKIE || \
(option) == CURLOPT_COOKIEFILE || \
(option) == CURLOPT_COOKIEJAR || \
(option) == CURLOPT_COOKIELIST || \
(option) == CURLOPT_CRLFILE || \
(option) == CURLOPT_CUSTOMREQUEST || \
(option) == CURLOPT_DEFAULT_PROTOCOL || \
(option) == CURLOPT_DNS_INTERFACE || \
(option) == CURLOPT_DNS_LOCAL_IP4 || \
(option) == CURLOPT_DNS_LOCAL_IP6 || \
(option) == CURLOPT_DNS_SERVERS || \
(option) == CURLOPT_DOH_URL || \
(option) == CURLOPT_ECH || \
(option) == CURLOPT_EGDSOCKET || \
(option) == CURLOPT_FTP_ACCOUNT || \
(option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \
(option) == CURLOPT_FTPPORT || \
(option) == CURLOPT_HAPROXY_CLIENT_IP || \
(option) == CURLOPT_HSTS || \
(option) == CURLOPT_INTERFACE || \
(option) == CURLOPT_ISSUERCERT || \
(option) == CURLOPT_KEYPASSWD || \
(option) == CURLOPT_KRBLEVEL || \
(option) == CURLOPT_LOGIN_OPTIONS || \
(option) == CURLOPT_MAIL_AUTH || \
(option) == CURLOPT_MAIL_FROM || \
(option) == CURLOPT_NETRC_FILE || \
(option) == CURLOPT_NOPROXY || \
(option) == CURLOPT_PASSWORD || \
(option) == CURLOPT_PINNEDPUBLICKEY || \
(option) == CURLOPT_PRE_PROXY || \
(option) == CURLOPT_PROTOCOLS_STR || \
(option) == CURLOPT_PROXY || \
(option) == CURLOPT_PROXY_CAINFO || \
(option) == CURLOPT_PROXY_CAPATH || \
(option) == CURLOPT_PROXY_CRLFILE || \
(option) == CURLOPT_PROXY_ISSUERCERT || \
(option) == CURLOPT_PROXY_KEYPASSWD || \
(option) == CURLOPT_PROXY_PINNEDPUBLICKEY || \
(option) == CURLOPT_PROXY_SERVICE_NAME || \
(option) == CURLOPT_PROXY_SSL_CIPHER_LIST || \
(option) == CURLOPT_PROXY_SSLCERT || \
(option) == CURLOPT_PROXY_SSLCERTTYPE || \
(option) == CURLOPT_PROXY_SSLKEY || \
(option) == CURLOPT_PROXY_SSLKEYTYPE || \
(option) == CURLOPT_PROXY_TLS13_CIPHERS || \
(option) == CURLOPT_PROXY_TLSAUTH_PASSWORD || \
(option) == CURLOPT_PROXY_TLSAUTH_TYPE || \
(option) == CURLOPT_PROXY_TLSAUTH_USERNAME || \
(option) == CURLOPT_PROXYPASSWORD || \
(option) == CURLOPT_PROXYUSERNAME || \
(option) == CURLOPT_PROXYUSERPWD || \
(option) == CURLOPT_RANDOM_FILE || \
(option) == CURLOPT_RANGE || \
(option) == CURLOPT_REDIR_PROTOCOLS_STR || \
(option) == CURLOPT_REFERER || \
(option) == CURLOPT_REQUEST_TARGET || \
(option) == CURLOPT_RTSP_SESSION_ID || \
(option) == CURLOPT_RTSP_STREAM_URI || \
(option) == CURLOPT_RTSP_TRANSPORT || \
(option) == CURLOPT_SASL_AUTHZID || \
(option) == CURLOPT_SERVICE_NAME || \
(option) == CURLOPT_SOCKS5_GSSAPI_SERVICE || \
(option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \
(option) == CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 || \
(option) == CURLOPT_SSH_KNOWNHOSTS || \
(option) == CURLOPT_SSH_PRIVATE_KEYFILE || \
(option) == CURLOPT_SSH_PUBLIC_KEYFILE || \
(option) == CURLOPT_SSLCERT || \
(option) == CURLOPT_SSLCERTTYPE || \
(option) == CURLOPT_SSLENGINE || \
(option) == CURLOPT_SSLKEY || \
(option) == CURLOPT_SSLKEYTYPE || \
(option) == CURLOPT_SSL_CIPHER_LIST || \
(option) == CURLOPT_SSL_EC_CURVES || \
(option) == CURLOPT_SSL_SIGNATURE_ALGORITHMS || \
(option) == CURLOPT_TLS13_CIPHERS || \
(option) == CURLOPT_TLSAUTH_PASSWORD || \
(option) == CURLOPT_TLSAUTH_TYPE || \
(option) == CURLOPT_TLSAUTH_USERNAME || \
(option) == CURLOPT_UNIX_SOCKET_PATH || \
(option) == CURLOPT_URL || \
(option) == CURLOPT_USERAGENT || \
(option) == CURLOPT_USERNAME || \
(option) == CURLOPT_AWS_SIGV4 || \
(option) == CURLOPT_HTTPSIG_HEADERS || \
(option) == CURLOPT_HTTPSIG_KEY || \
(option) == CURLOPT_HTTPSIG_KEYID || \
(option) == CURLOPT_USERPWD || \
(option) == CURLOPT_XOAUTH2_BEARER || \
0)
/* evaluates to true if option takes a curl_write_callback argument */
#define curlcheck_write_cb_option(option) \
((option) == CURLOPT_HEADERFUNCTION || \
(option) == CURLOPT_WRITEFUNCTION)
/* evaluates to true if option takes a curl_conv_callback argument */
#define curlcheck_conv_cb_option(option) \
((option) == CURLOPT_CONV_TO_NETWORK_FUNCTION || \
(option) == CURLOPT_CONV_FROM_NETWORK_FUNCTION || \
(option) == CURLOPT_CONV_FROM_UTF8_FUNCTION)
/* evaluates to true if option takes a data argument to pass to a callback */
#define curlcheck_cb_data_option(option) \
((option) == CURLOPT_CHUNK_DATA || \
(option) == CURLOPT_CLOSESOCKETDATA || \
(option) == CURLOPT_DEBUGDATA || \
(option) == CURLOPT_FNMATCH_DATA || \
(option) == CURLOPT_HEADERDATA || \
(option) == CURLOPT_HSTSREADDATA || \
(option) == CURLOPT_HSTSWRITEDATA || \
(option) == CURLOPT_INTERLEAVEDATA || \
(option) == CURLOPT_IOCTLDATA || \
(option) == CURLOPT_OPENSOCKETDATA || \
(option) == CURLOPT_PREREQDATA || \
(option) == CURLOPT_XFERINFODATA || \
(option) == CURLOPT_READDATA || \
(option) == CURLOPT_SEEKDATA || \
(option) == CURLOPT_SOCKOPTDATA || \
(option) == CURLOPT_SSH_KEYDATA || \
(option) == CURLOPT_SSL_CTX_DATA || \
(option) == CURLOPT_WRITEDATA || \
(option) == CURLOPT_RESOLVER_START_DATA || \
(option) == CURLOPT_TRAILERDATA || \
(option) == CURLOPT_SSH_HOSTKEYDATA || \
0)
/* evaluates to true if option takes a POST data argument (void* or char*) */
#define curlcheck_postfields_option(option) \
((option) == CURLOPT_POSTFIELDS || \
(option) == CURLOPT_COPYPOSTFIELDS || \
0)
/* evaluates to true if option takes a struct curl_slist * argument */
#define curlcheck_slist_option(option) \
((option) == CURLOPT_HTTP200ALIASES || \
(option) == CURLOPT_HTTPHEADER || \
(option) == CURLOPT_MAIL_RCPT || \
(option) == CURLOPT_POSTQUOTE || \
(option) == CURLOPT_PREQUOTE || \
(option) == CURLOPT_PROXYHEADER || \
(option) == CURLOPT_QUOTE || \
(option) == CURLOPT_RESOLVE || \
(option) == CURLOPT_TELNETOPTIONS || \
(option) == CURLOPT_CONNECT_TO || \
0)
/* groups of curl_easy_getinfo infos that take the same type of argument */
/* evaluates to true if info expects a pointer to char * argument */
#define curlcheck_string_info(info) \
(CURLINFO_STRING < (info) && (info) < CURLINFO_LONG && \
(info) != CURLINFO_PRIVATE)
/* evaluates to true if info expects a pointer to long argument */
#define curlcheck_long_info(info) \
(CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE)
/* evaluates to true if info expects a pointer to double argument */
#define curlcheck_double_info(info) \
(CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST)
/* true if info expects a pointer to struct curl_slist * argument */
#define curlcheck_slist_info(info) \
(((info) == CURLINFO_SSL_ENGINES) || \
((info) == CURLINFO_COOKIELIST))
/* true if info expects a pointer to struct curl_tlssessioninfo * argument */
#define curlcheck_tlssessioninfo_info(info) \
(((info) == CURLINFO_TLS_SSL_PTR) || \
((info) == CURLINFO_TLS_SESSION))
/* true if info expects a pointer to struct curl_certinfo * argument */
#define curlcheck_certinfo_info(info) ((info) == CURLINFO_CERTINFO)
/* true if info expects a pointer to struct curl_socket_t argument */
#define curlcheck_socket_info(info) \
(CURLINFO_SOCKET < (info) && (info) < CURLINFO_OFF_T)
/* true if info expects a pointer to curl_off_t argument */
#define curlcheck_off_t_info(info) \
(CURLINFO_OFF_T < (info))
/*
* typecheck helpers -- check whether given expression has requested type
*/
/* For pointers, you can use the curlcheck_ptr/curlcheck_arr macros,
* otherwise define a new macro. Search for __builtin_types_compatible_p
* in the GCC manual.
* NOTE: these macros MUST NOT EVALUATE their arguments! The argument is
* the actual expression passed to the curl_easy_setopt macro. This
* means that you can only apply the sizeof and __typeof__ operators, no
* == or whatsoever.
*/
/* XXX: should evaluate to true if expr is a pointer or a char[] array */
#define curlcheck_any_ptr(expr) \
(sizeof(expr) == sizeof(void *) || \
__builtin_types_compatible_p(__typeof__(expr), char[]))
/* evaluates to true if expr is NULL */
/* XXX: must not evaluate expr, so this check is not accurate */
#define curlcheck_NULL(expr) \
(__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL)))
/* evaluates to true if expr is type*, const type* or NULL */
#define curlcheck_ptr(expr, type) \
(curlcheck_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), type *) || \
__builtin_types_compatible_p(__typeof__(expr), const type *))
/* evaluates to true if expr is type**, const type** or NULL */
#define curlcheck_ptrptr(expr, type) \
(curlcheck_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), type **) || \
__builtin_types_compatible_p(__typeof__(expr), type *[]) || \
__builtin_types_compatible_p(__typeof__(expr), const type *[]) || \
__builtin_types_compatible_p(__typeof__(expr), const type **))
/* evaluates to true if expr is one of type[], type*, NULL or const type* */
#define curlcheck_arr(expr, type) \
(curlcheck_ptr((expr), type) || \
__builtin_types_compatible_p(__typeof__(expr), type []))
/* evaluates to true if expr is a string */
#define curlcheck_string(expr) \
(curlcheck_arr((expr), char) || \
curlcheck_arr((expr), signed char) || \
curlcheck_arr((expr), unsigned char))
/* evaluates to true if expr is a CURL * */
#define curlcheck_curl(expr) \
(curlcheck_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), CURL *))
/* evaluates to true if expr is a long (no matter the signedness)
* XXX: for now, int is also accepted (and therefore short and char, which
* are promoted to int when passed to a variadic function) */
#define curlcheck_long(expr) \
( \
((sizeof(long) != sizeof(int)) && \
(__builtin_types_compatible_p(__typeof__(expr), long) || \
__builtin_types_compatible_p(__typeof__(expr), signed long) || \
__builtin_types_compatible_p(__typeof__(expr), unsigned long))) \
|| \
((sizeof(long) == sizeof(int)) && \
(__builtin_types_compatible_p(__typeof__(expr), long) || \
__builtin_types_compatible_p(__typeof__(expr), signed long) || \
__builtin_types_compatible_p(__typeof__(expr), unsigned long) || \
__builtin_types_compatible_p(__typeof__(expr), int) || \
__builtin_types_compatible_p(__typeof__(expr), signed int) || \
__builtin_types_compatible_p(__typeof__(expr), unsigned int) || \
__builtin_types_compatible_p(__typeof__(expr), short) || \
__builtin_types_compatible_p(__typeof__(expr), signed short) || \
__builtin_types_compatible_p(__typeof__(expr), unsigned short) || \
__builtin_types_compatible_p(__typeof__(expr), char) || \
__builtin_types_compatible_p(__typeof__(expr), signed char) || \
__builtin_types_compatible_p(__typeof__(expr), unsigned char))) \
)
/* evaluates to true if expr is of type curl_off_t */
#define curlcheck_off_t(expr) \
(__builtin_types_compatible_p(__typeof__(expr), curl_off_t))
/* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */
/* XXX: also check size of a char[] array? */
#define curlcheck_error_buffer(expr) \
(curlcheck_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), char *) || \
__builtin_types_compatible_p(__typeof__(expr), char[]))
/* evaluates to true if expr is of type (const) void* or (const) FILE* */
#if 0
#define curlcheck_cb_data(expr) \
(curlcheck_ptr((expr), void) || \
curlcheck_ptr((expr), FILE))
#else /* be less strict */
#define curlcheck_cb_data(expr) \
curlcheck_any_ptr(expr)
#endif
/* evaluates to true if expr is of type FILE* */
#define curlcheck_FILE(expr) \
(curlcheck_NULL(expr) || \
(__builtin_types_compatible_p(__typeof__(expr), FILE *)))
/* evaluates to true if expr can be passed as POST data (void* or char*) */
#define curlcheck_postfields(expr) \
(curlcheck_ptr((expr), void) || \
curlcheck_arr((expr), char) || \
curlcheck_arr((expr), unsigned char))
/* helper: __builtin_types_compatible_p distinguishes between functions and
* function pointers, hide it */
#define curlcheck_cb_compatible(func, type) \
(__builtin_types_compatible_p(__typeof__(func), type) || \
__builtin_types_compatible_p(__typeof__(func) *, type))
/* evaluates to true if expr is of type curl_resolver_start_callback */
#define curlcheck_resolver_start_callback(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_resolver_start_callback))
/* evaluates to true if expr is of type curl_read_callback or "similar" */
#define curlcheck_read_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), __typeof__(fread) *) || \
curlcheck_cb_compatible((expr), curl_read_callback) || \
curlcheck_cb_compatible((expr), Wcurl_read_callback1) || \
curlcheck_cb_compatible((expr), Wcurl_read_callback2) || \
curlcheck_cb_compatible((expr), Wcurl_read_callback3) || \
curlcheck_cb_compatible((expr), Wcurl_read_callback4) || \
curlcheck_cb_compatible((expr), Wcurl_read_callback5) || \
curlcheck_cb_compatible((expr), Wcurl_read_callback6))
typedef size_t (*Wcurl_read_callback1)(char *, size_t, size_t, void *);
typedef size_t (*Wcurl_read_callback2)(char *, size_t, size_t, const void *);
typedef size_t (*Wcurl_read_callback3)(char *, size_t, size_t, FILE *);
typedef size_t (*Wcurl_read_callback4)(void *, size_t, size_t, void *);
typedef size_t (*Wcurl_read_callback5)(void *, size_t, size_t, const void *);
typedef size_t (*Wcurl_read_callback6)(void *, size_t, size_t, FILE *);
/* evaluates to true if expr is of type curl_write_callback or "similar" */
#define curlcheck_write_cb(expr) \
(curlcheck_read_cb(expr) || \
curlcheck_cb_compatible((expr), __typeof__(fwrite) *) || \
curlcheck_cb_compatible((expr), curl_write_callback) || \
curlcheck_cb_compatible((expr), Wcurl_write_callback1) || \
curlcheck_cb_compatible((expr), Wcurl_write_callback2) || \
curlcheck_cb_compatible((expr), Wcurl_write_callback3) || \
curlcheck_cb_compatible((expr), Wcurl_write_callback4) || \
curlcheck_cb_compatible((expr), Wcurl_write_callback5) || \
curlcheck_cb_compatible((expr), Wcurl_write_callback6))
typedef size_t (*Wcurl_write_callback1)(const char *, size_t, size_t, void *);
typedef size_t (*Wcurl_write_callback2)(const char *, size_t, size_t,
const void *);
typedef size_t (*Wcurl_write_callback3)(const char *, size_t, size_t, FILE *);
typedef size_t (*Wcurl_write_callback4)(const void *, size_t, size_t, void *);
typedef size_t (*Wcurl_write_callback5)(const void *, size_t, size_t,
const void *);
typedef size_t (*Wcurl_write_callback6)(const void *, size_t, size_t, FILE *);
/* evaluates to true if expr is of type curl_ioctl_callback or "similar" */
#define curlcheck_ioctl_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_ioctl_callback) || \
curlcheck_cb_compatible((expr), Wcurl_ioctl_callback1) || \
curlcheck_cb_compatible((expr), Wcurl_ioctl_callback2) || \
curlcheck_cb_compatible((expr), Wcurl_ioctl_callback3) || \
curlcheck_cb_compatible((expr), Wcurl_ioctl_callback4))
typedef curlioerr (*Wcurl_ioctl_callback1)(CURL *, int, void *);
typedef curlioerr (*Wcurl_ioctl_callback2)(CURL *, int, const void *);
typedef curlioerr (*Wcurl_ioctl_callback3)(CURL *, curliocmd, void *);
typedef curlioerr (*Wcurl_ioctl_callback4)(CURL *, curliocmd, const void *);
/* evaluates to true if expr is of type curl_sockopt_callback or "similar" */
#define curlcheck_sockopt_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_sockopt_callback) || \
curlcheck_cb_compatible((expr), Wcurl_sockopt_callback1) || \
curlcheck_cb_compatible((expr), Wcurl_sockopt_callback2))
typedef int (*Wcurl_sockopt_callback1)(void *, curl_socket_t, curlsocktype);
typedef int (*Wcurl_sockopt_callback2)(const void *, curl_socket_t,
curlsocktype);
/* evaluates to true if expr is of type curl_opensocket_callback or
"similar" */
#define curlcheck_opensocket_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_opensocket_callback) || \
curlcheck_cb_compatible((expr), Wcurl_opensocket_callback1) || \
curlcheck_cb_compatible((expr), Wcurl_opensocket_callback2) || \
curlcheck_cb_compatible((expr), Wcurl_opensocket_callback3) || \
curlcheck_cb_compatible((expr), Wcurl_opensocket_callback4))
typedef curl_socket_t (*Wcurl_opensocket_callback1)
(void *, curlsocktype, struct curl_sockaddr *);
typedef curl_socket_t (*Wcurl_opensocket_callback2)
(void *, curlsocktype, const struct curl_sockaddr *);
typedef curl_socket_t (*Wcurl_opensocket_callback3)
(const void *, curlsocktype, struct curl_sockaddr *);
typedef curl_socket_t (*Wcurl_opensocket_callback4)
(const void *, curlsocktype, const struct curl_sockaddr *);
/* evaluates to true if expr is of type curl_progress_callback or "similar" */
#define curlcheck_progress_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_progress_callback) || \
curlcheck_cb_compatible((expr), Wcurl_progress_callback1) || \
curlcheck_cb_compatible((expr), Wcurl_progress_callback2))
typedef int (*Wcurl_progress_callback1)(void *,
double, double, double, double);
typedef int (*Wcurl_progress_callback2)(const void *,
double, double, double, double);
/* evaluates to true if expr is of type curl_xferinfo_callback */
#define curlcheck_xferinfo_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_xferinfo_callback))
/* evaluates to true if expr is of type curl_debug_callback or "similar" */
#define curlcheck_debug_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_debug_callback) || \
curlcheck_cb_compatible((expr), Wcurl_debug_callback1) || \
curlcheck_cb_compatible((expr), Wcurl_debug_callback2) || \
curlcheck_cb_compatible((expr), Wcurl_debug_callback3) || \
curlcheck_cb_compatible((expr), Wcurl_debug_callback4) || \
curlcheck_cb_compatible((expr), Wcurl_debug_callback5) || \
curlcheck_cb_compatible((expr), Wcurl_debug_callback6) || \
curlcheck_cb_compatible((expr), Wcurl_debug_callback7) || \
curlcheck_cb_compatible((expr), Wcurl_debug_callback8))
typedef int (*Wcurl_debug_callback1)(CURL *,
curl_infotype, char *, size_t, void *);
typedef int (*Wcurl_debug_callback2)(CURL *,
curl_infotype, char *, size_t, const void *);
typedef int (*Wcurl_debug_callback3)(CURL *,
curl_infotype, const char *, size_t, void *);
typedef int (*Wcurl_debug_callback4)(CURL *,
curl_infotype, const char *, size_t, const void *);
typedef int (*Wcurl_debug_callback5)(CURL *,
curl_infotype, unsigned char *, size_t, void *);
typedef int (*Wcurl_debug_callback6)(CURL *,
curl_infotype, unsigned char *, size_t, const void *);
typedef int (*Wcurl_debug_callback7)(CURL *,
curl_infotype, const unsigned char *, size_t, void *);
typedef int (*Wcurl_debug_callback8)(CURL *,
curl_infotype, const unsigned char *, size_t, const void *);
/* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */
/* this is getting even messier... */
#define curlcheck_ssl_ctx_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_ssl_ctx_callback) || \
curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback1) || \
curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback2) || \
curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback3) || \
curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback4) || \
curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback5) || \
curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback6) || \
curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback7) || \
curlcheck_cb_compatible((expr), Wcurl_ssl_ctx_callback8))
typedef CURLcode (*Wcurl_ssl_ctx_callback1)(CURL *, void *, void *);
typedef CURLcode (*Wcurl_ssl_ctx_callback2)(CURL *, void *, const void *);
typedef CURLcode (*Wcurl_ssl_ctx_callback3)(CURL *, const void *, void *);
typedef CURLcode (*Wcurl_ssl_ctx_callback4)(CURL *, const void *,
const void *);
#ifdef HEADER_SSL_H
/* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX
* this of course breaks if we are included before OpenSSL headers...
*/
typedef CURLcode (*Wcurl_ssl_ctx_callback5)(CURL *, SSL_CTX *, void *);
typedef CURLcode (*Wcurl_ssl_ctx_callback6)(CURL *, SSL_CTX *, const void *);
typedef CURLcode (*Wcurl_ssl_ctx_callback7)(CURL *, const SSL_CTX *, void *);
typedef CURLcode (*Wcurl_ssl_ctx_callback8)(CURL *, const SSL_CTX *,
const void *);
#else
typedef Wcurl_ssl_ctx_callback1 Wcurl_ssl_ctx_callback5;
typedef Wcurl_ssl_ctx_callback1 Wcurl_ssl_ctx_callback6;
typedef Wcurl_ssl_ctx_callback1 Wcurl_ssl_ctx_callback7;
typedef Wcurl_ssl_ctx_callback1 Wcurl_ssl_ctx_callback8;
#endif
/* evaluates to true if expr is of type curl_conv_callback or "similar" */
#define curlcheck_conv_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_conv_callback) || \
curlcheck_cb_compatible((expr), Wcurl_conv_callback1) || \
curlcheck_cb_compatible((expr), Wcurl_conv_callback2) || \
curlcheck_cb_compatible((expr), Wcurl_conv_callback3) || \
curlcheck_cb_compatible((expr), Wcurl_conv_callback4))
typedef CURLcode (*Wcurl_conv_callback1)(char *, size_t length);
typedef CURLcode (*Wcurl_conv_callback2)(const char *, size_t length);
typedef CURLcode (*Wcurl_conv_callback3)(void *, size_t length);
typedef CURLcode (*Wcurl_conv_callback4)(const void *, size_t length);
/* evaluates to true if expr is of type curl_seek_callback or "similar" */
#define curlcheck_seek_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_seek_callback) || \
curlcheck_cb_compatible((expr), Wcurl_seek_callback1) || \
curlcheck_cb_compatible((expr), Wcurl_seek_callback2))
typedef CURLcode (*Wcurl_seek_callback1)(void *, curl_off_t, int);
typedef CURLcode (*Wcurl_seek_callback2)(const void *, curl_off_t, int);
/* evaluates to true if expr is of type curl_chunk_bgn_callback */
#define curlcheck_chunk_bgn_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_chunk_bgn_callback) || \
curlcheck_cb_compatible((expr), Wcurl_chunk_bgn_callback1) || \
curlcheck_cb_compatible((expr), Wcurl_chunk_bgn_callback2))
typedef long (*Wcurl_chunk_bgn_callback1)(struct curl_fileinfo *,
void *, int);
typedef long (*Wcurl_chunk_bgn_callback2)(void *, void *, int);
/* evaluates to true if expr is of type curl_chunk_end_callback */
#define curlcheck_chunk_end_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_chunk_end_callback))
/* evaluates to true if expr is of type curl_closesocket_callback */
#define curlcheck_close_socket_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_closesocket_callback))
/* evaluates to true if expr is of type curl_fnmatch_callback */
#define curlcheck_fnmatch_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_fnmatch_callback))
/* evaluates to true if expr is of type curl_hstsread_callback */
#define curlcheck_hstsread_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_hstsread_callback))
/* evaluates to true if expr is of type curl_hstswrite_callback */
#define curlcheck_hstswrite_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_hstswrite_callback))
/* evaluates to true if expr is of type curl_sshhostkeycallback */
#define curlcheck_ssh_hostkey_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_sshhostkeycallback))
/* evaluates to true if expr is of type curl_sshkeycallback */
#define curlcheck_ssh_key_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_sshkeycallback))
/* evaluates to true if expr is of type curl_interleave_callback */
#define curlcheck_interleave_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), Wcurl_interleave_callback1) || \
curlcheck_cb_compatible((expr), Wcurl_interleave_callback2))
typedef size_t (*Wcurl_interleave_callback1)(void *p, size_t s,
size_t n, void *u);
typedef size_t (*Wcurl_interleave_callback2)(char *p, size_t s,
size_t n, void *u);
/* evaluates to true if expr is of type curl_prereq_callback */
#define curlcheck_prereq_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_prereq_callback))
/* evaluates to true if expr is of type curl_trailer_callback */
#define curlcheck_trailer_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_trailer_callback))
#endif /* CURLINC_TYPECHECK_GCC_H */
+156
View File
@@ -0,0 +1,156 @@
#ifndef CURLINC_URLAPI_H
#define CURLINC_URLAPI_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl.h"
#ifdef __cplusplus
extern "C" {
#endif
/* the error codes for the URL API */
typedef enum {
CURLUE_OK,
CURLUE_BAD_HANDLE, /* 1 */
CURLUE_BAD_PARTPOINTER, /* 2 */
CURLUE_MALFORMED_INPUT, /* 3 */
CURLUE_BAD_PORT_NUMBER, /* 4 */
CURLUE_UNSUPPORTED_SCHEME, /* 5 */
CURLUE_URLDECODE, /* 6 */
CURLUE_OUT_OF_MEMORY, /* 7 */
CURLUE_USER_NOT_ALLOWED, /* 8 */
CURLUE_UNKNOWN_PART, /* 9 */
CURLUE_NO_SCHEME, /* 10 */
CURLUE_NO_USER, /* 11 */
CURLUE_NO_PASSWORD, /* 12 */
CURLUE_NO_OPTIONS, /* 13 */
CURLUE_NO_HOST, /* 14 */
CURLUE_NO_PORT, /* 15 */
CURLUE_NO_QUERY, /* 16 */
CURLUE_NO_FRAGMENT, /* 17 */
CURLUE_NO_ZONEID, /* 18 */
CURLUE_BAD_FILE_URL, /* 19 */
CURLUE_BAD_FRAGMENT, /* 20 */
CURLUE_BAD_HOSTNAME, /* 21 */
CURLUE_BAD_IPV6, /* 22 */
CURLUE_BAD_LOGIN, /* 23 */
CURLUE_BAD_PASSWORD, /* 24 */
CURLUE_BAD_PATH, /* 25 */
CURLUE_BAD_QUERY, /* 26 */
CURLUE_BAD_SCHEME, /* 27 */
CURLUE_BAD_SLASHES, /* 28 */
CURLUE_BAD_USER, /* 29 */
CURLUE_LACKS_IDN, /* 30 */
CURLUE_TOO_LARGE, /* 31 */
CURLUE_BACKSLASH, /* 32 */
CURLUE_LAST
} CURLUcode;
typedef enum {
CURLUPART_URL,
CURLUPART_SCHEME,
CURLUPART_USER,
CURLUPART_PASSWORD,
CURLUPART_OPTIONS,
CURLUPART_HOST,
CURLUPART_PORT,
CURLUPART_PATH,
CURLUPART_QUERY,
CURLUPART_FRAGMENT,
CURLUPART_ZONEID /* added in 7.65.0 */
} CURLUPart;
#define CURLU_DEFAULT_PORT (1 << 0) /* return default port number */
#define CURLU_NO_DEFAULT_PORT (1 << 1) /* act as if no port number was set,
if the port number matches the
default for the scheme */
#define CURLU_DEFAULT_SCHEME (1 << 2) /* return default scheme if
missing */
#define CURLU_NON_SUPPORT_SCHEME (1 << 3) /* allow non-supported scheme */
#define CURLU_PATH_AS_IS (1 << 4) /* leave dot sequences */
#define CURLU_DISALLOW_USER (1 << 5) /* no user+password allowed */
#define CURLU_URLDECODE (1 << 6) /* URL decode on get */
#define CURLU_URLENCODE (1 << 7) /* URL encode on set */
#define CURLU_APPENDQUERY (1 << 8) /* append a form style part */
#define CURLU_GUESS_SCHEME (1 << 9) /* legacy curl-style guessing */
#define CURLU_NO_AUTHORITY (1 << 10) /* Allow empty authority when the
scheme is unknown. */
#define CURLU_ALLOW_SPACE (1 << 11) /* Allow spaces in the URL */
#define CURLU_PUNYCODE (1 << 12) /* get the hostname in punycode */
#define CURLU_PUNY2IDN (1 << 13) /* punycode => IDN conversion */
#define CURLU_GET_EMPTY (1 << 14) /* allow empty queries and fragments
when extracting the URL or the
components */
#define CURLU_NO_GUESS_SCHEME (1 << 15) /* for get, do not accept a guess */
typedef struct Curl_URL CURLU;
/*
* curl_url() creates a new CURLU handle and returns a pointer to it.
* Must be freed with curl_url_cleanup().
*/
CURL_EXTERN CURLU *curl_url(void);
/*
* curl_url_cleanup() frees the CURLU handle and related resources used for
* the URL parsing. It does not free strings previously returned with the URL
* API.
*/
CURL_EXTERN void curl_url_cleanup(CURLU *u);
/*
* curl_url_dup() duplicates a CURLU handle and returns a new copy. The new
* handle must also be freed with curl_url_cleanup().
*/
CURL_EXTERN CURLU *curl_url_dup(const CURLU *in);
/*
* curl_url_get() extracts a specific part of the URL from a CURLU
* handle. Returns error code. The returned pointer MUST be freed with
* curl_free() afterwards.
*/
CURL_EXTERN CURLUcode curl_url_get(const CURLU *u, CURLUPart what,
char **part, unsigned int flags);
/*
* curl_url_set() sets a specific part of the URL in a CURLU handle. Returns
* error code. The passed in string is copied. Passing a NULL instead of
* a part string, clears that part.
*/
CURL_EXTERN CURLUcode curl_url_set(CURLU *u, CURLUPart what,
const char *part, unsigned int flags);
/*
* curl_url_strerror() turns a CURLUcode value into the equivalent human
* readable error string. This is useful for printing meaningful error
* messages.
*/
CURL_EXTERN const char *curl_url_strerror(CURLUcode error);
#ifdef __cplusplus
} /* end of extern "C" */
#endif
#endif /* CURLINC_URLAPI_H */
+98
View File
@@ -0,0 +1,98 @@
#ifndef CURLINC_WEBSOCKETS_H
#define CURLINC_WEBSOCKETS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
struct curl_ws_frame {
int age; /* zero */
int flags; /* See the CURLWS_* defines */
curl_off_t offset; /* the offset of this data into the frame */
curl_off_t bytesleft; /* number of pending bytes left of the payload */
size_t len; /* size of the current data chunk */
};
/* flag bits */
#define CURLWS_TEXT (1 << 0)
#define CURLWS_BINARY (1 << 1)
#define CURLWS_CONT (1 << 2)
#define CURLWS_CLOSE (1 << 3)
#define CURLWS_PING (1 << 4)
#define CURLWS_OFFSET (1 << 5)
/*
* NAME curl_ws_recv()
*
* DESCRIPTION
*
* Receives data from the websocket connection. Use after successful
* curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
*/
CURL_EXTERN CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen,
size_t *recv,
const struct curl_ws_frame **metap);
/* flags for curl_ws_send() */
#define CURLWS_PONG (1 << 6)
/*
* NAME curl_ws_send()
*
* DESCRIPTION
*
* Sends data over the websocket connection. Use after successful
* curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
*/
CURL_EXTERN CURLcode curl_ws_send(CURL *curl, const void *buffer_arg,
size_t buflen, size_t *sent,
curl_off_t fragsize,
unsigned int flags);
/*
* NAME curl_ws_start_frame()
*
* DESCRIPTION
*
* Buffers a websocket frame header with the given flags and length.
* Errors when a previous frame is not complete, e.g. not all its
* payload has been added.
*/
CURL_EXTERN CURLcode curl_ws_start_frame(CURL *curl,
unsigned int flags,
curl_off_t frame_len);
/* bits for the CURLOPT_WS_OPTIONS bitmask: */
#define CURLWS_RAW_MODE (1L << 0)
#define CURLWS_NOAUTOPONG (1L << 1)
CURL_EXTERN const struct curl_ws_frame *curl_ws_meta(CURL *curl);
#ifdef __cplusplus
}
#endif
#endif /* CURLINC_WEBSOCKETS_H */
@@ -0,0 +1,10 @@
# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
#
# SPDX-License-Identifier: curl
Makefile.soname.cmake
curl_config.h
curl_config.h.in
libcurl.vers
libcurl_unity.c
unitprotos.h
+355
View File
@@ -0,0 +1,355 @@
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
# SPDX-License-Identifier: curl
#
###########################################################################
set(LIBCURL_OUTPUT_NAME "${LIB_NAME}" CACHE STRING "Basename of the curl library")
set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS ${CURL_DEBUG_MACROS} "BUILDING_LIBCURL")
configure_file("curl_config-cmake.h.in" "${CMAKE_CURRENT_BINARY_DIR}/curl_config.h")
# Get CSOURCES, HHEADERS, LIB_RCFILES variables
curl_transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake")
include("${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake")
list(APPEND HHEADERS "${CMAKE_CURRENT_BINARY_DIR}/curl_config.h")
# The rest of the build
set_property(DIRECTORY APPEND PROPERTY INCLUDE_DIRECTORIES
"${PROJECT_BINARY_DIR}/lib" # for "curl_config.h"
"${PROJECT_SOURCE_DIR}/lib"
)
if(CURL_BUILD_TESTING)
# special libcurlu library for unittests
add_library(curlu STATIC EXCLUDE_FROM_ALL ${HHEADERS} ${CSOURCES})
target_compile_definitions(curlu PUBLIC "CURL_STATICLIB" "UNITTESTS")
target_link_libraries(curlu PUBLIC ${CURL_LIBS})
# There is plenty of parallelism when building the testdeps target.
# Override the curlu batch size with the maximum to optimize performance.
set_target_properties(curlu PROPERTIES UNITY_BUILD ON UNITY_BUILD_BATCH_SIZE 0 C_CLANG_TIDY "")
add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/unitprotos.h"
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
COMMAND ${PERL_EXECUTABLE} "${PROJECT_SOURCE_DIR}/scripts/extract-unit-protos"
${CSOURCES} > "${CMAKE_CURRENT_BINARY_DIR}/unitprotos.h"
DEPENDS "${PROJECT_SOURCE_DIR}/scripts/extract-unit-protos" ${CSOURCES}
VERBATIM)
add_custom_target(curlu-unitprotos DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/unitprotos.h")
endif()
## Library definition
if(NOT DEFINED IMPORT_LIB_SUFFIX)
# Suffix implib name with "_imp" by default, to avoid conflicting with
# the generated static "libcurl.lib" (typically with MSVC).
if(WIN32 AND BUILD_SHARED_LIBS AND
CMAKE_IMPORT_LIBRARY_SUFFIX STREQUAL CMAKE_STATIC_LIBRARY_SUFFIX)
set(IMPORT_LIB_SUFFIX "_imp")
else()
set(IMPORT_LIB_SUFFIX "")
endif()
endif()
if(NOT DEFINED STATIC_LIB_SUFFIX)
set(STATIC_LIB_SUFFIX "")
endif()
# Detect implib static lib filename collision
if(WIN32 AND BUILD_STATIC_LIBS AND BUILD_SHARED_LIBS AND
"${IMPORT_LIB_SUFFIX}${CMAKE_IMPORT_LIBRARY_SUFFIX}" STREQUAL
"${STATIC_LIB_SUFFIX}${CMAKE_STATIC_LIBRARY_SUFFIX}")
message(FATAL_ERROR "Library suffix is the same ('${STATIC_LIB_SUFFIX}${CMAKE_STATIC_LIBRARY_SUFFIX}') "
"for the import and static '${LIBCURL_OUTPUT_NAME}' library. "
"Set IMPORT_LIB_SUFFIX and/or STATIC_LIB_SUFFIX to different values, "
"or disable building either the shared or static library to avoid the filename collision.")
endif()
# Whether to do a single compilation pass for libcurl sources and reuse these
# objects to generate both static and shared target.
if(NOT DEFINED SHARE_LIB_OBJECT)
# Enable it by default on platforms where PIC is the default for both shared
# and static and there is a way to tell the linker which libcurl symbols it
# should export (vs. marking these symbols exportable at compile-time).
if(WIN32)
set(SHARE_LIB_OBJECT ON)
else()
# On other platforms, make it an option disabled by default
set(SHARE_LIB_OBJECT OFF)
endif()
endif()
if(SHARE_LIB_OBJECT)
set(LIB_OBJECT "libcurl_object")
add_library(${LIB_OBJECT} OBJECT ${HHEADERS} ${CSOURCES})
if(WIN32)
# Define CURL_STATICLIB always, to disable __declspec(dllexport) for
# exported libcurl symbols. We handle exports via libcurl.def instead.
# Except with symbol hiding disabled or debug mode enabled, when we export
# _all_ symbols from libcurl DLL, without using libcurl.def.
set_property(TARGET ${LIB_OBJECT} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_STATICLIB")
endif()
target_link_libraries(${LIB_OBJECT} PRIVATE ${CURL_LIBS})
set_target_properties(${LIB_OBJECT} PROPERTIES POSITION_INDEPENDENT_CODE ON)
set_property(TARGET ${LIB_OBJECT} APPEND PROPERTY COMPILE_OPTIONS "${CURL_CFLAGS}")
if(CURL_HIDES_PRIVATE_SYMBOLS)
set_property(TARGET ${LIB_OBJECT} APPEND PROPERTY COMPILE_OPTIONS "${CURL_CFLAG_SYMBOLS_HIDE}")
set_property(TARGET ${LIB_OBJECT} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_HIDDEN_SYMBOLS")
endif()
if(CURL_HAS_LTO)
if(CMAKE_CONFIGURATION_TYPES)
set_target_properties(${LIB_OBJECT} PROPERTIES
INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE
INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO TRUE)
else()
set_target_properties(${LIB_OBJECT} PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE)
endif()
endif()
if(CURL_CLANG_TIDY)
set_target_properties(${LIB_OBJECT} PROPERTIES UNITY_BUILD OFF)
endif()
if(CURL_ANALYZER_CFLAGS)
set_target_properties(${LIB_OBJECT} PROPERTIES UNITY_BUILD OFF)
set_property(TARGET ${LIB_OBJECT} APPEND PROPERTY COMPILE_OPTIONS ${CURL_ANALYZER_CFLAGS})
endif()
if(CURL_CODE_COVERAGE)
set_property(TARGET ${LIB_OBJECT} APPEND PROPERTY COMPILE_DEFINITIONS ${CURL_COVERAGE_MACROS})
set_property(TARGET ${LIB_OBJECT} APPEND PROPERTY COMPILE_OPTIONS ${CURL_COVERAGE_CFLAGS})
endif()
target_include_directories(${LIB_OBJECT} INTERFACE
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
"$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>")
set(LIB_SOURCE $<TARGET_OBJECTS:${LIB_OBJECT}>)
else()
set(LIB_SOURCE ${HHEADERS} ${CSOURCES})
endif()
# We want it to be called libcurl on all platforms
if(BUILD_STATIC_LIBS)
list(APPEND libcurl_export ${LIB_STATIC})
add_library(${LIB_STATIC} STATIC ${LIB_SOURCE})
add_library(${PROJECT_NAME}::${LIB_STATIC} ALIAS ${LIB_STATIC})
if(WIN32)
set_property(TARGET ${LIB_STATIC} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_STATICLIB")
endif()
target_link_libraries(${LIB_STATIC} PRIVATE ${CURL_LIBS})
# Remove the "lib" prefix since the library is already named "libcurl".
set_target_properties(${LIB_STATIC} PROPERTIES
PREFIX "" OUTPUT_NAME "${LIBCURL_OUTPUT_NAME}"
SUFFIX "${STATIC_LIB_SUFFIX}${CMAKE_STATIC_LIBRARY_SUFFIX}"
INTERFACE_COMPILE_DEFINITIONS "CURL_STATICLIB")
set_property(TARGET ${LIB_STATIC} APPEND PROPERTY COMPILE_OPTIONS "${CURL_CFLAGS}")
if(CURL_HIDES_PRIVATE_SYMBOLS)
set_property(TARGET ${LIB_STATIC} APPEND PROPERTY COMPILE_OPTIONS "${CURL_CFLAG_SYMBOLS_HIDE}")
set_property(TARGET ${LIB_STATIC} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_HIDDEN_SYMBOLS")
endif()
if(CURL_HAS_LTO)
if(CMAKE_CONFIGURATION_TYPES)
set_target_properties(${LIB_STATIC} PROPERTIES
INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE
INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO TRUE)
else()
set_target_properties(${LIB_STATIC} PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE)
endif()
endif()
if(CURL_CLANG_TIDY)
if(BUILD_SHARED_LIBS) # disable clang-tidy for static, and limit to the shared library, if both enabled
set_target_properties(${LIB_STATIC} PROPERTIES C_CLANG_TIDY "")
else()
set_target_properties(${LIB_STATIC} PROPERTIES UNITY_BUILD OFF)
endif()
endif()
if(CURL_ANALYZER_CFLAGS)
set_target_properties(${LIB_STATIC} PROPERTIES UNITY_BUILD OFF)
set_property(TARGET ${LIB_STATIC} APPEND PROPERTY COMPILE_OPTIONS ${CURL_ANALYZER_CFLAGS})
endif()
if(CURL_CODE_COVERAGE)
set_property(TARGET ${LIB_STATIC} APPEND PROPERTY COMPILE_DEFINITIONS ${CURL_COVERAGE_MACROS})
set_property(TARGET ${LIB_STATIC} APPEND PROPERTY COMPILE_OPTIONS ${CURL_COVERAGE_CFLAGS})
endif()
target_include_directories(${LIB_STATIC} INTERFACE
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
"$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>")
endif()
if(BUILD_SHARED_LIBS)
list(APPEND libcurl_export ${LIB_SHARED})
add_library(${LIB_SHARED} SHARED ${LIB_SOURCE})
add_library(${PROJECT_NAME}::${LIB_SHARED} ALIAS ${LIB_SHARED})
if(WIN32)
set_property(TARGET ${LIB_SHARED} APPEND PROPERTY SOURCES "dllmain.c")
set_property(TARGET ${LIB_SHARED} APPEND PROPERTY SOURCES ${LIB_RCFILES})
if(CURL_HIDES_PRIVATE_SYMBOLS)
set_property(TARGET ${LIB_SHARED} APPEND PROPERTY SOURCES "${PROJECT_SOURCE_DIR}/lib/libcurl.def")
endif()
endif()
target_link_libraries(${LIB_SHARED} PRIVATE ${CURL_LIBS})
# Remove the "lib" prefix since the library is already named "libcurl".
set_target_properties(${LIB_SHARED} PROPERTIES
PREFIX "" OUTPUT_NAME "${LIBCURL_OUTPUT_NAME}"
IMPORT_PREFIX "" IMPORT_SUFFIX "${IMPORT_LIB_SUFFIX}${CMAKE_IMPORT_LIBRARY_SUFFIX}"
POSITION_INDEPENDENT_CODE ON)
set_property(TARGET ${LIB_SHARED} APPEND PROPERTY COMPILE_OPTIONS "${CURL_CFLAGS}")
if(CURL_HIDES_PRIVATE_SYMBOLS)
set_property(TARGET ${LIB_SHARED} APPEND PROPERTY COMPILE_OPTIONS "${CURL_CFLAG_SYMBOLS_HIDE}")
set_property(TARGET ${LIB_SHARED} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_HIDDEN_SYMBOLS")
endif()
if(CURL_HAS_LTO)
if(CMAKE_CONFIGURATION_TYPES)
set_target_properties(${LIB_SHARED} PROPERTIES
INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE
INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO TRUE)
else()
set_target_properties(${LIB_SHARED} PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE)
endif()
endif()
if(CURL_CLANG_TIDY)
set_target_properties(${LIB_SHARED} PROPERTIES UNITY_BUILD OFF)
endif()
if(CURL_ANALYZER_CFLAGS)
set_target_properties(${LIB_SHARED} PROPERTIES UNITY_BUILD OFF)
set_property(TARGET ${LIB_SHARED} APPEND PROPERTY COMPILE_OPTIONS ${CURL_ANALYZER_CFLAGS})
endif()
if(CURL_CODE_COVERAGE)
set_property(TARGET ${LIB_SHARED} APPEND PROPERTY COMPILE_DEFINITIONS ${CURL_COVERAGE_MACROS})
set_property(TARGET ${LIB_SHARED} APPEND PROPERTY COMPILE_OPTIONS ${CURL_COVERAGE_CFLAGS})
set_property(TARGET ${LIB_SHARED} APPEND PROPERTY LINK_OPTIONS ${CURL_COVERAGE_LDFLAGS})
endif()
target_include_directories(${LIB_SHARED} INTERFACE
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
"$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>")
if(CMAKE_DLL_NAME_WITH_SOVERSION OR
CYGWIN OR
APPLE OR
AIX OR CMAKE_SYSTEM_NAME STREQUAL "AIX" OR
CMAKE_SYSTEM_NAME STREQUAL "Linux" OR
CMAKE_SYSTEM_NAME STREQUAL "SunOS" OR
CMAKE_SYSTEM_NAME STREQUAL "Haiku" OR
CMAKE_SYSTEM_NAME STREQUAL "OHOS" OR # OpenHarmony
# FreeBSD comes with the a.out and ELF flavors but a.out was supported
# up to v3.x and ELF from v3.x. I cannot imagine someone running CMake
# on those ancient systems.
CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")
set(_soversion_default TRUE)
else()
set(_soversion_default FALSE)
endif()
option(CURL_LIBCURL_SOVERSION "Enable libcurl SOVERSION" ${_soversion_default})
option(CURL_LIBCURL_VERSIONED_SYMBOLS "Enable libcurl versioned symbols" OFF)
if(CURL_LIBCURL_SOVERSION OR CURL_LIBCURL_VERSIONED_SYMBOLS)
# Get VERSIONCHANGE, VERSIONADD, VERSIONDEL, VERSIONINFO variables
curl_transform_makefile_inc("Makefile.soname" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.soname.cmake")
include("${CMAKE_CURRENT_BINARY_DIR}/Makefile.soname.cmake")
math(EXPR _cmakesoname "${VERSIONCHANGE} - ${VERSIONDEL}")
set(_cmakeversion "${_cmakesoname}.${VERSIONDEL}.${VERSIONADD}")
endif()
if(CURL_LIBCURL_SOVERSION)
set_target_properties(${LIB_SHARED} PROPERTIES
VERSION "${_cmakeversion}" SOVERSION "${_cmakesoname}")
endif()
## Versioned symbols
if(CURL_LIBCURL_VERSIONED_SYMBOLS)
if(NOT DEFINED CURL_LIBCURL_VERSIONED_SYMBOLS_PREFIX)
# Default to prefixes used by autotools
if(CURL_WITH_MULTI_SSL)
set(CURL_LIBCURL_VERSIONED_SYMBOLS_PREFIX "MULTISSL_")
elseif(CURL_USE_OPENSSL)
set(CURL_LIBCURL_VERSIONED_SYMBOLS_PREFIX "OPENSSL_")
elseif(CURL_USE_MBEDTLS)
set(CURL_LIBCURL_VERSIONED_SYMBOLS_PREFIX "MBEDTLS_")
elseif(CURL_USE_WOLFSSL)
set(CURL_LIBCURL_VERSIONED_SYMBOLS_PREFIX "WOLFSSL_")
elseif(CURL_USE_GNUTLS)
set(CURL_LIBCURL_VERSIONED_SYMBOLS_PREFIX "GNUTLS_")
elseif(CURL_USE_RUSTLS)
set(CURL_LIBCURL_VERSIONED_SYMBOLS_PREFIX "RUSTLS_")
endif()
endif()
# Generate version script for the linker, for versioned symbols.
# Consumed variables:
# CURL_LIBCURL_VERSIONED_SYMBOLS_PREFIX
# CURL_LIBCURL_VERSIONED_SYMBOLS_SONAME
set(CURL_LIBCURL_VERSIONED_SYMBOLS_SONAME ${_cmakesoname})
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/libcurl.vers.in"
"${CMAKE_CURRENT_BINARY_DIR}/libcurl.vers" @ONLY)
include(CMakePushCheckState)
include(CheckCSourceCompiles)
cmake_push_check_state()
set(CMAKE_REQUIRED_LINK_OPTIONS "-Wl,--version-script=${CMAKE_CURRENT_BINARY_DIR}/libcurl.vers")
check_c_source_compiles("int main(void) { return 0; }" HAVE_VERSIONED_SYMBOLS)
if(HAVE_VERSIONED_SYMBOLS)
set_property(TARGET ${LIB_SHARED} APPEND PROPERTY LINK_OPTIONS "${CMAKE_REQUIRED_LINK_OPTIONS}")
else()
message(WARNING "Versioned symbols requested, but not supported by the toolchain.")
endif()
cmake_pop_check_state()
endif()
endif()
add_library(${LIB_NAME} ALIAS ${LIB_SELECTED})
add_library(${PROJECT_NAME}::${LIB_NAME} ALIAS ${LIB_SELECTED})
if(CURL_ENABLE_EXPORT_TARGET)
if(NOT CURL_DISABLE_INSTALL AND BUILD_STATIC_LIBS)
install(TARGETS ${LIB_STATIC}
EXPORT ${TARGETS_EXPORT_NAME}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
endif()
if(NOT CURL_DISABLE_INSTALL AND BUILD_SHARED_LIBS)
install(TARGETS ${LIB_SHARED}
EXPORT ${TARGETS_EXPORT_NAME}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
endif()
export(TARGETS ${libcurl_export}
FILE "${PROJECT_BINARY_DIR}/libcurl-target.cmake"
NAMESPACE ${PROJECT_NAME}::
)
endif()
if(PERL_EXECUTABLE)
add_custom_target(curl-optiontable
COMMENT "Generating lib/easyoptions.c" VERBATIM USES_TERMINAL
COMMAND "${PERL_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/optiontable.pl" "${PROJECT_SOURCE_DIR}/include/curl/curl.h"
> "${PROJECT_SOURCE_DIR}/lib/easyoptions.c"
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/optiontable.pl" "${PROJECT_SOURCE_DIR}/include/curl/curl.h"
)
endif()
+193
View File
@@ -0,0 +1,193 @@
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
# SPDX-License-Identifier: curl
#
###########################################################################
AUTOMAKE_OPTIONS = foreign nostdinc
# Get CSOURCES, HHEADERS, LIB_RCFILES variables
include Makefile.inc
EXTRA_DIST = \
CMakeLists.txt \
config-mac.h \
config-os400.h \
config-win32.h \
curl_config-cmake.h.in \
curl_config.h.in \
libcurl.def \
Makefile.soname \
optiontable.pl \
$(LIB_RCFILES)
lib_LTLIBRARIES = libcurl.la
if BUILD_UNITTESTS
noinst_LTLIBRARIES = libcurlu.la
# generate a file with "private" prototypes for unit testing
UNITPROTOS = unitprotos.h
else
noinst_LTLIBRARIES =
endif
# This might hold -Werror
CFLAGS += @CURL_CFLAG_EXTRAS@
# Specify our include paths here, and do it relative to $(top_srcdir) and
# $(top_builddir), to ensure that these paths which belong to the library
# being currently built and tested are searched before the library which
# might possibly already be installed in the system.
#
# $(top_srcdir)/include is for libcurl's external include files
# $(top_builddir)/lib is for libcurl's generated lib/curl_config.h file
# $(srcdir) for the generated unity source to find included sources
AM_CPPFLAGS = -I$(top_srcdir)/include \
-I$(top_builddir)/lib \
-I$(top_srcdir)/lib \
-I$(srcdir)
# Prevent LIBS from being used for all link targets
LIBS = $(BLANK_AT_MAKETIME)
if DEBUGBUILD
AM_CPPFLAGS += -DDEBUGBUILD
endif
AM_CPPFLAGS += -DBUILDING_LIBCURL
if DOING_NATIVE_WINDOWS
CSOURCES += dllmain.c
endif
if USE_UNITY
libcurl_unity.c: $(top_srcdir)/scripts/mk-unity.pl $(CSOURCES)
@PERL@ $(top_srcdir)/scripts/mk-unity.pl --include $(CSOURCES) > libcurl_unity.c
nodist_libcurl_la_SOURCES = libcurl_unity.c
libcurl_la_SOURCES =
nodist_libcurlu_la_SOURCES = libcurl_unity.c
libcurlu_la_SOURCES =
CLEANFILES = libcurl_unity.c
else
libcurl_la_SOURCES = $(CSOURCES) $(HHEADERS)
libcurlu_la_SOURCES = $(CSOURCES) $(HHEADERS)
CLEANFILES =
endif
CLEANFILES += $(UNITPROTOS)
libcurl_la_CPPFLAGS_EXTRA =
libcurl_la_LDFLAGS_EXTRA =
libcurl_la_CFLAGS_EXTRA =
if CURL_LT_SHLIB_USE_VERSION_INFO
# Get VERSIONCHANGE, VERSIONADD, VERSIONDEL, VERSIONINFO variables
include Makefile.soname
libcurl_la_LDFLAGS_EXTRA += $(VERSIONINFO)
endif
if CURL_LT_SHLIB_USE_NO_UNDEFINED
libcurl_la_LDFLAGS_EXTRA += -no-undefined
endif
if CURL_LT_SHLIB_USE_MIMPURE_TEXT
libcurl_la_LDFLAGS_EXTRA += -mimpure-text
endif
if CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS
libcurl_la_LDFLAGS_EXTRA += -Wl,--version-script=libcurl.vers
else
# if symbol-hiding is enabled, hide them!
if DOING_CURL_SYMBOL_HIDING
libcurl_la_LDFLAGS_EXTRA += -export-symbols-regex '^curl_.*'
endif
endif
if USE_CPPFLAG_CURL_STATICLIB
libcurl_la_CPPFLAGS_EXTRA += -DCURL_STATICLIB
else
if HAVE_WINDRES
libcurl_la_SOURCES += $(LIB_RCFILES)
$(LIB_RCFILES): $(top_srcdir)/include/curl/curlver.h
endif
endif
if DOING_CURL_SYMBOL_HIDING
libcurl_la_CPPFLAGS_EXTRA += -DCURL_HIDDEN_SYMBOLS
libcurl_la_CFLAGS_EXTRA += $(CFLAG_CURL_SYMBOL_HIDING)
endif
libcurl_la_CPPFLAGS = $(AM_CPPFLAGS) $(libcurl_la_CPPFLAGS_EXTRA)
libcurl_la_LDFLAGS = $(libcurl_la_LDFLAGS_EXTRA) $(CURL_LDFLAGS_LIB) $(LIBCURL_PC_LIBS_PRIVATE)
libcurl_la_CFLAGS = $(libcurl_la_CFLAGS_EXTRA)
libcurlu_la_CPPFLAGS = $(AM_CPPFLAGS) -DCURL_STATICLIB -DUNITTESTS
libcurlu_la_LDFLAGS = -static $(LIBCURL_PC_LIBS_PRIVATE)
CHECKSRC = $(CS_$(V))
CS_0 = @echo " RUN " $@;
CS_1 =
CS_ = $(CS_0)
checksrc:
$(CHECKSRC)(@PERL@ $(top_srcdir)/scripts/checksrc.pl -D$(srcdir) $(CSOURCES) $(HHEADERS))
if NOT_CURL_CI
if DEBUGBUILD
# for debug builds, we scan the sources on all regular make invokes
CHECKSOURCES = checksrc
endif
endif
all-local: $(CHECKSOURCES)
UNIT_V = $(UNITV_$(V))
UNITV_0 = @echo " UNITPR " $@;
UNITV_1 =
UNITV_ = $(UNITV_0)
# UNITPROTOS depends on every C file in the lib/ dir
$(UNITPROTOS): $(CSOURCES)
$(UNIT_V)(cd $(srcdir) && @PERL@ ../scripts/extract-unit-protos $(CSOURCES)) > $(top_builddir)/lib/$(UNITPROTOS)
_tidy_cflags =
TIDYFLAGS =
if CURL_WERROR
TIDYFLAGS += '--warnings-as-errors=*'
endif
if CLANG
_tidy_cflags += $(CFLAGS)
endif
tidy:
(_csources=`echo ' $(CSOURCES)' | sed -E -e 's/ +$$//' -e 's/ +/ /g' -e 's| | $(srcdir)/|g'`; \
@CLANG_TIDY@ --config-file=$(top_srcdir)/.clang-tidy.yml $(TIDYFLAGS) $(CURL_CLANG_TIDYFLAGS) $$_csources \
-- $(AM_CPPFLAGS) $(CPPFLAGS) -DHAVE_CONFIG_H $(_tidy_cflags))
optiontable:
@PERL@ $(srcdir)/optiontable.pl $(top_srcdir)/include/curl/curl.h > $(srcdir)/easyoptions.c
if HAVE_WINDRES
.rc.lo:
$(LIBTOOL) --tag=RC --mode=compile $(RC) -I$(top_srcdir)/include $(RCFLAGS) -i $< -o $@
endif
+442
View File
@@ -0,0 +1,442 @@
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
# SPDX-License-Identifier: curl
#
###########################################################################
# Shared between CMakeLists.txt and Makefile.am
LIB_CURLX_CFILES = \
curlx/base64.c \
curlx/basename.c \
curlx/dynbuf.c \
curlx/win32-fopen.c \
curlx/inet_ntop.c \
curlx/inet_pton.c \
curlx/multibyte.c \
curlx/nonblock.c \
curlx/snprintf.c \
curlx/strcopy.c \
curlx/strdup.c \
curlx/strerr.c \
curlx/strparse.c \
curlx/timediff.c \
curlx/timeval.c \
curlx/version_win32.c \
curlx/wait.c \
curlx/warnless.c \
curlx/winapi.c
LIB_CURLX_HFILES = \
curlx/base64.h \
curlx/basename.h \
curlx/dynbuf.h \
curlx/win32-fopen.h \
curlx/inet_ntop.h \
curlx/inet_pton.h \
curlx/multibyte.h \
curlx/nonblock.h \
curlx/snprintf.h \
curlx/strcopy.h \
curlx/strdup.h \
curlx/strerr.h \
curlx/strparse.h \
curlx/timediff.h \
curlx/timeval.h \
curlx/version_win32.h \
curlx/wait.h \
curlx/warnless.h \
curlx/winapi.h
LIB_VAUTH_CFILES = \
vauth/cleartext.c \
vauth/cram.c \
vauth/digest.c \
vauth/digest_sspi.c \
vauth/gsasl.c \
vauth/krb5_gssapi.c \
vauth/krb5_sspi.c \
vauth/ntlm.c \
vauth/ntlm_sspi.c \
vauth/oauth2.c \
vauth/spnego_gssapi.c \
vauth/spnego_sspi.c \
vauth/vauth.c
LIB_VAUTH_HFILES = \
vauth/digest.h \
vauth/vauth.h
LIB_VDNS_CFILES = \
vdns/asyn-ares.c \
vdns/asyn-base.c \
vdns/asyn-thrdd.c \
vdns/cf-dns.c \
vdns/dnscache.c \
vdns/doh.c \
vdns/hostip.c \
vdns/hostip4.c \
vdns/hostip6.c \
vdns/httpsrr.c
LIB_VDNS_HFILES = \
vdns/asyn.h \
vdns/cf-dns.h \
vdns/dnscache.h \
vdns/doh.h \
vdns/hostip.h \
vdns/httpsrr.h
LIB_VTLS_CFILES = \
vtls/apple.c \
vtls/cipher_suite.c \
vtls/gtls.c \
vtls/hostcheck.c \
vtls/keylog.c \
vtls/mbedtls.c \
vtls/openssl.c \
vtls/rustls.c \
vtls/schannel.c \
vtls/schannel_verify.c \
vtls/vtls.c \
vtls/vtls_config.c \
vtls/vtls_scache.c \
vtls/vtls_spack.c \
vtls/wolfssl.c \
vtls/x509asn1.c
LIB_VTLS_HFILES = \
vtls/apple.h \
vtls/cipher_suite.h \
vtls/gtls.h \
vtls/hostcheck.h \
vtls/keylog.h \
vtls/mbedtls.h \
vtls/openssl.h \
vtls/rustls.h \
vtls/schannel.h \
vtls/schannel_int.h \
vtls/vtls.h \
vtls/vtls_config.h \
vtls/vtls_int.h \
vtls/vtls_scache.h \
vtls/vtls_spack.h \
vtls/wolfssl.h \
vtls/x509asn1.h
LIB_VQUIC_CFILES = \
vquic/capsule.c \
vquic/cf-capsule.c \
vquic/cf-ngtcp2.c \
vquic/cf-ngtcp2-cmn.c \
vquic/cf-ngtcp2-proxy.c \
vquic/cf-quiche.c \
vquic/vquic.c \
vquic/vquic-tls.c
LIB_VQUIC_HFILES = \
vquic/capsule.h \
vquic/cf-capsule.h \
vquic/cf-ngtcp2.h \
vquic/cf-ngtcp2-cmn.h \
vquic/cf-ngtcp2-proxy.h \
vquic/cf-quiche.h \
vquic/vquic.h \
vquic/vquic_int.h \
vquic/vquic-tls.h
LIB_VSSH_CFILES = \
vssh/libssh.c \
vssh/libssh2.c \
vssh/vssh.c
LIB_VSSH_HFILES = \
vssh/vssh.h \
vssh/ssh.h
LIB_CFILES = \
altsvc.c \
amigaos.c \
api.c \
bufq.c \
bufref.c \
cf-h1-proxy.c \
cf-h2-proxy.c \
cf-haproxy.c \
cf-https-connect.c \
cf-ip-happy.c \
cf-recvbuf.c \
cf-setup.c \
cf-socket.c \
cfilters.c \
conncache.c \
connect.c \
content_encoding.c \
cookie.c \
creds.c \
cshutdn.c \
curl_addrinfo.c \
curl_endian.c \
curl_fnmatch.c \
curl_fopen.c \
curl_get_line.c \
curl_gethostname.c \
curl_gssapi.c \
curl_memrchr.c \
curl_ntlm_core.c \
curl_range.c \
curl_sasl.c \
curl_sha512_256.c \
curl_share.c \
curl_sspi.c \
curl_threads.c \
curl_trc.c \
cw-out.c \
cw-pause.c \
dict.c \
dynhds.c \
easy.c \
easygetopt.c \
easyoptions.c \
escape.c \
fake_addrinfo.c \
file.c \
fileinfo.c \
formdata.c \
ftp.c \
ftplistparser.c \
getenv.c \
getinfo.c \
gopher.c \
hash.c \
headers.c \
hmac.c \
hsts.c \
http.c \
http1.c \
http2.c \
http_aws_sigv4.c \
http_httpsig.c \
curl_ed25519.c \
http_chunks.c \
http_digest.c \
http_negotiate.c \
http_ntlm.c \
http_proxy.c \
idn.c \
if2ip.c \
imap.c \
ldap.c \
llist.c \
macos.c \
md4.c \
md5.c \
memdebug.c \
mime.c \
mprintf.c \
mqtt.c \
multi.c \
multi_ev.c \
multi_ntfy.c \
netrc.c \
openldap.c \
parsedate.c \
peer.c \
pingpong.c \
pop3.c \
progress.c \
protocol.c \
proxy.c \
psl.c \
ptrarray.c \
rand.c \
ratelimit.c \
request.c \
rtsp.c \
select.c \
sendf.c \
setopt.c \
sha256.c \
slist.c \
smtp.c \
socketpair.c \
socks.c \
socks_gssapi.c \
socks_sspi.c \
splay.c \
strcase.c \
strequal.c \
strerror.c \
telnet.c \
tftp.c \
thrdpool.c \
thrdqueue.c \
transfer.c \
u8_strset.c \
u32_ptrset.c \
uint-bset.c \
uint-spbset.c \
uint-table.c \
url.c \
urlapi.c \
version.c \
ws.c
LIB_HFILES = \
altsvc.h \
amigaos.h \
api.h \
arpa_telnet.h \
bufq.h \
bufref.h \
cf-h1-proxy.h \
cf-h2-proxy.h \
cf-haproxy.h \
cf-https-connect.h \
cf-ip-happy.h \
cf-recvbuf.h \
cf-setup.h \
cf-socket.h \
cfilters.h \
conncache.h \
cshutdn.h \
connect.h \
content_encoding.h \
cookie.h \
creds.h \
curl_addrinfo.h \
curl_ctype.h \
curl_endian.h \
curl_fnmatch.h \
curl_fopen.h \
curl_get_line.h \
curl_gethostname.h \
curl_gssapi.h \
curl_hmac.h \
curl_ldap.h \
curl_md4.h \
curl_md5.h \
curl_memrchr.h \
curl_ntlm_core.h \
curl_printf.h \
curl_range.h \
curl_sasl.h \
curl_setup.h \
curl_sha256.h \
curl_sha512_256.h \
curl_share.h \
curl_sspi.h \
curl_threads.h \
curl_trc.h \
cw-out.h \
cw-pause.h \
dict.h \
dynhds.h \
easy_lock.h \
easyif.h \
easyoptions.h \
escape.h \
fake_addrinfo.h \
file.h \
fileinfo.h \
formdata.h \
ftp.h \
ftp-int.h \
ftplistparser.h \
functypes.h \
getinfo.h \
gopher.h \
hash.h \
headers.h \
hsts.h \
http.h \
http1.h \
http2.h \
http_aws_sigv4.h \
http_httpsig.h \
curl_ed25519.h \
http_chunks.h \
http_digest.h \
http_negotiate.h \
http_ntlm.h \
http_proxy.h \
idn.h \
if2ip.h \
imap.h \
llist.h \
macos.h \
mime.h \
mqtt.h \
multihandle.h \
multi_ev.h \
multi_ntfy.h \
multiif.h \
netrc.h \
parsedate.h \
peer.h \
pingpong.h \
pop3.h \
progress.h \
protocol.h \
proxy.h \
psl.h \
ptrarray.h \
rand.h \
ratelimit.h \
request.h \
rtsp.h \
select.h \
sendf.h \
setopt.h \
setup-os400.h \
setup-vms.h \
setup-win32.h \
sigpipe.h \
slist.h \
smtp.h \
sockaddr.h \
socketpair.h \
socks.h \
splay.h \
strcase.h \
strerror.h \
telnet.h \
tftp.h \
thrdpool.h \
thrdqueue.h \
transfer.h \
u8_strset.h \
u32_ptrset.h \
uint-bset.h \
uint-spbset.h \
uint-table.h \
url.h \
urlapi-int.h \
urldata.h \
ws.h
LIB_RCFILES = libcurl.rc
CSOURCES = $(LIB_CFILES) $(LIB_VAUTH_CFILES) $(LIB_VDNS_CFILES) \
$(LIB_VTLS_CFILES) $(LIB_VQUIC_CFILES) $(LIB_VSSH_CFILES) \
$(LIB_CURLX_CFILES)
HHEADERS = $(LIB_HFILES) $(LIB_VAUTH_HFILES) $(LIB_VDNS_HFILES) \
$(LIB_VTLS_HFILES) $(LIB_VQUIC_HFILES) $(LIB_VSSH_HFILES) \
$(LIB_CURLX_HFILES)
+43
View File
@@ -0,0 +1,43 @@
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
# SPDX-License-Identifier: curl
#
###########################################################################
# Shared between CMakeLists.txt and Makefile.am
# Keep in sync with CURL_LIBCURL_VERSIONED_SYMBOLS_SONAME in configure.ac
VERSIONCHANGE=12
VERSIONADD=0
VERSIONDEL=8
# libtool version:
VERSIONINFO=-version-info $(VERSIONCHANGE):$(VERSIONADD):$(VERSIONDEL)
# This flag accepts an argument of the form current[:revision[:age]]. It means
# passing -version-info 3:12:1 sets current to 3, revision to 12, and age to 1.
#
# Here's the simplified rule guide on how to change -version-info:
# (current version is C:R:A)
#
# 1. if there are only source changes, use C:R+1:A
# 2. if interfaces were added use C+1:0:A+1
# 3. if interfaces were removed, then use C+1:0:0
#
# For the full guide on libcurl ABI rules, see docs/libcurl/ABI
+726
View File
@@ -0,0 +1,726 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
/*
* The Alt-Svc: header is defined in RFC 7838:
* https://datatracker.ietf.org/doc/html/rfc7838
*/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC)
#include "urldata.h"
#include "altsvc.h"
#include "curl_fopen.h"
#include "curl_get_line.h"
#include "parsedate.h"
#include "curl_trc.h"
#include "curlx/inet_pton.h"
#include "curlx/strparse.h"
#include "connect.h"
#define MAX_ALTSVC_LINE 4095
#define MAX_ALTSVC_DATELEN 17
#define MAX_ALTSVC_HOSTLEN 2048
#define MAX_ALTSVC_ALPNLEN 10
#define H3VERSION "h3"
#if defined(DEBUGBUILD) || defined(UNITTESTS)
/* to play well with debug builds, we can *set* a fixed time this will
return */
static time_t altsvc_debugtime(void *unused)
{
const char *timestr = getenv("CURL_TIME");
(void)unused;
if(timestr) {
curl_off_t val;
curlx_str_number(&timestr, &val, TIME_T_MAX);
return (time_t)val;
}
return time(NULL);
}
#undef time
#define time(x) altsvc_debugtime(x)
#endif
/* Given the ALPN ID, return the name */
const char *Curl_alpnid2str(enum alpnid id)
{
switch(id) {
case ALPN_h1:
return "h1";
case ALPN_h2:
return "h2";
case ALPN_h3:
return H3VERSION;
default:
return ""; /* bad */
}
}
static enum alpnid Curl_str2alpnid(const struct Curl_str *cstr)
{
return Curl_alpn2alpnid((const unsigned char *)curlx_str(cstr),
curlx_strlen(cstr));
}
#define altsvc_free(x) curlx_free(x)
static struct altsvc *altsvc_createid(const char *srchost,
size_t hlen,
const char *dsthost,
size_t dlen, /* dsthost length */
enum alpnid srcalpnid,
enum alpnid dstalpnid,
size_t srcport,
size_t dstport)
{
struct altsvc *as;
if((hlen > 2) && srchost[0] == '[') {
/* IPv6 address, strip off brackets */
srchost++;
hlen -= 2;
}
else if(hlen && (srchost[hlen - 1] == '.')) {
/* strip off trailing dot */
hlen--;
}
if((dlen > 2) && dsthost[0] == '[') {
/* IPv6 address, strip off brackets */
dsthost++;
dlen -= 2;
}
if(!hlen || !dlen)
/* bad input */
return NULL;
/* struct size plus both strings */
as = curlx_calloc(1, sizeof(struct altsvc) + (hlen + 1) + (dlen + 1));
if(!as)
return NULL;
as->src.host = (char *)as + sizeof(struct altsvc);
memcpy(as->src.host, srchost, hlen);
/* the null-terminator is already there */
as->dst.host = (char *)as + sizeof(struct altsvc) + hlen + 1;
memcpy(as->dst.host, dsthost, dlen);
/* the null-terminator is already there */
as->src.alpnid = srcalpnid;
as->dst.alpnid = dstalpnid;
as->src.port = (unsigned short)srcport;
as->dst.port = (unsigned short)dstport;
return as;
}
static struct altsvc *altsvc_create(struct Curl_str *srchost,
struct Curl_str *dsthost,
struct Curl_str *srcalpn,
struct Curl_str *dstalpn,
size_t srcport,
size_t dstport)
{
enum alpnid dstalpnid = Curl_str2alpnid(dstalpn);
enum alpnid srcalpnid = Curl_str2alpnid(srcalpn);
if(!srcalpnid || !dstalpnid)
return NULL;
return altsvc_createid(curlx_str(srchost), curlx_strlen(srchost),
curlx_str(dsthost), curlx_strlen(dsthost),
srcalpnid, dstalpnid,
srcport, dstport);
}
/* append the new entry to the list after possibly removing an old entry
first */
static void altsvc_append(struct altsvcinfo *asi, struct altsvc *as)
{
while(Curl_llist_count(&asi->list) >= MAX_ALTSVC_ENTRIES) {
/* It is full. Remove the first entry in the list */
struct Curl_llist_node *e = Curl_llist_head(&asi->list);
struct altsvc *oldas = Curl_node_elem(e);
Curl_node_remove(e);
altsvc_free(oldas);
}
Curl_llist_append(&asi->list, as, &as->node);
}
/* only returns SERIOUS errors */
static CURLcode altsvc_add(struct altsvcinfo *asi, const char *line)
{
/* Example line:
h2 example.com 443 h3 shiny.example.com 8443 "20191231 10:00:00" 1
*/
struct Curl_str srchost;
struct Curl_str dsthost;
struct Curl_str srcalpn;
struct Curl_str dstalpn;
struct Curl_str date;
curl_off_t srcport;
curl_off_t dstport;
curl_off_t persist;
curl_off_t prio;
if(curlx_str_word(&line, &srcalpn, MAX_ALTSVC_ALPNLEN) ||
curlx_str_singlespace(&line) ||
curlx_str_word(&line, &srchost, MAX_ALTSVC_HOSTLEN) ||
curlx_str_singlespace(&line) ||
curlx_str_number(&line, &srcport, 65535) ||
curlx_str_singlespace(&line) ||
curlx_str_word(&line, &dstalpn, MAX_ALTSVC_ALPNLEN) ||
curlx_str_singlespace(&line) ||
curlx_str_word(&line, &dsthost, MAX_ALTSVC_HOSTLEN) ||
curlx_str_singlespace(&line) ||
curlx_str_number(&line, &dstport, 65535) ||
curlx_str_singlespace(&line) ||
curlx_str_quotedword(&line, &date, MAX_ALTSVC_DATELEN) ||
curlx_str_singlespace(&line) ||
curlx_str_number(&line, &persist, 1) ||
curlx_str_singlespace(&line) ||
curlx_str_number(&line, &prio, 0) ||
curlx_str_newline(&line))
;
else {
char dbuf[MAX_ALTSVC_DATELEN + 1];
time_t expires = 0;
time_t now = time(NULL);
/* The date parser works on a null-terminated string. The maximum length
is upheld by curlx_str_quotedword(). */
memcpy(dbuf, curlx_str(&date), curlx_strlen(&date));
dbuf[curlx_strlen(&date)] = 0;
Curl_getdate_capped(dbuf, &expires);
if(now < expires) {
struct altsvc *as = altsvc_create(&srchost, &dsthost, &srcalpn, &dstalpn,
(size_t)srcport, (size_t)dstport);
if(as) {
as->expires = expires;
as->persist = persist ? 1 : 0;
altsvc_append(asi, as);
}
else
return CURLE_OUT_OF_MEMORY;
}
}
return CURLE_OK;
}
/*
* Load alt-svc entries from the given file. The text based line-oriented file
* format is documented here: https://curl.se/docs/alt-svc.html
*
* This function only returns error on major problems that prevent alt-svc
* handling to work completely. It will ignore individual syntactical errors
* etc.
*/
static CURLcode altsvc_load(struct altsvcinfo *asi, const char *file)
{
CURLcode result = CURLE_OK;
FILE *fp;
/* we need a private copy of the filename so that the altsvc cache file
name survives an easy handle reset */
curlx_free(asi->filename);
asi->filename = curlx_strdup(file);
if(!asi->filename)
return CURLE_OUT_OF_MEMORY;
fp = curlx_fopen(file, FOPEN_READTEXT);
if(fp) {
curlx_struct_stat stat;
if((curlx_fstat(fileno(fp), &stat) == -1) || !S_ISDIR(stat.st_mode)) {
bool eof = FALSE;
struct dynbuf buf;
curlx_dyn_init(&buf, MAX_ALTSVC_LINE);
do {
result = Curl_get_line(&buf, fp, &eof);
if(!result) {
const char *lineptr = curlx_dyn_ptr(&buf);
curlx_str_passblanks(&lineptr);
if(curlx_str_single(&lineptr, '#'))
altsvc_add(asi, lineptr);
}
} while(!result && !eof);
curlx_dyn_free(&buf); /* free the line buffer */
}
curlx_fclose(fp);
}
return result;
}
/*
* Write this single altsvc entry to a single output line
*/
static CURLcode altsvc_out(struct altsvc *as, FILE *fp)
{
struct tm stamp;
const char *dst6_pre = "";
const char *dst6_post = "";
const char *src6_pre = "";
const char *src6_post = "";
CURLcode result = curlx_gmtime(as->expires, &stamp);
if(result)
return result;
#ifdef USE_IPV6
else {
char ipv6_unused[16];
if(curlx_inet_pton(AF_INET6, as->dst.host, ipv6_unused) == 1) {
dst6_pre = "[";
dst6_post = "]";
}
if(curlx_inet_pton(AF_INET6, as->src.host, ipv6_unused) == 1) {
src6_pre = "[";
src6_post = "]";
}
}
#endif
curl_mfprintf(fp,
"%s %s%s%s %u "
"%s %s%s%s %u "
"\"%d%02d%02d "
"%02d:%02d:%02d\" "
"%d 0\n", /* prio still always zero */
Curl_alpnid2str(as->src.alpnid),
src6_pre, as->src.host, src6_post,
as->src.port,
Curl_alpnid2str(as->dst.alpnid),
dst6_pre, as->dst.host, dst6_post,
as->dst.port,
stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday,
stamp.tm_hour, stamp.tm_min, stamp.tm_sec,
as->persist);
return CURLE_OK;
}
/* ---- library-wide functions below ---- */
/*
* Curl_altsvc_init() creates a new altsvc cache.
* It returns the new instance or NULL if something goes wrong.
*/
struct altsvcinfo *Curl_altsvc_init(void)
{
struct altsvcinfo *asi = curlx_calloc(1, sizeof(struct altsvcinfo));
if(!asi)
return NULL;
Curl_llist_init(&asi->list, NULL);
/* set default behavior */
asi->flags = CURLALTSVC_H1
#ifdef USE_HTTP2
| CURLALTSVC_H2
#endif
#ifdef USE_HTTP3
| CURLALTSVC_H3
#endif
;
return asi;
}
/*
* Curl_altsvc_load() loads alt-svc from file.
*/
CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file)
{
DEBUGASSERT(asi);
return altsvc_load(asi, file);
}
/*
* Curl_altsvc_ctrl() passes on the external bitmask.
*/
CURLcode Curl_altsvc_ctrl(struct Curl_easy *data, const long ctrl)
{
DEBUGASSERT(data);
if(!ctrl)
return CURLE_BAD_FUNCTION_ARGUMENT;
if(!data->asi) {
data->asi = Curl_altsvc_init();
if(!data->asi)
return CURLE_OUT_OF_MEMORY;
}
data->asi->flags = ctrl;
return CURLE_OK;
}
/*
* Curl_altsvc_cleanup() frees an altsvc cache instance and all associated
* resources.
*/
void Curl_altsvc_cleanup(struct altsvcinfo **asi)
{
if(*asi) {
struct Curl_llist_node *e;
struct Curl_llist_node *n;
struct altsvcinfo *altsvc = *asi;
for(e = Curl_llist_head(&altsvc->list); e; e = n) {
struct altsvc *as = Curl_node_elem(e);
n = Curl_node_next(e);
altsvc_free(as);
}
curlx_free(altsvc->filename);
curlx_free(altsvc);
*asi = NULL; /* clear the pointer */
}
}
/*
* Curl_altsvc_save() writes the altsvc cache to a file.
*/
CURLcode Curl_altsvc_save(struct Curl_easy *data,
struct altsvcinfo *asi, const char *file)
{
CURLcode result = CURLE_OK;
FILE *out;
char *tempstore = NULL;
if(!asi)
/* no cache activated */
return CURLE_OK;
/* if not new name is given, use the one we stored from the load */
if(!file && asi->filename)
file = asi->filename;
if((asi->flags & CURLALTSVC_READONLYFILE) || !file || !file[0])
/* marked as read-only, no file or zero length filename */
return CURLE_OK;
result = Curl_fopen(data, file, &out, &tempstore);
if(!result) {
struct Curl_llist_node *e;
struct Curl_llist_node *n;
fputs("# Your alt-svc cache. https://curl.se/docs/alt-svc.html\n"
"# This file was generated by libcurl! Edit at your own risk.\n",
out);
for(e = Curl_llist_head(&asi->list); e; e = n) {
struct altsvc *as = Curl_node_elem(e);
n = Curl_node_next(e);
result = altsvc_out(as, out);
if(result)
break;
}
curlx_fclose(out);
if(!result && tempstore && curlx_rename(tempstore, file))
result = CURLE_WRITE_ERROR;
if(result && tempstore)
unlink(tempstore);
}
curlx_free(tempstore);
return result;
}
/* hostcompare() returns true if 'host' matches 'check'. The first host
* argument may have a trailing dot present that will be ignored.
*/
static bool hostcompare(const char *host, const char *check)
{
size_t hlen = strlen(host);
size_t clen = strlen(check);
if(hlen && (host[hlen - 1] == '.'))
hlen--;
if(hlen != clen)
/* they cannot match if they have different lengths */
return FALSE;
return curl_strnequal(host, check, hlen);
}
/* altsvc_flush() removes all alternatives for this source origin from the
list */
static void altsvc_flush(struct altsvcinfo *asi,
struct Curl_peer *origin,
enum alpnid origin_alpnid)
{
struct Curl_llist_node *e;
struct Curl_llist_node *n;
for(e = Curl_llist_head(&asi->list); e; e = n) {
struct altsvc *as = Curl_node_elem(e);
n = Curl_node_next(e);
if((origin_alpnid == as->src.alpnid) &&
(origin->port == as->src.port) &&
hostcompare(origin->hostname, as->src.host)) {
Curl_node_remove(e);
altsvc_free(as);
}
}
}
#define ALTSVC_MA 1
#define ALTSVC_PERSIST 2
static void altsvc_parse_params(const char **pp,
time_t *pmaxage,
bool *ppersist)
{
curlx_str_passblanks(pp);
if(curlx_str_single(pp, ';'))
return;
for(;;) {
struct Curl_str name;
struct Curl_str val;
curl_off_t num;
int keyword = 0;
/* allow some extra whitespaces around name and value */
if(curlx_str_until(pp, &name, MAX_ALTSVC_LINE, '=') ||
curlx_str_single(pp, '='))
break; /* skip further parameter parsing */
curlx_str_trimblanks(&name);
curlx_str_passblanks(pp);
if(**pp == '\"') {
if(curlx_str_quotedword(pp, &val, MAX_ALTSVC_LINE))
break;
}
else {
if(curlx_str_cspn(pp, &val, ",;\r\n"))
break;
}
curlx_str_trimblanks(&val);
if(curlx_str_casecompare(&name, "ma"))
keyword = ALTSVC_MA;
else if(curlx_str_casecompare(&name, "persist"))
keyword = ALTSVC_PERSIST;
if(keyword) {
const char *vp = curlx_str(&val);
const char *vend = vp + curlx_strlen(&val);
if(curlx_str_number(&vp, &num, TIME_T_MAX))
break; /* not a number, skip further parameter parsing */
if(vp != vend)
break; /* not entirely a number, skip further parameter parsing */
if(keyword == ALTSVC_MA)
*pmaxage = (time_t)num;
else if(num == 1)
*ppersist = TRUE;
}
curlx_str_passblanks(pp);
if(curlx_str_single(pp, ';'))
break; /* no further parameters */
}
}
static bool altsvc_parse_dest(const char **pp,
struct Curl_easy *data,
struct Curl_peer *origin,
struct Curl_str *dsthost,
uint16_t *pdstport)
{
curl_off_t port = 0;
if(curlx_str_single(pp, '\"'))
return FALSE;
/* quoted string, with hostname or just :port ? */
if(curlx_str_single(pp, ':')) { /* is hostname:port ? */
if(curlx_str_single(pp, '[')) { /* DNS hostname/IPv4 */
if(curlx_str_until(pp, dsthost, MAX_ALTSVC_HOSTLEN, ':')) {
infof(data, "Bad alt-svc hostname, ignoring.");
return FALSE;
}
}
else { /* IPv6 hostname */
if(curlx_str_until(pp, dsthost, MAX_IPADR_LEN, ']') ||
curlx_str_single(pp, ']')) {
infof(data, "Bad alt-svc IPv6 hostname, ignoring.");
return FALSE;
}
}
if(curlx_str_single(pp, ':'))
return FALSE; /* not followed by ':' */
}
else /* is only :port, hostname is effectively origin */
curlx_str_assign(dsthost, origin->hostname,
strlen(origin->hostname));
if(curlx_str_number(pp, &port, 0xffff)) {
infof(data, "Unknown alt-svc port number, ignoring.");
return FALSE;
}
*pdstport = (uint16_t)port;
if(curlx_str_single(pp, '\"'))
return FALSE; /* quoted string not ending here as expected */
return TRUE;
}
/*
* Curl_altsvc_parse() takes an incoming alt-svc response header and stores
* the data correctly in the cache.
*
* 'value' points to the header *value*. That is contents to the right of the
* header name.
*
* Currently this function rejects invalid data without returning an error.
* Invalid hostname, port number will result in the specific alternative
* being rejected. Unknown protocols are skipped.
*/
CURLcode Curl_altsvc_parse(struct Curl_easy *data,
struct altsvcinfo *asi, const char *value,
struct Curl_peer *origin,
enum alpnid origin_alpnid)
{
struct altsvc *as;
size_t entries = 0;
struct Curl_str alpn;
const char *p;
DEBUGASSERT(asi);
DEBUGASSERT(origin);
/* RFC 7838, The "Alt-Svc" header field value is basically
* Alt-Svc: (clear|alpn="(host)?:port"\s*(;\s*parameter=value)*)
* This can be repeated, comma-separated.
*
* We parse "best effort", ignoring values we do not recognize.
*/
/* Try to catch a standalone "clear" */
p = value;
if(!curlx_str_cspn(&p, &alpn, ";\n\r")) {
curlx_str_trimblanks(&alpn);
/* "clear" is a magic keyword */
if(curlx_str_casecompare(&alpn, "clear")) {
/* Flush cached alternatives for this source origin */
altsvc_flush(asi, origin, origin_alpnid);
return CURLE_OK;
}
}
/* Not a standalone "clear", parse from start for alpn entries */
for(p = value; *p;) {
time_t maxage = 24 * 3600; /* default is 24 hours */
bool persist = FALSE;
enum alpnid dstalpnid;
struct Curl_str dsthost;
uint16_t dstport;
if(curlx_str_until(&p, &alpn, MAX_ALTSVC_LINE, '='))
break; /* not another entry, leave */
curlx_str_trimblanks(&alpn);
dstalpnid = Curl_str2alpnid(&alpn);
if(curlx_str_single(&p, '='))
break;
/* Parse altsvc hostname:port */
if(!altsvc_parse_dest(&p, data, origin, &dsthost, &dstport))
break;
/* Parse optional parameters */
altsvc_parse_params(&p, &maxage, &persist);
if(dstalpnid) { /* this is a known ALPN id, e.g. not ALPN_none */
if(!entries++)
/* Flush cached alternatives for this source origin, if any - when
this is the first entry of the line. */
altsvc_flush(asi, origin, origin_alpnid);
as = altsvc_createid(origin->hostname, strlen(origin->hostname),
curlx_str(&dsthost),
curlx_strlen(&dsthost),
origin_alpnid, dstalpnid,
origin->port, dstport);
if(as) {
time_t secs = time(NULL);
/* The expires time also needs to take the Age: value (if any)
into account. [See RFC 7838 section 3.1] */
if(maxage > (TIME_T_MAX - secs))
as->expires = TIME_T_MAX;
else
as->expires = maxage + secs;
as->persist = persist;
altsvc_append(asi, as);
infof(data, "Added alt-svc: %.*s:%u over %s",
(int)curlx_strlen(&dsthost), curlx_str(&dsthost),
dstport, Curl_alpnid2str(dstalpnid));
}
else
return CURLE_OUT_OF_MEMORY;
}
/* When this is followed by a comma, we expect another entry */
if(curlx_str_single(&p, ','))
break;
}
return CURLE_OK;
}
/*
* Return TRUE on a match
*/
bool Curl_altsvc_lookup(struct altsvcinfo *asi,
struct Curl_peer *origin,
enum alpnid origin_alpnid,
struct altsvc **dstentry,
const int versions, /* one or more bits */
bool *psame_destination)
{
DEBUGASSERT(asi);
DEBUGASSERT(origin);
DEBUGASSERT(dstentry);
*psame_destination = FALSE;
if(Curl_llist_count(&asi->list)) {
struct Curl_llist_node *e;
struct Curl_llist_node *n;
time_t now = time(NULL);
for(e = Curl_llist_head(&asi->list); e; e = n) {
struct altsvc *as = Curl_node_elem(e);
n = Curl_node_next(e);
if(as->expires < now) {
/* an expired entry, remove */
Curl_node_remove(e);
altsvc_free(as);
continue;
}
if((origin_alpnid == as->src.alpnid) &&
(versions & (int)as->dst.alpnid) &&
(origin->port == as->src.port) &&
hostcompare(origin->hostname, as->src.host)) {
/* match */
*dstentry = as;
/* alt-svc on the same host+port or another one? */
*psame_destination = (origin->port == as->dst.port) &&
hostcompare(origin->hostname, as->dst.host);
return TRUE;
}
}
}
return FALSE;
}
#if defined(DEBUGBUILD) || defined(UNITTESTS)
#undef time
#endif
#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_ALTSVC */
+78
View File
@@ -0,0 +1,78 @@
#ifndef HEADER_CURL_ALTSVC_H
#define HEADER_CURL_ALTSVC_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC)
#include "llist.h"
struct Curl_peer;
/* the maximum number of alt-svc entries kept in a single cache */
#define MAX_ALTSVC_ENTRIES 5000
struct althost {
char *host;
uint16_t port;
enum alpnid alpnid;
};
struct altsvc {
struct althost src;
struct althost dst;
time_t expires;
struct Curl_llist_node node;
BIT(persist);
};
struct altsvcinfo {
char *filename;
struct Curl_llist list; /* list of entries */
long flags; /* the publicly set bitmask */
};
const char *Curl_alpnid2str(enum alpnid id);
struct altsvcinfo *Curl_altsvc_init(void);
CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file);
CURLcode Curl_altsvc_save(struct Curl_easy *data,
struct altsvcinfo *asi, const char *file);
CURLcode Curl_altsvc_ctrl(struct Curl_easy *data, const long ctrl);
void Curl_altsvc_cleanup(struct altsvcinfo **asi);
CURLcode Curl_altsvc_parse(struct Curl_easy *data,
struct altsvcinfo *asi, const char *value,
struct Curl_peer *origin,
enum alpnid origin_alpnid);
bool Curl_altsvc_lookup(struct altsvcinfo *asi,
struct Curl_peer *origin,
enum alpnid origin_alpnid,
struct altsvc **dstentry,
const int versions, /* CURLALTSVC_H* bits */
bool *psame_destination);
#else
/* disabled */
#define Curl_altsvc_save(a, b, c)
#define Curl_altsvc_cleanup(x)
#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_ALTSVC */
#endif /* HEADER_CURL_ALTSVC_H */
+239
View File
@@ -0,0 +1,239 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#ifdef __AMIGA__
#include "vdns/hostip.h"
#include "curl_addrinfo.h"
#include "amigaos.h"
#ifdef HAVE_PROTO_BSDSOCKET_H
# ifdef __amigaos4__
# include <bsdsocket/socketbasetags.h>
# elif !defined(USE_AMISSL)
# include <amitcp/socketbasetags.h>
# endif
# ifdef __libnix__
# include <stabs.h>
# endif
#endif
#ifdef HAVE_PROTO_BSDSOCKET_H
#ifdef __amigaos4__
/*
* AmigaOS 4.x specific code
*/
/*
* hostip4.c - Curl_ipv4_resolve_r() replacement code
*
* Logic that needs to be considered are the following build cases:
* - newlib networking
* - clib2 networking
* - direct bsdsocket.library networking (usually AmiSSL builds)
* Each with the threaded resolver enabled or not.
*
* With the threaded resolver enabled, try to use gethostbyname_r() where
* available, otherwise (re)open bsdsocket.library and fallback to
* gethostbyname().
*/
#include <proto/bsdsocket.h>
static struct SocketIFace *__CurlISocket = NULL;
static uint32 SocketFeatures = 0;
#define HAVE_BSDSOCKET_GETHOSTBYNAME_R 0x01
#define HAVE_BSDSOCKET_GETADDRINFO 0x02
CURLcode Curl_amiga_init(void)
{
struct SocketIFace *ISocket;
struct Library *base = OpenLibrary("bsdsocket.library", 4);
if(base) {
ISocket = (struct SocketIFace *)GetInterface(base, "main", 1, NULL);
if(ISocket) {
ULONG enabled = 0;
SocketBaseTags(SBTM_SETVAL(SBTC_CAN_SHARE_LIBRARY_BASES), TRUE,
SBTM_GETREF(SBTC_HAVE_GETHOSTADDR_R_API), (ULONG)&enabled,
TAG_DONE);
if(enabled) {
SocketFeatures |= HAVE_BSDSOCKET_GETHOSTBYNAME_R;
}
__CurlISocket = ISocket;
atexit(Curl_amiga_cleanup);
return CURLE_OK;
}
CloseLibrary(base);
}
return CURLE_FAILED_INIT;
}
void Curl_amiga_cleanup(void)
{
if(__CurlISocket) {
struct Library *base = __CurlISocket->Data.LibBase;
DropInterface((struct Interface *)__CurlISocket);
CloseLibrary(base);
__CurlISocket = NULL;
}
}
#ifdef CURLRES_AMIGA
/*
* Because we need to handle the different cases in hostip4.c at runtime,
* not at compile-time, based on what was detected in Curl_amiga_init(),
* we replace it completely with our own as to not complicate the baseline
* code. Assumes malloc/calloc/free are thread-safe because Curl_he2ai()
* allocates memory also.
*/
struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname, uint16_t port)
{
struct Curl_addrinfo *ai = NULL;
struct hostent *h;
struct SocketIFace *ISocket = __CurlISocket;
if(SocketFeatures & HAVE_BSDSOCKET_GETHOSTBYNAME_R) {
LONG h_errnop = 0;
struct hostent *buf;
buf = curlx_calloc(1, CURL_HOSTENT_SIZE);
if(buf) {
h = gethostbyname_r((STRPTR)hostname, buf,
(char *)buf + sizeof(struct hostent),
CURL_HOSTENT_SIZE - sizeof(struct hostent),
&h_errnop);
if(h) {
ai = Curl_he2ai(h, port);
}
curlx_free(buf);
}
}
else {
#ifdef USE_RESOLV_THREADED
/* gethostbyname() is not thread-safe, so we need to reopen bsdsocket
* on the thread's context
*/
struct Library *base = OpenLibrary("bsdsocket.library", 4);
if(base) {
ISocket = (struct SocketIFace *)GetInterface(base, "main", 1, NULL);
if(ISocket) {
h = gethostbyname((STRPTR)hostname);
if(h) {
ai = Curl_he2ai(h, port);
}
DropInterface((struct Interface *)ISocket);
}
CloseLibrary(base);
}
#else
/* not using threaded resolver - safe to use this as-is */
h = gethostbyname(hostname);
if(h) {
ai = Curl_he2ai(h, port);
}
#endif
}
return ai;
}
#endif /* CURLRES_AMIGA */
#ifdef USE_AMISSL
#include <signal.h>
int Curl_amiga_select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *errorfds, struct timeval *timeout)
{
int r = WaitSelect(nfds, readfds, writefds, errorfds, timeout, 0);
/* Ensure Ctrl-C signal is actioned */
if((r == -1) && (SOCKERRNO == SOCKEINTR))
raise(SIGINT);
return r;
}
#endif /* USE_AMISSL */
#elif !defined(USE_AMISSL) /* __amigaos4__ */
/*
* Amiga OS3 specific code
*/
struct Library *SocketBase = NULL;
#ifdef __libnix__
void __request(const char *msg);
#define CURL_AMIGA_REQUEST(msg) __request(msg)
#else
#define CURL_AMIGA_REQUEST(msg) Printf((const unsigned char *)(msg "\n\a"), 0)
#endif
void Curl_amiga_cleanup(void)
{
if(SocketBase) {
CloseLibrary(SocketBase);
SocketBase = NULL;
}
}
CURLcode Curl_amiga_init(void)
{
if(!SocketBase)
SocketBase = OpenLibrary((const unsigned char *)"bsdsocket.library", 4);
if(!SocketBase) {
CURL_AMIGA_REQUEST("No TCP/IP Stack running!");
return CURLE_FAILED_INIT;
}
if(SocketBaseTags(SBTM_SETVAL(SBTC_ERRNOPTR(sizeof(errno))), (ULONG)&errno,
SBTM_SETVAL(SBTC_LOGTAGPTR), (ULONG)"curl", TAG_DONE)) {
CURL_AMIGA_REQUEST("SocketBaseTags ERROR");
return CURLE_FAILED_INIT;
}
#ifndef __libnix__
atexit(Curl_amiga_cleanup);
#endif
return CURLE_OK;
}
#ifdef __libnix__
ADD2EXIT(Curl_amiga_cleanup, -50);
#endif
#endif /* !USE_AMISSL */
#endif /* HAVE_PROTO_BSDSOCKET_H */
#endif /* __AMIGA__ */
+41
View File
@@ -0,0 +1,41 @@
#ifndef HEADER_CURL_AMIGAOS_H
#define HEADER_CURL_AMIGAOS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#if defined(__AMIGA__) && defined(HAVE_PROTO_BSDSOCKET_H) && \
(!defined(USE_AMISSL) || defined(__amigaos4__))
CURLcode Curl_amiga_init(void);
void Curl_amiga_cleanup(void);
#else
#define Curl_amiga_init() CURLE_OK
#define Curl_amiga_cleanup() Curl_nop_stmt
#endif
#endif /* HEADER_CURL_AMIGAOS_H */
+449
View File
@@ -0,0 +1,449 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include "urldata.h"
#include "api.h"
#include "curl_threads.h"
#include "multiif.h"
#include "vtls/vtls_scache.h"
typedef char mapi_fn_ids_fit_uint8[
(CURL_MAPI_FN_LAST <= CURL_CBAPI_FN_START) ? 1 : -1];
typedef char cbapi_fn_ids_fit_uint8[
((CURL_CBAPI_FN_LAST - 1) <= UINT8_MAX) ? 1 : -1];
typedef char mapi_depth_fits_uint8[
(CURL_MAPI_MAX_RECURSION <= UINT8_MAX) ? 1 : -1];
struct Curl_eapi_fn_props {
Curl_eapi_fn fn;
uint8_t data_is_killed; /* easy handle is killed in call */
uint8_t recurse; /* may be called when another call is in progress */
uint8_t no_event_cb; /* may not be called during a multi event callback */
uint8_t no_scache_lock; /* may not be called with easy's vtls_scache
locked by current thread */
};
static const struct Curl_eapi_fn_props eapi_fn_props[CURL_EAPI_FN_LAST] = {
/* function kill rec !ev !scach */
{ CURL_EAPI_FN_easy_cleanup, 1, 0, 0, 0 },
{ CURL_EAPI_FN_easy_duphandle, 0, 1, 0, 0 },
{ CURL_EAPI_FN_easy_getinfo, 0, 1, 0, 0 },
{ CURL_EAPI_FN_easy_header, 0, 1, 0, 0 },
{ CURL_EAPI_FN_easy_nextheader, 0, 1, 0, 0 },
{ CURL_EAPI_FN_easy_pause, 0, 1, 1, 0 },
{ CURL_EAPI_FN_easy_perform_ev, 0, 0, 0, 1 },
{ CURL_EAPI_FN_easy_perform, 0, 0, 0, 1 },
{ CURL_EAPI_FN_easy_recv, 0, 0, 0, 1 },
{ CURL_EAPI_FN_easy_reset, 0, 0, 0, 0 },
{ CURL_EAPI_FN_easy_send, 0, 0, 0, 1 },
{ CURL_EAPI_FN_easy_setopt, 0, 1, 0, 0 },
{ CURL_EAPI_FN_easy_ssls_export, 0, 0, 0, 1 },
{ CURL_EAPI_FN_easy_ssls_import, 0, 0, 0, 1 },
{ CURL_EAPI_FN_easy_upkeep, 0, 0, 0, 1 },
{ CURL_EAPI_FN_ws_recv, 0, 1, 0, 1 },
{ CURL_EAPI_FN_ws_send, 0, 1, 0, 1 },
{ CURL_EAPI_FN_ws_start_frame, 0, 1, 0, 0 },
};
struct Curl_mapi_fn_props {
Curl_mapi_fn fn;
uint8_t multi_is_killed; /* multi handle is killed during call */
uint8_t recurse; /* may be called when another call is in progress */
uint8_t allow_ntfy_cb; /* may be called during a notify callback */
uint8_t no_scache_lock; /* may not be called with multi's vtls_scache
locked by current thread */
};
static const struct Curl_mapi_fn_props mapi_fn_props[CURL_MAPI_FN_LAST] = {
/* function kill rec ntfy !scach */
{ CURL_MAPI_FN_multi_add_handle, 0, 0, 1, 0 },
{ CURL_MAPI_FN_multi_assign, 0, 1, 1, 0 },
{ CURL_MAPI_FN_multi_cleanup, 1, 0, 0, 1 },
{ CURL_MAPI_FN_multi_fdset, 0, 0, 1, 0 },
{ CURL_MAPI_FN_multi_get_handles, 0, 1, 1, 0 },
{ CURL_MAPI_FN_multi_get_offt, 0, 1, 1, 0 },
{ CURL_MAPI_FN_multi_info_read, 0, 1, 1, 0 },
{ CURL_MAPI_FN_multi_notify_disable, 0, 1, 1, 0 },
{ CURL_MAPI_FN_multi_notify_enable, 0, 1, 1, 0 },
{ CURL_MAPI_FN_multi_perform, 0, 0, 0, 1 },
{ CURL_MAPI_FN_multi_poll, 0, 0, 1, 0 },
{ CURL_MAPI_FN_multi_remove_handle, 0, 0, 1, 0 },
{ CURL_MAPI_FN_multi_setopt, 0, 0, 1, 0 },
{ CURL_MAPI_FN_multi_socket_action, 0, 0, 0, 1 },
{ CURL_MAPI_FN_multi_socket_all, 0, 0, 0, 1 },
{ CURL_MAPI_FN_multi_socket, 0, 0, 0, 1 },
{ CURL_MAPI_FN_multi_timeout, 0, 0, 1, 1 },
{ CURL_MAPI_FN_multi_wait, 0, 0, 1, 0 },
{ CURL_MAPI_FN_multi_waitfds, 0, 0, 1, 0 },
};
struct Curl_cbapi_fn_props {
Curl_cbapi_fn fn;
uint8_t is_event_cb; /* is a multi event processing callback */
};
static const struct Curl_cbapi_fn_props
cbapi_fn_props[CURL_CBAPI_FN_LAST - CURL_CBAPI_FN_START] = {
{ CURL_CBAPI_FN_easy_chunk_bgn, 0 },
{ CURL_CBAPI_FN_easy_chunk_end, 0 },
{ CURL_CBAPI_FN_easy_closesocket, 0 },
{ CURL_CBAPI_FN_easy_cr_in_read, 0 },
{ CURL_CBAPI_FN_easy_cr_in_resume_from, 0 },
{ CURL_CBAPI_FN_easy_cw_out_cb, 0 },
{ CURL_CBAPI_FN_easy_fdebug, 0 },
{ CURL_CBAPI_FN_easy_fnmatch_data, 0 },
{ CURL_CBAPI_FN_easy_fopensocket, 0 },
{ CURL_CBAPI_FN_easy_fprereq, 0 },
{ CURL_CBAPI_FN_easy_fprogress, 0 },
{ CURL_CBAPI_FN_easy_fread_func, 0 },
{ CURL_CBAPI_FN_easy_fsockopt, 0 },
{ CURL_CBAPI_FN_easy_fsslctx, 0 },
{ CURL_CBAPI_FN_easy_fwrite_rtp, 0 },
{ CURL_CBAPI_FN_easy_fxferinfo, 0 },
{ CURL_CBAPI_FN_easy_ioctl_func, 0 },
{ CURL_CBAPI_FN_easy_resolver_start, 0 },
{ CURL_CBAPI_FN_easy_seek_func, 0 },
{ CURL_CBAPI_FN_easy_ssh_hostkeyfunc, 0 },
{ CURL_CBAPI_FN_easy_ssh_keyfunc, 0 },
{ CURL_CBAPI_FN_easy_trailer_callback, 0 },
{ CURL_CBAPI_FN_multi_ntfy_cb, 0 },
{ CURL_CBAPI_FN_multi_push_cb, 0 },
{ CURL_CBAPI_FN_multi_socket_cb, 1 },
{ CURL_CBAPI_FN_multi_timer_cb, 1 },
};
static bool eapi_in_event_cb(struct Curl_easy *data)
{
struct Curl_multi *multi = data->multi;
if(multi && multi->callstack.count) {
size_t i;
for(i = 0; i < multi->callstack.count; ++i) {
if(multi->callstack.calls[i] >= CURL_CBAPI_FN_START) {
uint8_t fn = multi->callstack.calls[i];
if((fn < CURL_CBAPI_FN_LAST) &&
cbapi_fn_props[fn - CURL_CBAPI_FN_START].is_event_cb)
return TRUE;
}
}
}
return FALSE;
}
static bool mapi_in_ntfy_cb(struct Curl_multi *multi)
{
if(multi && multi->callstack.count) {
size_t i;
for(i = 0; i < multi->callstack.count; ++i) {
if(multi->callstack.calls[i] == CURL_CBAPI_FN_multi_ntfy_cb)
return TRUE;
}
}
return FALSE;
}
bool Curl_api_multi_is_in_callback(struct Curl_multi *multi)
{
if(multi && multi->callstack.count) {
size_t i;
for(i = 0; i < multi->callstack.count; ++i) {
if(multi->callstack.calls[i] >= CURL_CBAPI_FN_START)
return TRUE;
}
}
return FALSE;
}
bool Curl_api_is_in_callback(struct Curl_easy *data)
{
if(data && data->multi) {
return Curl_api_multi_is_in_callback(data->multi);
}
return FALSE;
}
bool Curl_eapi_enter(struct Curl_eapi_guard *guard,
CURL *curl,
Curl_eapi_fn fn,
CURLcode *presult)
{
struct Curl_easy *data = curl;
const struct Curl_eapi_fn_props *fn_props;
CURLcode result = CURLE_OK;
guard->depth = 0;
/* Verify that we got an easy handle we can work with. */
if(!GOOD_EASY_HANDLE(data) || data->state.internal) {
result = CURLE_BAD_FUNCTION_ARGUMENT;
goto out;
}
/* verify that is either not added to a multi handle OR has a
* GOOD multi handle that knows `data` for `data->mid`. */
if(data->mid != UINT32_MAX) {
if(GOOD_MULTI_HANDLE(data->multi)) {
if(!Curl_multi_knows_easy(data->multi, data)) {
/* But multi does not know it, something is fishy, better deny call */
DEBUGASSERT(0);
result = CURLE_BAD_FUNCTION_ARGUMENT;
goto out;
}
}
else {
DEBUGASSERT(0); /* data needs to have a GOOD multi handle */
result = CURLE_BAD_FUNCTION_ARGUMENT;
goto out;
}
}
else if(data->multi) {
DEBUGASSERT(0); /* data should not have a multi handle */
result = CURLE_BAD_FUNCTION_ARGUMENT;
goto out;
}
/* verify that the call `fn` we're about to enter is known
* and check call properties to be admitting. */
if(fn >= CURL_EAPI_FN_LAST) {
result = CURLE_BAD_FUNCTION_ARGUMENT;
goto out;
}
fn_props = &eapi_fn_props[fn];
DEBUGASSERT(fn_props->fn == fn);
if(!fn_props->recurse) {
if(data->callstack.count) {
#ifdef CURLVERBOSE
DEBUGF(curl_mfprintf(stderr,
"EAPI guard: calling %hu with call to %u ongoing\n", (uint16_t)fn,
data->callstack.calls[data->callstack.count - 1]));
#endif
result = CURLE_RECURSIVE_API_CALL;
goto out;
}
if(data->multi && data->multi->callstack.count) {
#ifdef CURLVERBOSE
DEBUGF(curl_mfprintf(stderr,
"EAPI guard: calling %hu with multi call to %u ongoing\n",
(uint16_t)fn,
data->multi->callstack.calls[data->multi->callstack.count - 1]));
#endif
result = CURLE_RECURSIVE_API_CALL;
goto out;
}
}
if(fn_props->no_event_cb && eapi_in_event_cb(data)) {
/* Not allowed to be invoked while an event cb is ongoing */
#ifdef CURLVERBOSE
DEBUGF(curl_mfprintf(stderr,
"EAPI guard: calling %hu while event callback ongoing\n",
(uint16_t)fn));
#endif
result = CURLE_RECURSIVE_API_CALL;
goto out;
}
#if defined(USE_SSL) && defined(USE_MUTEX)
if(fn_props->no_scache_lock &&
Curl_ssl_scache_is_locked_by_current_thread(data)) {
#ifdef CURLVERBOSE
DEBUGF(curl_mfprintf(stderr,
"EAPI guard: calling %hu while vtls_scache is locked by "
"current thread\n", (uint16_t)fn));
#endif
result = CURLE_RECURSIVE_API_CALL;
goto out;
}
#endif
/* all fine, add to data's callstack */
if(data->callstack.count >= CURL_EAPI_MAX_RECURSION) {
result = CURLE_RECURSIVE_API_CALL;
goto out;
}
data->callstack.calls[data->callstack.count] = (uint16_t)fn;
++data->callstack.count;
guard->depth = data->callstack.count;
guard->data = fn_props->data_is_killed ? NULL : data;
out:
if(presult)
*presult = result;
return guard->depth > 0;
}
void Curl_eapi_leave(struct Curl_eapi_guard *guard)
{
if(guard->depth) {
/* guard->data is set when handle is supposed to stay alive during call */
if(guard->data && GOOD_EASY_HANDLE(guard->data)) {
if(guard->depth > guard->data->callstack.count) {
DEBUGASSERT(0); /* something very wrong */
}
else {
if(guard->depth < guard->data->callstack.count) {
DEBUGASSERT(0); /* someone forgot to clean up */
}
/* reset to depth the guard was entered in */
guard->data->callstack.count = (uint16_t)(guard->depth - 1);
}
}
}
}
CURLHcode Curl_eapi_hcode(CURLcode result)
{
switch(result) {
case CURLE_OK:
return CURLHE_OK;
case CURLE_BAD_FUNCTION_ARGUMENT:
return CURLHE_BAD_ARGUMENT;
case CURLE_OUT_OF_MEMORY:
return CURLHE_OUT_OF_MEMORY;
case CURLE_NOT_BUILT_IN:
return CURLHE_NOT_BUILT_IN;
default:
/* Unfortunately, we cannot convert RECURSIVE_API_CALL,
* but since the header API is reentrant, this should not happen. */
return CURLHE_BAD_ARGUMENT;
}
}
bool Curl_mapi_enter(struct Curl_mapi_guard *guard,
CURLM *m,
Curl_mapi_fn fn,
CURLMcode *pmresult)
{
struct Curl_multi *multi = m;
const struct Curl_mapi_fn_props *fn_props;
CURLMcode mresult = CURLM_OK;
guard->depth = 0;
/* Verify that we got an easy handle we can work with. */
if(!GOOD_MULTI_HANDLE(multi)) {
mresult = CURLM_BAD_HANDLE;
goto out;
}
if(fn >= CURL_MAPI_FN_LAST) {
mresult = CURLM_BAD_FUNCTION_ARGUMENT;
goto out;
}
fn_props = &mapi_fn_props[fn];
DEBUGASSERT(fn_props->fn == fn);
if(fn_props->allow_ntfy_cb && mapi_in_ntfy_cb(multi)) {
/* explicitly allowed, even though normal recursion may not */
}
else if(!fn_props->recurse && multi->callstack.count) {
#ifdef CURLVERBOSE
DEBUGF(curl_mfprintf(stderr,
"MAPI guard: calling %hu with call to %u ongoing\n", (uint16_t)fn,
multi->callstack.calls[multi->callstack.count - 1]));
#endif
mresult = CURLM_RECURSIVE_API_CALL;
goto out;
}
#if defined(USE_SSL) && defined(USE_MUTEX)
if(fn_props->no_scache_lock && multi->ssl_scache &&
Curl_ssl_scache_is_locked_by_current_thread(multi->admin)) {
#ifdef CURLVERBOSE
DEBUGF(curl_mfprintf(stderr,
"MAPI guard: calling %hu while its vtls_scache is locked by "
"current thread\n", (uint16_t)fn));
#endif
mresult = CURLM_RECURSIVE_API_CALL;
goto out;
}
#endif
/* all fine, add to data's callstack */
if(multi->callstack.count >= CURL_MAPI_MAX_RECURSION) {
mresult = CURLM_RECURSIVE_API_CALL;
goto out;
}
multi->callstack.calls[multi->callstack.count] = (uint8_t)fn;
++multi->callstack.count;
guard->depth = multi->callstack.count;
guard->multi = fn_props->multi_is_killed ? NULL : multi;
out:
if(pmresult)
*pmresult = mresult;
return guard->depth > 0;
}
void Curl_mapi_leave(struct Curl_mapi_guard *guard)
{
if(guard->depth) {
/* guard->data is set when handle is supposed to stay alive during call */
if(guard->multi && GOOD_MULTI_HANDLE(guard->multi)) {
if(guard->depth > guard->multi->callstack.count) {
DEBUGASSERT(0); /* something very wrong */
}
else {
if(guard->depth < guard->multi->callstack.count) {
DEBUGASSERT(0); /* someone forgot to clean up */
}
/* reset to depth the guard was entered in */
guard->multi->callstack.count = (uint8_t)(guard->depth - 1);
}
}
}
}
void Curl_cbapi_enter(struct Curl_mapi_guard *guard,
struct Curl_easy *data,
struct Curl_multi *multi,
Curl_cbapi_fn fn)
{
guard->depth = 0;
if(!multi)
multi = data ? data->multi : NULL;
/* if not multi is involved here, just leave */
if(!multi)
return;
/* invalid callback specifier? */
if((fn >= CURL_CBAPI_FN_LAST) || (fn < CURL_CBAPI_FN_START)) {
DEBUGASSERT(0);
return;
}
DEBUGASSERT(cbapi_fn_props[fn - CURL_CBAPI_FN_START].fn == fn);
/* all fine, add to data's callstack */
/* if multi callstack already at max depth, leave */
if(multi->callstack.count >= CURL_MAPI_MAX_RECURSION) {
DEBUGASSERT(0);
return;
}
multi->callstack.calls[multi->callstack.count] = (uint8_t)fn;
++multi->callstack.count;
guard->depth = multi->callstack.count;
guard->multi = multi;
}
void Curl_cbapi_leave(struct Curl_mapi_guard *guard)
{
Curl_mapi_leave(guard);
}
+212
View File
@@ -0,0 +1,212 @@
#ifndef HEADER_CURL_API_H
#define HEADER_CURL_API_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#define CURLEASY_MAGIC_NUMBER 0xc0dedbadU
#ifdef DEBUGBUILD
/* On a debug build, we want to fail hard on easy handles that
* are not NULL, but no longer have the MAGIC touch. This gives
* us early warning on things only discovered by valgrind otherwise. */
#define GOOD_EASY_HANDLE(x) \
(((x) && ((x)->magic == CURLEASY_MAGIC_NUMBER)) ? TRUE : \
(DEBUGASSERT(!(x)), FALSE))
#else
#define GOOD_EASY_HANDLE(x) \
((x) && ((x)->magic == CURLEASY_MAGIC_NUMBER))
#endif
#define CURLMULTI_MAGIC_NUMBER 0x000bab1e
#ifdef DEBUGBUILD
/* On a debug build, we want to fail hard on multi handles that
* are not NULL, but no longer have the MAGIC touch. This gives
* us early warning on things only discovered by valgrind otherwise. */
#define GOOD_MULTI_HANDLE(x) \
(((x) && (x)->magic == CURLMULTI_MAGIC_NUMBER) ? TRUE : \
(DEBUGASSERT(!(x)), FALSE))
#else
#define GOOD_MULTI_HANDLE(x) \
((x) && (x)->magic == CURLMULTI_MAGIC_NUMBER)
#endif
/* the API functions called on a CURL* */
typedef enum {
CURL_EAPI_FN_easy_cleanup,
CURL_EAPI_FN_easy_duphandle,
CURL_EAPI_FN_easy_getinfo,
CURL_EAPI_FN_easy_header,
CURL_EAPI_FN_easy_nextheader,
CURL_EAPI_FN_easy_pause,
CURL_EAPI_FN_easy_perform_ev,
CURL_EAPI_FN_easy_perform,
CURL_EAPI_FN_easy_recv,
CURL_EAPI_FN_easy_reset,
CURL_EAPI_FN_easy_send,
CURL_EAPI_FN_easy_setopt,
CURL_EAPI_FN_easy_ssls_export,
CURL_EAPI_FN_easy_ssls_import,
CURL_EAPI_FN_easy_upkeep,
CURL_EAPI_FN_ws_recv,
CURL_EAPI_FN_ws_send,
CURL_EAPI_FN_ws_start_frame,
CURL_EAPI_FN_LAST
} Curl_eapi_fn;
/* the API functions called on a CURLM* */
typedef enum {
CURL_MAPI_FN_multi_add_handle,
CURL_MAPI_FN_multi_assign,
CURL_MAPI_FN_multi_cleanup,
CURL_MAPI_FN_multi_fdset,
CURL_MAPI_FN_multi_get_handles,
CURL_MAPI_FN_multi_get_offt,
CURL_MAPI_FN_multi_info_read,
CURL_MAPI_FN_multi_notify_disable,
CURL_MAPI_FN_multi_notify_enable,
CURL_MAPI_FN_multi_perform,
CURL_MAPI_FN_multi_poll,
CURL_MAPI_FN_multi_remove_handle,
CURL_MAPI_FN_multi_setopt,
CURL_MAPI_FN_multi_socket_action,
CURL_MAPI_FN_multi_socket_all,
CURL_MAPI_FN_multi_socket,
CURL_MAPI_FN_multi_timeout,
CURL_MAPI_FN_multi_wait,
CURL_MAPI_FN_multi_waitfds,
CURL_MAPI_FN_LAST
} Curl_mapi_fn;
#define CURL_CBAPI_FN_START 128
/* the callback functions */
typedef enum {
CURL_CBAPI_FN_easy_chunk_bgn = CURL_CBAPI_FN_START,
CURL_CBAPI_FN_easy_chunk_end,
CURL_CBAPI_FN_easy_closesocket,
CURL_CBAPI_FN_easy_cr_in_read,
CURL_CBAPI_FN_easy_cr_in_resume_from,
CURL_CBAPI_FN_easy_cw_out_cb,
CURL_CBAPI_FN_easy_fdebug,
CURL_CBAPI_FN_easy_fnmatch_data,
CURL_CBAPI_FN_easy_fopensocket,
CURL_CBAPI_FN_easy_fprereq,
CURL_CBAPI_FN_easy_fprogress,
CURL_CBAPI_FN_easy_fread_func,
CURL_CBAPI_FN_easy_fsockopt,
CURL_CBAPI_FN_easy_fsslctx,
CURL_CBAPI_FN_easy_fwrite_rtp,
CURL_CBAPI_FN_easy_fxferinfo,
CURL_CBAPI_FN_easy_ioctl_func,
CURL_CBAPI_FN_easy_resolver_start,
CURL_CBAPI_FN_easy_seek_func,
CURL_CBAPI_FN_easy_ssh_hostkeyfunc,
CURL_CBAPI_FN_easy_ssh_keyfunc,
CURL_CBAPI_FN_easy_trailer_callback,
CURL_CBAPI_FN_multi_ntfy_cb,
CURL_CBAPI_FN_multi_push_cb,
CURL_CBAPI_FN_multi_socket_cb,
CURL_CBAPI_FN_multi_timer_cb,
CURL_CBAPI_FN_LAST
} Curl_cbapi_fn;
/* EAPI */
#define CURL_EAPI_MAX_RECURSION 7
struct Curl_eapi_stack {
uint16_t count;
uint16_t calls[CURL_EAPI_MAX_RECURSION];
};
struct Curl_eapi_guard {
struct Curl_easy *data; /* != NULL if handle stays */
uint16_t depth; /* > 0 if this guard was entered */
};
bool Curl_eapi_enter(struct Curl_eapi_guard *guard,
CURL *curl,
Curl_eapi_fn fn,
CURLcode *presult);
void Curl_eapi_leave(struct Curl_eapi_guard *guard);
/* Convert an EAPI failure to a header API result */
CURLHcode Curl_eapi_hcode(CURLcode result);
/* Curl_eapi_enter() checks for curl being NULL, but windows compiler
* analyzers do not realize this. *sigh* */
#define CURL_EAPI_ENTER(g, curl, fn, r) \
Curl_eapi_enter((g), (curl), CURL_EAPI_FN_##fn, (r)) && (curl)
#define CURL_EAPI_LEAVE(g) \
Curl_eapi_leave(g)
/* MAPI */
#define CURL_MAPI_MAX_RECURSION 15
struct Curl_mapi_stack {
uint8_t count;
uint8_t calls[CURL_MAPI_MAX_RECURSION];
};
struct Curl_mapi_guard {
struct Curl_multi *multi; /* != NULL if handle stays */
uint8_t depth; /* > 0 if this guard was entered */
};
bool Curl_mapi_enter(struct Curl_mapi_guard *guard,
CURLM *m,
Curl_mapi_fn fn,
CURLMcode *pmresult);
void Curl_mapi_leave(struct Curl_mapi_guard *guard);
/* Curl_mapi_enter() checks for m being NULL, but windows compiler
* analyzers do not realize this. *sigh* */
#define CURL_MAPI_ENTER(g, m, fn, r) \
Curl_mapi_enter((g), (m), CURL_MAPI_FN_##fn, (r)) && (m)
#define CURL_MAPI_LEAVE(g) \
Curl_mapi_leave(g)
void Curl_cbapi_enter(struct Curl_mapi_guard *guard,
struct Curl_easy *data,
struct Curl_multi *multi,
Curl_cbapi_fn fn);
void Curl_cbapi_leave(struct Curl_mapi_guard *guard);
#define CURL_CBAPI_START(g, d, fn) \
Curl_cbapi_enter((g), (d), NULL, CURL_CBAPI_FN_##fn)
#define CURL_CBAPI_MULTI_START(g, m, fn) \
Curl_cbapi_enter((g), NULL, (m), CURL_CBAPI_FN_##fn)
#define CURL_CBAPI_END(g) \
Curl_cbapi_leave(g)
#define CURL_CBAPI_MULTI_END(g) \
Curl_cbapi_leave(g)
bool Curl_api_is_in_callback(struct Curl_easy *data);
bool Curl_api_multi_is_in_callback(struct Curl_multi *multi);
#endif /* HEADER_CURL_API_H */
+116
View File
@@ -0,0 +1,116 @@
#ifndef HEADER_CURL_ARPA_TELNET_H
#define HEADER_CURL_ARPA_TELNET_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#ifndef CURL_DISABLE_TELNET
/*
* Telnet option defines. Add more here if in need.
*/
#define CURL_TELOPT_BINARY 0 /* binary 8-bit data */
#define CURL_TELOPT_ECHO 1 /* echo */
#define CURL_TELOPT_SGA 3 /* Suppress Go Ahead */
#define CURL_TELOPT_EXOPL 255 /* EXtended OPtions List */
#define CURL_TELOPT_TTYPE 24 /* Terminal TYPE */
#define CURL_TELOPT_NAWS 31 /* Negotiate About Window Size */
#define CURL_TELOPT_XDISPLOC 35 /* X DISPlay LOCation */
#define CURL_TELOPT_NEW_ENVIRON 39 /* NEW ENVIRONment variables */
#define CURL_NEW_ENV_VAR 0
#define CURL_NEW_ENV_VALUE 1
#ifdef CURLVERBOSE
/*
* The telnet options represented as strings
*/
static const char * const telnetoptions[] = {
"BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD",
"NAME", "STATUS", "TIMING MARK", "RCTE",
"NAOL", "NAOP", "NAOCRD", "NAOHTS",
"NAOHTD", "NAOFFD", "NAOVTS", "NAOVTD",
"NAOLFD", "EXTEND ASCII", "LOGOUT", "BYTE MACRO",
"DE TERMINAL", "SUPDUP", "SUPDUP OUTPUT", "SEND LOCATION",
"TERM TYPE", "END OF RECORD", "TACACS UID", "OUTPUT MARKING",
"TTYLOC", "3270 REGIME", "X3 PAD", "NAWS",
"TERM SPEED", "LFLOW", "LINEMODE", "XDISPLOC",
"OLD-ENVIRON", "AUTHENTICATION", "ENCRYPT", "NEW-ENVIRON"
};
#define CURL_TELOPT(x) telnetoptions[x]
#else
#define CURL_TELOPT(x) ""
#endif
#define CURL_TELOPT_MAXIMUM CURL_TELOPT_NEW_ENVIRON
#define CURL_TELOPT_OK(x) ((x) <= CURL_TELOPT_MAXIMUM)
#define CURL_NTELOPTS 40
/*
* First some defines
*/
#define CURL_xEOF 236 /* End Of File */
#define CURL_SE 240 /* Sub negotiation End */
#define CURL_NOP 241 /* No OPeration */
#define CURL_DM 242 /* Data Mark */
#define CURL_GA 249 /* Go Ahead, reverse the line */
#define CURL_SB 250 /* SuBnegotiation */
#define CURL_WILL 251 /* Our side WILL use this option */
#define CURL_WONT 252 /* Our side will not use this option */
#define CURL_DO 253 /* DO use this option! */
#define CURL_DONT 254 /* DO NOT use this option! */
#define CURL_IAC 255 /* Interpret As Command */
#ifdef CURLVERBOSE
/*
* Then those numbers represented as strings:
*/
static const char * const telnetcmds[] = {
"EOF", "SUSP", "ABORT", "EOR", "SE",
"NOP", "DMARK", "BRK", "IP", "AO",
"AYT", "EC", "EL", "GA", "SB",
"WILL", "WONT", "DO", "DONT", "IAC"
};
#endif
#define CURL_TELCMD_MINIMUM CURL_xEOF /* the first one */
#define CURL_TELCMD_MAXIMUM CURL_IAC /* surprise, 255 is the last one! ;-) */
#define CURL_TELQUAL_IS 0
#define CURL_TELQUAL_SEND 1
#define CURL_TELQUAL_INFO 2
#define CURL_TELQUAL_NAME 3
#define CURL_TELCMD_OK(x) \
(((unsigned int)(x) >= CURL_TELCMD_MINIMUM) && \
((unsigned int)(x) <= CURL_TELCMD_MAXIMUM))
#ifdef CURLVERBOSE
#define CURL_TELCMD(x) telnetcmds[(x) - CURL_TELCMD_MINIMUM]
#else
#define CURL_TELCMD(x) ""
#endif
#endif /* CURL_DISABLE_TELNET */
#endif /* HEADER_CURL_ARPA_TELNET_H */
+619
View File
@@ -0,0 +1,619 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include "bufq.h"
static bool chunk_is_empty(const struct buf_chunk *chunk)
{
return chunk->r_offset >= chunk->w_offset;
}
static bool chunk_is_full(const struct buf_chunk *chunk)
{
return chunk->w_offset >= chunk->dlen;
}
static size_t chunk_len(const struct buf_chunk *chunk)
{
return chunk->w_offset - chunk->r_offset;
}
static void chunk_reset(struct buf_chunk *chunk)
{
chunk->next = NULL;
chunk->r_offset = chunk->w_offset = 0;
}
static size_t chunk_append(struct buf_chunk *chunk,
const uint8_t *buf, size_t len)
{
uint8_t *p = &chunk->x.data[chunk->w_offset];
size_t n = chunk->dlen - chunk->w_offset;
DEBUGASSERT(chunk->dlen >= chunk->w_offset);
if(n) {
n = CURLMIN(n, len);
memcpy(p, buf, n);
chunk->w_offset += n;
}
return n;
}
static size_t chunk_read(struct buf_chunk *chunk,
uint8_t *buf, size_t len)
{
uint8_t *p = &chunk->x.data[chunk->r_offset];
size_t n = chunk->w_offset - chunk->r_offset;
DEBUGASSERT(chunk->w_offset >= chunk->r_offset);
if(!n) {
return 0;
}
else if(n <= len) {
memcpy(buf, p, n);
chunk->r_offset = chunk->w_offset = 0;
return n;
}
else {
memcpy(buf, p, len);
chunk->r_offset += len;
return len;
}
}
static CURLcode chunk_slurpn(struct buf_chunk *chunk, size_t max_len,
Curl_bufq_reader *reader,
void *reader_ctx, size_t *pnread)
{
uint8_t *p = &chunk->x.data[chunk->w_offset];
size_t n = chunk->dlen - chunk->w_offset; /* free amount */
CURLcode result;
*pnread = 0;
DEBUGASSERT(chunk->dlen >= chunk->w_offset);
if(!n)
return CURLE_AGAIN;
if(max_len && n > max_len)
n = max_len;
result = reader(reader_ctx, p, n, pnread);
if(!result) {
DEBUGASSERT(*pnread <= n);
chunk->w_offset += *pnread;
}
return result;
}
static void chunk_peek(const struct buf_chunk *chunk,
const uint8_t **pbuf, size_t *plen)
{
DEBUGASSERT(chunk->w_offset >= chunk->r_offset);
*pbuf = &chunk->x.data[chunk->r_offset];
*plen = chunk->w_offset - chunk->r_offset;
}
static void chunk_peek_at(const struct buf_chunk *chunk, size_t offset,
const uint8_t **pbuf, size_t *plen)
{
offset += chunk->r_offset;
DEBUGASSERT(chunk->w_offset >= offset);
*pbuf = &chunk->x.data[offset];
*plen = chunk->w_offset - offset;
}
static size_t chunk_skip(struct buf_chunk *chunk, size_t amount)
{
size_t n = chunk->w_offset - chunk->r_offset;
DEBUGASSERT(chunk->w_offset >= chunk->r_offset);
if(n) {
n = CURLMIN(n, amount);
chunk->r_offset += n;
if(chunk->r_offset == chunk->w_offset)
chunk->r_offset = chunk->w_offset = 0;
}
return n;
}
static void chunk_list_free(struct buf_chunk **anchor)
{
struct buf_chunk *chunk;
while(*anchor) {
chunk = *anchor;
*anchor = chunk->next;
curlx_free(chunk);
}
}
void Curl_bufcp_init(struct bufc_pool *pool,
size_t chunk_size, size_t spare_max)
{
DEBUGASSERT(chunk_size > 0);
DEBUGASSERT(spare_max > 0);
memset(pool, 0, sizeof(*pool));
pool->chunk_size = chunk_size;
pool->spare_max = spare_max;
}
static CURLcode bufcp_take(struct bufc_pool *pool,
struct buf_chunk **pchunk)
{
struct buf_chunk *chunk = NULL;
if(pool->spare) {
chunk = pool->spare;
pool->spare = chunk->next;
--pool->spare_count;
chunk_reset(chunk);
*pchunk = chunk;
return CURLE_OK;
}
/* Check for integer overflow before allocation */
if(pool->chunk_size > SIZE_MAX - sizeof(*chunk)) {
*pchunk = NULL;
return CURLE_OUT_OF_MEMORY;
}
chunk = curlx_calloc(1, sizeof(*chunk) + pool->chunk_size);
if(!chunk) {
*pchunk = NULL;
return CURLE_OUT_OF_MEMORY;
}
chunk->dlen = pool->chunk_size;
*pchunk = chunk;
return CURLE_OK;
}
static void bufcp_put(struct bufc_pool *pool,
struct buf_chunk *chunk)
{
if(pool->spare_count >= pool->spare_max) {
curlx_free(chunk);
}
else {
chunk_reset(chunk);
chunk->next = pool->spare;
pool->spare = chunk;
++pool->spare_count;
}
}
void Curl_bufcp_free(struct bufc_pool *pool)
{
chunk_list_free(&pool->spare);
pool->spare_count = 0;
}
static void bufq_init(struct bufq *q, struct bufc_pool *pool,
size_t chunk_size, size_t max_chunks, int opts)
{
DEBUGASSERT(chunk_size > 0);
DEBUGASSERT(max_chunks > 0);
memset(q, 0, sizeof(*q));
q->chunk_size = chunk_size;
q->max_chunks = max_chunks;
q->pool = pool;
q->opts = opts;
}
void Curl_bufq_init2(struct bufq *q, size_t chunk_size, size_t max_chunks,
int opts)
{
bufq_init(q, NULL, chunk_size, max_chunks, opts);
}
void Curl_bufq_init(struct bufq *q, size_t chunk_size, size_t max_chunks)
{
bufq_init(q, NULL, chunk_size, max_chunks, BUFQ_OPT_NONE);
}
void Curl_bufq_initp(struct bufq *q, struct bufc_pool *pool,
size_t max_chunks, int opts)
{
bufq_init(q, pool, pool->chunk_size, max_chunks, opts);
}
void Curl_bufq_free(struct bufq *q)
{
chunk_list_free(&q->head);
chunk_list_free(&q->spare);
q->tail = NULL;
q->chunk_count = 0;
}
void Curl_bufq_reset(struct bufq *q)
{
struct buf_chunk *chunk;
while(q->head) {
chunk = q->head;
q->head = chunk->next;
chunk->next = q->spare;
q->spare = chunk;
}
q->tail = NULL;
}
size_t Curl_bufq_len(const struct bufq *q)
{
const struct buf_chunk *chunk = q->head;
size_t len = 0;
while(chunk) {
len += chunk_len(chunk);
chunk = chunk->next;
}
return len;
}
bool Curl_bufq_is_empty(const struct bufq *q)
{
return !q->head || chunk_is_empty(q->head);
}
bool Curl_bufq_is_full(const struct bufq *q)
{
if(!q->tail || q->spare)
return FALSE;
if(q->chunk_count < q->max_chunks)
return FALSE;
if(q->chunk_count > q->max_chunks)
return TRUE;
/* we have no spares and cannot make more, is the tail full? */
return chunk_is_full(q->tail);
}
static struct buf_chunk *get_spare(struct bufq *q)
{
struct buf_chunk *chunk = NULL;
if(q->spare) {
chunk = q->spare;
q->spare = chunk->next;
chunk_reset(chunk);
return chunk;
}
if(q->chunk_count >= q->max_chunks && (!(q->opts & BUFQ_OPT_SOFT_LIMIT)))
return NULL;
if(q->pool) {
if(bufcp_take(q->pool, &chunk))
return NULL;
++q->chunk_count;
return chunk;
}
else {
/* Check for integer overflow before allocation */
if(q->chunk_size > SIZE_MAX - sizeof(*chunk)) {
return NULL;
}
chunk = curlx_calloc(1, sizeof(*chunk) + q->chunk_size);
if(!chunk)
return NULL;
chunk->dlen = q->chunk_size;
++q->chunk_count;
return chunk;
}
}
static void prune_head(struct bufq *q)
{
struct buf_chunk *chunk;
while(q->head && chunk_is_empty(q->head)) {
chunk = q->head;
q->head = chunk->next;
if(q->tail == chunk)
q->tail = q->head;
if(q->pool) {
bufcp_put(q->pool, chunk);
--q->chunk_count;
}
else if((q->chunk_count > q->max_chunks) ||
(q->opts & BUFQ_OPT_NO_SPARES)) {
/* SOFT_LIMIT allowed us more than max. free spares until
* we are at max again. Or free them if we are configured
* to not use spares. */
curlx_free(chunk);
--q->chunk_count;
}
else {
chunk->next = q->spare;
q->spare = chunk;
}
}
}
static struct buf_chunk *get_non_full_tail(struct bufq *q)
{
struct buf_chunk *chunk;
if(q->tail && !chunk_is_full(q->tail))
return q->tail;
chunk = get_spare(q);
if(chunk) {
/* new tail, and possibly new head */
if(q->tail) {
q->tail->next = chunk;
q->tail = chunk;
}
else {
DEBUGASSERT(!q->head);
q->head = q->tail = chunk;
}
}
return chunk;
}
CURLcode Curl_bufq_write(struct bufq *q,
const uint8_t *buf, size_t len,
size_t *pnwritten)
{
struct buf_chunk *tail;
size_t n;
DEBUGASSERT(q->max_chunks > 0);
*pnwritten = 0;
while(len) {
tail = get_non_full_tail(q);
if(!tail) {
if((q->chunk_count < q->max_chunks) || (q->opts & BUFQ_OPT_SOFT_LIMIT))
/* should have gotten a tail, but did not */
return CURLE_OUT_OF_MEMORY;
break;
}
n = chunk_append(tail, buf, len);
if(!n)
break;
*pnwritten += n;
buf += n;
len -= n;
}
return (!*pnwritten && len) ? CURLE_AGAIN : CURLE_OK;
}
CURLcode Curl_bufq_cwrite(struct bufq *q,
const char *buf, size_t len,
size_t *pnwritten)
{
return Curl_bufq_write(q, (const uint8_t *)buf, len, pnwritten);
}
CURLcode Curl_bufq_read(struct bufq *q, uint8_t *buf, size_t len,
size_t *pnread)
{
*pnread = 0;
while(len && q->head) {
size_t n = chunk_read(q->head, buf, len);
if(n) {
*pnread += n;
buf += n;
len -= n;
}
prune_head(q);
}
return (!*pnread) ? CURLE_AGAIN : CURLE_OK;
}
CURLcode Curl_bufq_cread(struct bufq *q, char *buf, size_t len,
size_t *pnread)
{
return Curl_bufq_read(q, (uint8_t *)buf, len, pnread);
}
bool Curl_bufq_peek(struct bufq *q,
const uint8_t **pbuf, size_t *plen)
{
if(q->head && chunk_is_empty(q->head)) {
prune_head(q);
}
if(q->head && !chunk_is_empty(q->head)) {
chunk_peek(q->head, pbuf, plen);
return TRUE;
}
*pbuf = NULL;
*plen = 0;
return FALSE;
}
bool Curl_bufq_peek_at(struct bufq *q, size_t offset,
const uint8_t **pbuf, size_t *plen)
{
struct buf_chunk *c = q->head;
size_t clen;
while(c) {
clen = chunk_len(c);
if(!clen)
break;
if(offset >= clen) {
offset -= clen;
c = c->next;
continue;
}
chunk_peek_at(c, offset, pbuf, plen);
return TRUE;
}
*pbuf = NULL;
*plen = 0;
return FALSE;
}
void Curl_bufq_skip(struct bufq *q, size_t amount)
{
size_t n;
while(amount && q->head) {
n = chunk_skip(q->head, amount);
amount -= n;
prune_head(q);
}
}
CURLcode Curl_bufq_pass(struct bufq *q, Curl_bufq_writer *writer,
void *writer_ctx, size_t *pwritten)
{
const uint8_t *buf;
size_t blen;
CURLcode result = CURLE_OK;
*pwritten = 0;
while(Curl_bufq_peek(q, &buf, &blen)) {
size_t chunk_written;
result = writer(writer_ctx, buf, blen, &chunk_written);
if(result) {
if((result == CURLE_AGAIN) && *pwritten) {
/* blocked on subsequent write, report success */
result = CURLE_OK;
}
break;
}
if(!chunk_written) {
if(!*pwritten) {
/* treat as blocked */
result = CURLE_AGAIN;
}
break;
}
*pwritten += chunk_written;
Curl_bufq_skip(q, chunk_written);
}
return result;
}
CURLcode Curl_bufq_write_pass(struct bufq *q,
const uint8_t *buf, size_t len,
Curl_bufq_writer *writer, void *writer_ctx,
size_t *pwritten)
{
CURLcode result = CURLE_OK;
size_t n;
*pwritten = 0;
while(len) {
if(Curl_bufq_is_full(q)) {
/* try to make room in case we are full */
result = Curl_bufq_pass(q, writer, writer_ctx, &n);
if(result) {
if(result != CURLE_AGAIN) {
/* real error, fail */
return result;
}
/* would block, bufq is full, give up */
break;
}
}
/* Add to bufq as much as there is room for */
result = Curl_bufq_write(q, buf, len, &n);
if(result) {
if(result != CURLE_AGAIN)
/* real error, fail */
return result;
/* result == CURLE_AGAIN */
if(*pwritten)
/* we did write successfully before */
result = CURLE_OK;
return result;
}
else if(n == 0)
/* edge case of writer returning 0 (and len is >0)
* break or we might enter an infinite loop here */
break;
/* Track what we added to bufq */
buf += n;
len -= n;
*pwritten += n;
}
return (!*pwritten && len) ? CURLE_AGAIN : CURLE_OK;
}
CURLcode Curl_bufq_sipn(struct bufq *q, size_t max_len,
Curl_bufq_reader *reader, void *reader_ctx,
size_t *pnread)
{
struct buf_chunk *tail = NULL;
*pnread = 0;
tail = get_non_full_tail(q);
if(!tail) {
if(q->chunk_count < q->max_chunks)
return CURLE_OUT_OF_MEMORY;
/* full, blocked */
return CURLE_AGAIN;
}
return chunk_slurpn(tail, max_len, reader, reader_ctx, pnread);
}
/**
* Read up to `max_len` bytes and append it to the end of the buffer queue.
* if `max_len` is 0, no limit is imposed and the call behaves exactly
* the same as `Curl_bufq_slurp()`.
* Returns the total amount of buf read (may be 0) in `pnread` or error
* Note that even in case of an error chunks may have been read and
* the buffer queue will have different length than before.
*/
static CURLcode bufq_slurpn(struct bufq *q, size_t max_len,
Curl_bufq_reader *reader, void *reader_ctx,
size_t *pnread)
{
CURLcode result;
*pnread = 0;
while(1) {
size_t n;
result = Curl_bufq_sipn(q, max_len, reader, reader_ctx, &n);
if(result) {
if(!*pnread || result != CURLE_AGAIN) {
/* blocked on first read or real error, fail */
return result;
}
result = CURLE_OK;
break;
}
else if(n == 0) {
/* eof, result remains CURLE_OK */
break;
}
*pnread += n;
if(max_len) {
DEBUGASSERT(n <= max_len);
max_len -= n;
if(!max_len)
break;
}
/* give up slurping when we get less bytes than we asked for */
if(q->tail && !chunk_is_full(q->tail))
break;
}
return result;
}
CURLcode Curl_bufq_slurp(struct bufq *q, Curl_bufq_reader *reader,
void *reader_ctx, size_t *pnread)
{
return bufq_slurpn(q, 0, reader, reader_ctx, pnread);
}
+257
View File
@@ -0,0 +1,257 @@
#ifndef HEADER_CURL_BUFQ_H
#define HEADER_CURL_BUFQ_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
/**
* A chunk of bytes for reading and writing.
* The size is fixed a creation with read and write offset
* for where unread content is.
*/
struct buf_chunk {
struct buf_chunk *next; /* to keep it in a list */
size_t dlen; /* the amount of allocated x.data[] */
size_t r_offset; /* first unread bytes */
size_t w_offset; /* one after last written byte */
union {
uint8_t data[1]; /* the buffer for `dlen` bytes */
void *dummy; /* alignment */
} x;
};
/**
* A pool for providing/keeping a number of chunks of the same size
*
* The same pool can be shared by many `bufq` instances. A pool is not thread
* safe. All bufqs using it are supposed to operate in the same thread.
*/
struct bufc_pool {
struct buf_chunk *spare; /* list of available spare chunks */
size_t chunk_size; /* the size of chunks in this pool */
size_t spare_count; /* current number of spare chunks in list */
size_t spare_max; /* max number of spares to keep */
};
void Curl_bufcp_init(struct bufc_pool *pool,
size_t chunk_size, size_t spare_max);
void Curl_bufcp_free(struct bufc_pool *pool);
/**
* A queue of byte chunks for reading and writing.
* Reading is done from `head`, writing is done to `tail`.
*
* `bufq`s can be empty or full or neither. Its `len` is the number
* of bytes that can be read. For an empty bufq, `len` will be 0.
*
* By default, a bufq can hold up to `max_chunks * chunk_size` number
* of bytes. When `max_chunks` are used (in the `head` list) and the
* `tail` chunk is full, the bufq will report that it is full.
*
* On a full bufq, `len` may be less than the maximum number of bytes,
* e.g. when the head chunk is partially read. `len` may also become
* larger than the max when option `BUFQ_OPT_SOFT_LIMIT` is used.
*
* By default, writing to a full bufq will return (-1, CURLE_AGAIN). Same
* as reading from an empty bufq.
* With `BUFQ_OPT_SOFT_LIMIT` set, a bufq will allow writing beyond this limit
* and use more than `max_chunks`. It will report that it is full
* nevertheless. This is provided for situation where writes preferably never
* fail (except for memory exhaustion).
*
* By default and without a pool, a bufq will keep chunks that read
* empty in its `spare` list. Option `BUFQ_OPT_NO_SPARES` will
* disable that and free chunks once they become empty.
*
* When providing a pool to a bufq, all chunk creation and spare handling
* will be delegated to that pool.
*/
struct bufq {
struct buf_chunk *head; /* chunk with bytes to read from */
struct buf_chunk *tail; /* chunk to write to */
struct buf_chunk *spare; /* list of free chunks, unless `pool` */
struct bufc_pool *pool; /* optional pool for free chunks */
size_t chunk_count; /* current number of chunks in `head+spare` */
size_t max_chunks; /* max `head` chunks to use */
size_t chunk_size; /* size of chunks to manage */
int opts; /* options for handling queue, see below */
};
/**
* Default behaviour: chunk limit is "hard", meaning attempts to write
* more bytes than can be hold in `max_chunks` is refused and will return
* -1, CURLE_AGAIN. */
#define BUFQ_OPT_NONE 0
/**
* Make `max_chunks` a "soft" limit. A bufq will report that it is "full"
* when `max_chunks` are used, but allows writing beyond this limit.
*/
#define BUFQ_OPT_SOFT_LIMIT (1 << 0)
/**
* Do not keep spare chunks.
*/
#define BUFQ_OPT_NO_SPARES (1 << 1)
/**
* Initialize a buffer queue that can hold up to `max_chunks` buffers
* each of size `chunk_size`. The bufq will not allow writing of
* more bytes than can be held in `max_chunks`.
*/
void Curl_bufq_init(struct bufq *q, size_t chunk_size, size_t max_chunks);
/**
* Initialize a buffer queue that can hold up to `max_chunks` buffers
* each of size `chunk_size` with the given options. See `BUFQ_OPT_*`.
*/
void Curl_bufq_init2(struct bufq *q, size_t chunk_size,
size_t max_chunks, int opts);
void Curl_bufq_initp(struct bufq *q, struct bufc_pool *pool,
size_t max_chunks, int opts);
/**
* Reset the buffer queue to be empty. Keep any allocated buffer chunks
* around.
*/
void Curl_bufq_reset(struct bufq *q);
/**
* Free all resources held by the buffer queue.
*/
void Curl_bufq_free(struct bufq *q);
/**
* Return the total amount of data in the queue.
*/
size_t Curl_bufq_len(const struct bufq *q);
/**
* Returns TRUE iff there is no data in the buffer queue.
*/
bool Curl_bufq_is_empty(const struct bufq *q);
/**
* Returns TRUE iff there is no space left in the buffer queue.
*/
bool Curl_bufq_is_full(const struct bufq *q);
/**
* Write buf to the end of the buffer queue. The buf is copied
* and the amount of copied bytes is returned.
* CURLE_AGAIN is returned if the buffer queue is full.
*/
CURLcode Curl_bufq_write(struct bufq *q,
const uint8_t *buf, size_t len,
size_t *pnwritten);
CURLcode Curl_bufq_cwrite(struct bufq *q,
const char *buf, size_t len,
size_t *pnwritten);
/**
* Read buf from the start of the buffer queue. The buf is copied
* and the amount of copied bytes is returned.
*/
CURLcode Curl_bufq_read(struct bufq *q, uint8_t *buf, size_t len,
size_t *pnread);
CURLcode Curl_bufq_cread(struct bufq *q, char *buf, size_t len,
size_t *pnread);
/**
* Peek at the head chunk in the buffer queue. Returns a pointer to
* the chunk buf (at the current offset) and its length. Does not
* modify the buffer queue.
* Returns TRUE iff bytes are available. Sets `pbuf` to NULL and `plen`
* to 0 when no bytes are available.
* Repeated calls return the same information until the buffer queue
* is modified, see `Curl_bufq_skip()``
*/
bool Curl_bufq_peek(struct bufq *q,
const uint8_t **pbuf, size_t *plen);
bool Curl_bufq_peek_at(struct bufq *q, size_t offset,
const uint8_t **pbuf, size_t *plen);
/**
* Tell the buffer queue to discard `amount` buf bytes at the head of the
* queue. Skipping more buf than is currently buffered will empty the queue.
*/
void Curl_bufq_skip(struct bufq *q, size_t amount);
typedef CURLcode Curl_bufq_writer(void *writer_ctx,
const uint8_t *buf, size_t len,
size_t *pwritten);
/**
* Passes the chunks in the buffer queue to the writer and returns
* the amount of buf written. A writer may return -1 and CURLE_AGAIN
* to indicate blocking at which point the queue will stop and return
* the amount of buf passed so far.
* -1 is returned on any other errors reported by the writer.
* Note that in case of a -1 chunks may have been written and
* the buffer queue will have different length than before.
*/
CURLcode Curl_bufq_pass(struct bufq *q, Curl_bufq_writer *writer,
void *writer_ctx, size_t *pwritten);
typedef CURLcode Curl_bufq_reader(void *reader_ctx,
uint8_t *buf, size_t len,
size_t *pnread);
/**
* Read bytes and append them to the end of the buffer queue until the
* reader returns blocking or the queue is full. A reader returns
* CURLE_AGAIN to indicate blocking.
* Returns the total amount of buf read (may be 0) in `pnread` on success.
* Note that in case of an error chunks may have been read and
* the buffer queue will have different length than before.
*/
CURLcode Curl_bufq_slurp(struct bufq *q, Curl_bufq_reader *reader,
void *reader_ctx, size_t *pnread);
/**
* Read *once* up to `max_len` bytes and append it to the buffer.
* if `max_len` is 0, no limit is imposed besides the chunk space.
* Returns the total amount of buf read (may be 0) or -1 on other
* reader errors.
*/
CURLcode Curl_bufq_sipn(struct bufq *q, size_t max_len,
Curl_bufq_reader *reader, void *reader_ctx,
size_t *pnread);
/**
* Write buf to the end of the buffer queue.
* Write bufq content or passed `buf` directly using the `writer`
* callback when it sees fit. 'buf' might get passed directly
* on or is placed into the buffer, depending on `len` and current
* amount buffered, chunk size, etc.
*/
CURLcode Curl_bufq_write_pass(struct bufq *q,
const uint8_t *buf, size_t len,
Curl_bufq_writer *writer, void *writer_ctx,
size_t *pwritten);
#endif /* HEADER_CURL_BUFQ_H */
+138
View File
@@ -0,0 +1,138 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include "urldata.h"
#include "bufref.h"
#include "curlx/strdup.h"
#ifdef DEBUGBUILD
#define SIGNATURE 0x5c48e9b2 /* Random pattern. */
#endif
/*
* Init a bufref struct.
*/
void Curl_bufref_init(struct bufref *br)
{
DEBUGASSERT(br);
br->dtor = NULL;
br->ptr = NULL;
br->len = 0;
#ifdef DEBUGBUILD
br->signature = SIGNATURE;
#endif
}
/*
* Free the buffer and re-init the necessary fields. It does not touch the
* 'signature' field and thus this buffer reference can be reused.
*/
void Curl_bufref_free(struct bufref *br)
{
DEBUGASSERT(br);
DEBUGASSERT(br->signature == SIGNATURE);
DEBUGASSERT(br->ptr || !br->len);
if(br->ptr && br->dtor)
br->dtor(CURL_UNCONST(br->ptr));
br->dtor = NULL;
br->ptr = NULL;
br->len = 0;
}
/*
* Set the buffer reference to new values. The previously referenced buffer
* is released before assignment.
*/
void Curl_bufref_set(struct bufref *br, const void *ptr, size_t len,
void (*dtor)(void *))
{
DEBUGASSERT(ptr || !len);
DEBUGASSERT(len <= CURL_MAX_INPUT_LENGTH);
Curl_bufref_free(br);
br->ptr = (const unsigned char *)ptr;
br->len = len;
br->dtor = dtor;
}
/*
* Get a pointer to the referenced buffer.
*/
const unsigned char *Curl_bufref_uptr(const struct bufref *br)
{
DEBUGASSERT(br);
DEBUGASSERT(br->signature == SIGNATURE);
DEBUGASSERT(br->ptr || !br->len);
return br->ptr;
}
/*
* Get a pointer to the referenced string.
*/
const char *Curl_bufref_ptr(const struct bufref *br)
{
DEBUGASSERT(br);
DEBUGASSERT(br->signature == SIGNATURE);
DEBUGASSERT(br->ptr || !br->len);
return (const char *)br->ptr;
}
/*
* Get the length of the referenced buffer data.
*/
size_t Curl_bufref_len(const struct bufref *br)
{
DEBUGASSERT(br);
DEBUGASSERT(br->signature == SIGNATURE);
DEBUGASSERT(br->ptr || !br->len);
return br->len;
}
CURLcode Curl_bufref_memdup0(struct bufref *br, const void *ptr, size_t len)
{
unsigned char *cpy = NULL;
DEBUGASSERT(br);
DEBUGASSERT(br->signature == SIGNATURE);
DEBUGASSERT(br->ptr || !br->len);
DEBUGASSERT(ptr || !len);
DEBUGASSERT(len <= CURL_MAX_INPUT_LENGTH);
if(ptr) {
cpy = curlx_memdup0(ptr, len);
if(!cpy)
return CURLE_OUT_OF_MEMORY;
}
Curl_bufref_set(br, cpy, len, curl_free);
return CURLE_OK;
}
+51
View File
@@ -0,0 +1,51 @@
#ifndef HEADER_CURL_BUFREF_H
#define HEADER_CURL_BUFREF_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
/*
* Generic buffer reference.
*/
struct bufref {
void (*dtor)(void *); /* Associated destructor. */
const unsigned char *ptr; /* Referenced data buffer. */
size_t len; /* The data size in bytes. */
#ifdef DEBUGBUILD
int signature; /* Detect API use mistakes. */
#endif
};
void Curl_bufref_init(struct bufref *br);
void Curl_bufref_set(struct bufref *br, const void *ptr, size_t len,
void (*dtor)(void *));
const char *Curl_bufref_ptr(const struct bufref *br);
const unsigned char *Curl_bufref_uptr(const struct bufref *br);
size_t Curl_bufref_len(const struct bufref *br);
CURLcode Curl_bufref_memdup0(struct bufref *br, const void *ptr, size_t len);
void Curl_bufref_free(struct bufref *br);
/* return a strdup() version of the buffer */
#define Curl_bufref_dup(x) curlx_strdup(Curl_bufref_ptr(x))
#endif
+965
View File
@@ -0,0 +1,965 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
#include <curl/curl.h>
#include "urldata.h"
#include "curlx/dynbuf.h"
#include "sendf.h"
#include "http.h"
#include "http1.h"
#include "http_proxy.h"
#include "select.h"
#include "progress.h"
#include "multiif.h"
#include "cfilters.h"
#include "cf-h1-proxy.h"
#include "connect.h"
#include "curl_trc.h"
#include "strcase.h"
#include "curlx/strparse.h"
typedef enum {
H1_TUNNEL_INIT, /* init/default/no tunnel state */
H1_TUNNEL_CONNECT, /* CONNECT request is being send */
H1_TUNNEL_RECEIVE, /* CONNECT answer is being received */
H1_TUNNEL_RESPONSE, /* CONNECT response received completely */
H1_TUNNEL_ESTABLISHED,
H1_TUNNEL_FAILED
} h1_tunnel_state;
/* struct for HTTP CONNECT tunneling */
struct h1_tunnel_state {
struct Curl_peer *dest;
struct dynbuf rcvbuf;
struct dynbuf request_data;
size_t nsent;
size_t headerlines;
struct Curl_chunker ch;
int httpversion;
enum keeponval {
KEEPON_DONE,
KEEPON_CONNECT,
KEEPON_IGNORE
} keepon;
curl_off_t cl; /* size of content to read and ignore */
h1_tunnel_state tunnel_state;
BIT(chunked_encoding);
BIT(close_connection);
BIT(maybe_folded);
BIT(leading_unfold);
BIT(udp_tunnel);
};
/* Persistent context for the H1-PROXY filter */
struct cf_h1_proxy_ctx {
struct Curl_peer *peer;
struct h1_tunnel_state *ts;
};
static bool tunnel_is_established(struct h1_tunnel_state *ts)
{
return ts && (ts->tunnel_state == H1_TUNNEL_ESTABLISHED);
}
static bool tunnel_is_failed(struct h1_tunnel_state *ts)
{
return ts && (ts->tunnel_state == H1_TUNNEL_FAILED);
}
static bool h1_proxy_is_udp(struct Curl_cfilter *cf)
{
struct cf_h1_proxy_ctx *pctx = cf->ctx;
return (bool)(pctx->ts && pctx->ts->udp_tunnel);
}
static CURLcode tunnel_reinit(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct h1_tunnel_state *ts)
{
(void)data;
(void)cf;
DEBUGASSERT(ts);
curlx_dyn_reset(&ts->rcvbuf);
curlx_dyn_reset(&ts->request_data);
ts->tunnel_state = H1_TUNNEL_INIT;
ts->keepon = KEEPON_CONNECT;
ts->cl = 0;
ts->close_connection = FALSE;
ts->maybe_folded = FALSE;
ts->leading_unfold = FALSE;
ts->chunked_encoding = FALSE;
ts->nsent = 0;
ts->headerlines = 0;
return CURLE_OK;
}
static CURLcode tunnel_init(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct h1_tunnel_state **pts)
{
struct h1_tunnel_state *ts;
if(cf->conn->scheme->flags & PROTOPT_NOTCPPROXY) {
failf(data, "%s cannot be done over CONNECT", cf->conn->scheme->name);
return CURLE_UNSUPPORTED_PROTOCOL;
}
ts = curlx_calloc(1, sizeof(*ts));
if(!ts)
return CURLE_OUT_OF_MEMORY;
infof(data, "allocate connect buffer");
curlx_dyn_init(&ts->rcvbuf, DYN_PROXY_CONNECT_HEADERS);
curlx_dyn_init(&ts->request_data, DYN_HTTP_REQUEST);
Curl_httpchunk_init(data, &ts->ch, TRUE, TRUE);
*pts = ts;
return tunnel_reinit(cf, data, ts);
}
static void h1_tunnel_go_state(struct Curl_cfilter *cf,
struct h1_tunnel_state *ts,
h1_tunnel_state new_state,
struct Curl_easy *data)
{
if(ts->tunnel_state == new_state)
return;
/* entering this one */
switch(new_state) {
case H1_TUNNEL_INIT:
CURL_TRC_CF(data, cf, "new tunnel state 'init'");
tunnel_reinit(cf, data, ts);
break;
case H1_TUNNEL_CONNECT:
CURL_TRC_CF(data, cf, "new tunnel state 'connect'");
ts->tunnel_state = H1_TUNNEL_CONNECT;
ts->keepon = KEEPON_CONNECT;
curlx_dyn_reset(&ts->rcvbuf);
break;
case H1_TUNNEL_RECEIVE:
CURL_TRC_CF(data, cf, "new tunnel state 'receive'");
ts->tunnel_state = H1_TUNNEL_RECEIVE;
break;
case H1_TUNNEL_RESPONSE:
CURL_TRC_CF(data, cf, "new tunnel state 'response'");
ts->tunnel_state = H1_TUNNEL_RESPONSE;
break;
case H1_TUNNEL_ESTABLISHED:
CURL_TRC_CF(data, cf, "new tunnel state 'established'");
infof(data, "CONNECT%s phase completed for HTTP proxy",
h1_proxy_is_udp(cf) ? "-UDP" : "");
data->state.authproxy.done = TRUE;
data->state.authproxy.multipass = FALSE;
FALLTHROUGH();
case H1_TUNNEL_FAILED:
if(new_state == H1_TUNNEL_FAILED)
CURL_TRC_CF(data, cf, "new tunnel state 'failed'");
ts->tunnel_state = new_state;
curlx_dyn_reset(&ts->rcvbuf);
curlx_dyn_reset(&ts->request_data);
/* restore the protocol pointer */
data->info.httpcode = 0; /* clear it as it might have been used for the
proxy */
/* If a proxy-authorization header was used for the proxy, then we should
make sure that it is not accidentally used for the document request
after we have connected. Let's thus free and clear it here. */
curlx_safefree(data->req.hd_proxy_auth);
break;
}
}
static void tunnel_free(struct h1_tunnel_state *ts,
struct Curl_easy *data)
{
if(ts) {
Curl_peer_unlink(&ts->dest);
curlx_dyn_free(&ts->rcvbuf);
curlx_dyn_free(&ts->request_data);
Curl_httpchunk_free(data, &ts->ch);
curlx_free(ts);
}
}
static void cf_tunnel_free(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
if(cf) {
struct cf_h1_proxy_ctx *pctx = cf->ctx;
struct h1_tunnel_state *ts = pctx ? pctx->ts : NULL;
if(ts) {
h1_tunnel_go_state(cf, ts, H1_TUNNEL_FAILED, data);
tunnel_free(ts, data);
pctx->ts = NULL;
}
}
}
static bool tunnel_want_send(struct h1_tunnel_state *ts)
{
return ts->tunnel_state == H1_TUNNEL_CONNECT;
}
static CURLcode start_CONNECT(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct h1_tunnel_state *ts)
{
struct cf_h1_proxy_ctx *pctx = cf->ctx;
struct httpreq *req = NULL;
int http_minor;
CURLcode result;
DEBUGASSERT(data);
/* This only happens if we have looped here due to authentication reasons,
and we do not really use the newly cloned URL here then. Free it. */
curlx_safefree(data->req.newurl);
result = Curl_http_proxy_create_tunnel_request(&req, cf, data,
pctx->peer, ts->dest,
PROXY_HTTP_V1,
h1_proxy_is_udp(cf));
if(result)
goto out;
curlx_dyn_reset(&ts->request_data);
ts->nsent = 0;
ts->headerlines = 0;
http_minor = ts->httpversion % 10;
result = Curl_h1_req_write_head(req, http_minor, &ts->request_data);
if(!result)
result = Curl_creader_set_null(data);
out:
if(result)
failf(data, "Failed sending CONNECT to proxy");
if(req)
Curl_http_req_free(req);
return result;
}
static CURLcode send_CONNECT(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct h1_tunnel_state *ts,
bool *done)
{
const uint8_t *buf = curlx_dyn_uptr(&ts->request_data);
size_t request_len = curlx_dyn_len(&ts->request_data);
size_t blen = request_len;
CURLcode result = CURLE_OK;
size_t nwritten;
if(blen <= ts->nsent)
goto out; /* we are done */
blen -= ts->nsent;
buf += ts->nsent;
result = cf->next->cft->do_send(cf->next, data, buf, blen, FALSE, &nwritten);
if(result) {
if(result == CURLE_AGAIN)
result = CURLE_OK;
goto out;
}
DEBUGASSERT(blen >= nwritten);
ts->nsent += nwritten;
Curl_debug(data, CURLINFO_HEADER_OUT, (const char *)buf, nwritten);
out:
if(result)
failf(data, "Failed sending CONNECT to proxy");
*done = (!result && (ts->nsent >= request_len));
return result;
}
static CURLcode on_resp_status(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct h1_tunnel_state *ts,
const char *header)
{
struct SingleRequest *k = &data->req;
(void)ts;
if(!strncmp(header, "HTTP/1.", 7) &&
((header[7] == '0') || (header[7] == '1')) &&
(header[8] == ' ') &&
ISDIGIT(header[9]) && ISDIGIT(header[10]) && ISDIGIT(header[11]) &&
!ISDIGIT(header[12])) {
/* store the HTTP code from the proxy */
data->info.httpproxycode = k->httpcode = ((header[9] - '0') * 100) +
((header[10] - '0') * 10) + (header[11] - '0');
CURL_TRC_CF(data, cf, "CONNECT%s HTTP status %d",
h1_proxy_is_udp(cf) ? "-UDP" : "", k->httpcode);
return CURLE_OK;
}
failf(data, "Invalid response header");
return CURLE_WEIRD_SERVER_REPLY;
}
static CURLcode on_resp_header(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct h1_tunnel_state *ts,
const char *header)
{
CURLcode result = CURLE_OK;
struct SingleRequest *k = &data->req;
bool is_udp = h1_proxy_is_udp(cf);
if(checkprefix("Proxy-authenticate:", header) && (407 == k->httpcode)) {
bool proxy = (k->httpcode == 407);
char *auth = Curl_copy_header_value(header);
if(!auth)
return CURLE_OUT_OF_MEMORY;
CURL_TRC_CF(data, cf, "CONNECT%s: fwd auth header '%s'",
is_udp ? "-UDP" : "", header);
result = Curl_http_input_auth(data, proxy, auth);
curlx_free(auth);
if(result)
return result;
}
else if(checkprefix("Content-Length:", header)) {
if(k->httpcode < 300) {
if(k->httpcode < 200) {
/* Informational 1xx responses cannot carry a body. RFC 9110 15.2 */
failf(data, "Invalid Content-Length: in %03d response", k->httpcode);
return CURLE_WEIRD_SERVER_REPLY;
}
/* A client MUST ignore any Content-Length or Transfer-Encoding
header fields received in a successful response to CONNECT.
"Successful" described as: 2xx (Successful). RFC 7231 4.3.6 */
infof(data, "Ignoring Content-Length in CONNECT%s %03d response",
is_udp ? "-UDP" : "", k->httpcode);
}
else {
const char *p = header + CURL_CSTRLEN("Content-Length:");
if(curlx_str_numblanks(&p, &ts->cl)) {
failf(data, "Unsupported Content-Length value");
return CURLE_WEIRD_SERVER_REPLY;
}
}
}
else if(Curl_compareheader(header,
STRCONST("Connection:"), STRCONST("close"))) {
CURL_TRC_CF(data, cf, "CONNECT%s Connection: close", is_udp ? "-UDP" : "");
ts->close_connection = TRUE;
}
else if(checkprefix("Transfer-Encoding:", header)) {
if(k->httpcode < 300) {
if(k->httpcode < 200) {
/* Informational 1xx responses cannot carry a body. RFC 9110 15.2 */
failf(data, "Invalid Transfer-Encoding: in %03d response",
k->httpcode);
return CURLE_WEIRD_SERVER_REPLY;
}
/* A client MUST ignore any Content-Length or Transfer-Encoding
header fields received in a successful response to CONNECT.
"Successful" described as: 2xx (Successful). RFC 7231 4.3.6 */
infof(data, "Ignoring Transfer-Encoding in "
"CONNECT%s %03d response", is_udp ? "-UDP" : "", k->httpcode);
}
else if(Curl_compareheader(header,
STRCONST("Transfer-Encoding:"),
STRCONST("chunked"))) {
CURL_TRC_CF(data, cf, "CONNECT%s response chunked",
is_udp ? "-UDP" : "");
ts->chunked_encoding = TRUE;
Curl_httpchunk_reset(data, &ts->ch, TRUE);
}
}
else if(is_udp && checkprefix("Capsule-protocol:", header)) {
if(Curl_compareheader(header,
STRCONST("Capsule-protocol:"),
STRCONST("?1"))) {
CURL_TRC_CF(data, cf, "CONNECT-UDP Response --> Capsule-protocol: ?1");
}
}
else if(Curl_compareheader(header,
STRCONST("Proxy-Connection:"),
STRCONST("close"))) {
CURL_TRC_CF(data, cf, "CONNECT%s Proxy-Connection: close",
is_udp ? "-UDP" : "");
ts->close_connection = TRUE;
}
return result;
}
static CURLcode single_header(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct h1_tunnel_state *ts)
{
CURLcode result = CURLE_OK;
const char *linep = curlx_dyn_ptr(&ts->rcvbuf);
size_t line_len = curlx_dyn_len(&ts->rcvbuf); /* bytes in this line */
const struct SingleRequest *k = &data->req;
int writetype;
ts->headerlines++;
/* output debug if that is requested */
Curl_debug(data, CURLINFO_HEADER_IN, linep, line_len);
/* a CONNECT response line is handed to the client as a header, so it must
pass the same checks as a regular response header before delivery */
result = Curl_verify_header(data, linep, line_len);
if(result)
return result;
/* send the header to the callback */
writetype = CLIENTWRITE_HEADER | CLIENTWRITE_CONNECT |
(ts->headerlines == 1 ? CLIENTWRITE_STATUS : 0);
result = Curl_client_write(data, writetype, linep, line_len);
if(result)
return result;
result = Curl_bump_headersize(data, line_len, TRUE);
if(result)
return result;
/* Newlines are CRLF, so the CR is ignored as the line is not
really terminated until the LF comes. Treat a following CR
as end-of-headers as well.*/
if(ISNEWLINE(linep[0])) {
/* end of response-headers from the proxy */
if(ts->headerlines == 1) {
ts->keepon = KEEPON_DONE;
result = CURLE_WEIRD_SERVER_REPLY;
}
else if((407 == k->httpcode) && !data->state.authproblem) {
/* If we get a 407 response code with content length
when we have no auth problem, we must ignore the
whole response-body */
ts->keepon = KEEPON_IGNORE;
if(ts->cl) {
infof(data, "Ignore %" FMT_OFF_T " bytes of response-body", ts->cl);
}
else if(ts->chunked_encoding) {
infof(data, "Ignore chunked response-body");
}
else {
/* without content-length or chunked encoding, we
cannot keep the connection alive since the close is
the end signal so we bail out at once instead */
CURL_TRC_CF(data, cf, "CONNECT: no content-length or chunked");
ts->keepon = KEEPON_DONE;
}
}
else {
ts->keepon = KEEPON_DONE;
}
DEBUGASSERT(ts->keepon == KEEPON_IGNORE ||
ts->keepon == KEEPON_DONE);
return result;
}
if(ts->headerlines == 1)
result = on_resp_status(cf, data, ts, linep);
else
result = on_resp_header(cf, data, ts, linep);
if(result)
return result;
curlx_dyn_reset(&ts->rcvbuf);
return result;
}
static CURLcode recv_CONNECT_resp(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct h1_tunnel_state *ts,
bool *done)
{
CURLcode result = CURLE_OK;
int error;
#define SELECT_OK 0
#define SELECT_ERROR 1
error = SELECT_OK;
*done = FALSE;
while(ts->keepon) {
size_t nread;
char byte;
/* Read one byte at a time to avoid a race condition. Wait at most one
second before looping to ensure continuous pgrsUpdates. */
result = Curl_conn_recv(data, cf->sockindex, &byte, 1, &nread);
if(result == CURLE_AGAIN)
/* socket buffer drained, return */
return CURLE_OK;
if(!result)
result = Curl_pgrsUpdate(data);
if(result) {
ts->keepon = KEEPON_DONE;
break;
}
if(!nread) {
if(ts->maybe_folded) {
/* EOF right after LF: finalize the pending header line. */
result = single_header(cf, data, ts);
if(result)
return result;
ts->maybe_folded = FALSE;
}
if(data->set.proxyauth && data->state.authproxy.avail &&
data->req.hd_proxy_auth) {
/* proxy auth was requested and there was proxy auth available,
then deem this as "mere" proxy disconnect */
ts->close_connection = TRUE;
infof(data, "Proxy CONNECT connection closed");
}
else {
error = SELECT_ERROR;
failf(data, "Proxy CONNECT aborted");
}
ts->keepon = KEEPON_DONE;
break;
}
if(ts->keepon == KEEPON_IGNORE) {
/* This means we are currently ignoring a response-body */
if(ts->chunked_encoding) {
/* chunked-encoded body, so we need to do the chunked dance
properly to know when the end of the body is reached */
size_t consumed = 0;
/* now parse the chunked piece of data so that we can
properly tell when the stream ends */
result = Curl_httpchunk_read(data, &ts->ch, &byte, 1, &consumed);
if(result)
return result;
if(Curl_httpchunk_is_done(data, &ts->ch)) {
/* we are done reading chunks! */
infof(data, "chunk reading DONE");
ts->keepon = KEEPON_DONE;
}
}
else if(ts->cl) {
/* A Content-Length based body: count down the counter
and make sure to break out of the loop when we are done! */
ts->cl--;
if(ts->cl <= 0) {
ts->keepon = KEEPON_DONE;
break;
}
}
continue;
}
if(ts->maybe_folded) {
if(ISBLANK(byte)) {
Curl_http_to_fold(&ts->rcvbuf);
ts->leading_unfold = TRUE;
}
else {
result = single_header(cf, data, ts);
if(result)
return result;
/* now handle the new byte */
}
ts->maybe_folded = FALSE;
}
if(ts->leading_unfold) {
if(ISBLANK(byte))
/* skip a bit brother */
continue;
/* non-blank, insert a space then continue the unfolding */
if(curlx_dyn_addn(&ts->rcvbuf, " ", 1)) {
failf(data, "CONNECT response too large");
return CURLE_RECV_ERROR;
}
ts->leading_unfold = FALSE;
}
if(curlx_dyn_addn(&ts->rcvbuf, &byte, 1)) {
failf(data, "CONNECT response too large");
return CURLE_RECV_ERROR;
}
/* if this is not the end of a header line then continue */
if(byte != 0x0a)
continue;
else {
const char *linep = curlx_dyn_ptr(&ts->rcvbuf);
size_t hlen = curlx_dyn_len(&ts->rcvbuf);
if(hlen && ISNEWLINE(linep[0])) {
/* end of headers */
result = single_header(cf, data, ts);
if(result)
return result;
}
else
ts->maybe_folded = TRUE;
}
if(result)
return result;
} /* while there is buffer left and loop is requested */
if(error)
result = CURLE_RECV_ERROR;
*done = (ts->keepon == KEEPON_DONE);
if(!result && *done &&
data->info.httpproxycode / 100 != 2 &&
!(h1_proxy_is_udp(cf) && data->info.httpproxycode == 101)) {
/* Deal with the possibly already received authenticate
headers. 'newurl' is set to a new URL if we must loop. */
result = Curl_http_auth_act(data);
}
return result;
}
static CURLcode H1_CONNECT(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct h1_tunnel_state *ts)
{
struct connectdata *conn = cf->conn;
CURLcode result;
bool done;
if(tunnel_is_established(ts))
return CURLE_OK;
if(tunnel_is_failed(ts))
return CURLE_RECV_ERROR; /* Need a cfilter close and new bootstrap */
do {
if(Curl_timeleft_ms(data) < 0) {
failf(data, "Proxy CONNECT aborted due to timeout");
result = CURLE_OPERATION_TIMEDOUT;
goto out;
}
switch(ts->tunnel_state) {
case H1_TUNNEL_INIT:
/* Prepare the CONNECT request and make a first attempt to send. */
CURL_TRC_CF(data, cf, "CONNECT start");
result = start_CONNECT(cf, data, ts);
if(result)
goto out;
h1_tunnel_go_state(cf, ts, H1_TUNNEL_CONNECT, data);
FALLTHROUGH();
case H1_TUNNEL_CONNECT:
/* see that the request is completely sent */
CURL_TRC_CF(data, cf, "CONNECT send");
result = send_CONNECT(cf, data, ts, &done);
if(result || !done)
goto out;
h1_tunnel_go_state(cf, ts, H1_TUNNEL_RECEIVE, data);
FALLTHROUGH();
case H1_TUNNEL_RECEIVE:
/* read what is there */
CURL_TRC_CF(data, cf, "CONNECT receive");
result = recv_CONNECT_resp(cf, data, ts, &done);
if(result)
CURL_TRC_CF(data, cf, "error receiving CONNECT response: %d",
(int)result);
if(!result)
result = Curl_pgrsUpdate(data);
/* error or not complete yet. return for more multi-multi */
if(result || !done)
goto out;
/* got it */
h1_tunnel_go_state(cf, ts, H1_TUNNEL_RESPONSE, data);
FALLTHROUGH();
case H1_TUNNEL_RESPONSE:
CURL_TRC_CF(data, cf, "CONNECT response");
if(data->req.newurl) {
/* not the "final" response, we need to do a follow up request.
* If the other side indicated a connection close, or if someone
* else told us to close this connection, do so now.
*/
Curl_req_soft_reset(&data->req, data);
if(ts->close_connection || conn->bits.close) {
/* Close this filter and the sub-chain, re-connect the
* sub-chain and continue. Closing this filter will
* reset our tunnel state. To avoid recursion, we return
* and expect to be called again.
*/
CURL_TRC_CF(data, cf, "CONNECT need to close+open");
infof(data, "Connect me again please");
return CURLE_AGAIN;
}
else {
/* staying on this connection, reset state */
h1_tunnel_go_state(cf, ts, H1_TUNNEL_INIT, data);
}
}
break;
default:
break;
}
} while(data->req.newurl);
DEBUGASSERT(ts->tunnel_state == H1_TUNNEL_RESPONSE);
if(h1_proxy_is_udp(cf)) {
/* RFC 9298: Accept 101 Upgrade for HTTP/1.1 and
* 2xx responses for HTTP/2 and HTTP/3 proxies. */
if(data->info.httpproxycode / 100 != 2 &&
data->info.httpproxycode != 101) {
curlx_safefree(data->req.newurl);
h1_tunnel_go_state(cf, ts, H1_TUNNEL_FAILED, data);
failf(data, "CONNECT-UDP tunnel failed, response %d",
data->req.httpcode);
return CURLE_COULDNT_CONNECT;
}
}
else {
if(data->info.httpproxycode / 100 != 2) {
/* a non-2xx response and we have no next URL to try. */
curlx_safefree(data->req.newurl);
h1_tunnel_go_state(cf, ts, H1_TUNNEL_FAILED, data);
failf(data, "CONNECT tunnel failed, response %d", data->req.httpcode);
return CURLE_COULDNT_CONNECT;
}
}
/* 2xx response, SUCCESS! */
/* 101 Switching Protocol for CONNECT-UDP */
h1_tunnel_go_state(cf, ts, H1_TUNNEL_ESTABLISHED, data);
infof(data, "CONNECT%s tunnel established, response %d",
h1_proxy_is_udp(cf) ? "-UDP" : "", data->info.httpproxycode);
result = CURLE_OK;
out:
if(result)
h1_tunnel_go_state(cf, ts, H1_TUNNEL_FAILED, data);
return result;
}
static CURLcode cf_h1_proxy_connect(struct Curl_cfilter *cf,
struct Curl_easy *data,
bool *done)
{
CURLcode result;
struct cf_h1_proxy_ctx *pctx = cf->ctx;
struct h1_tunnel_state *ts = pctx->ts;
if(cf->connected) {
*done = TRUE;
return CURLE_OK;
}
CURL_TRC_CF(data, cf, "connect");
result = cf->next->cft->do_connect(cf->next, data, done);
if(result || !*done)
return result;
*done = FALSE;
if(!ts) {
result = tunnel_init(cf, data, &ts);
if(result)
return result;
pctx->ts = ts;
}
/* We want "seamless" operations through HTTP proxy tunnel */
result = H1_CONNECT(cf, data, ts);
if(result)
goto out;
curlx_safefree(data->req.hd_proxy_auth);
out:
*done = (result == CURLE_OK) && tunnel_is_established(pctx->ts);
if(*done) {
cf->connected = TRUE;
/* The real request will follow the CONNECT, reset request partially */
Curl_req_soft_reset(&data->req, data);
Curl_client_reset(data);
Curl_pgrsReset(data);
cf_tunnel_free(cf, data);
}
return result;
}
static CURLcode cf_h1_proxy_adjust_pollset(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct easy_pollset *ps)
{
struct cf_h1_proxy_ctx *pctx = cf->ctx;
struct h1_tunnel_state *ts = pctx->ts;
CURLcode result = CURLE_OK;
if(!cf->connected) {
/* If we are not connected, but the filter "below" is
* and not waiting on something, we are tunneling. */
curl_socket_t sock = Curl_conn_cf_get_socket(cf, data);
if(ts) {
/* when we have sent a CONNECT to a proxy, we should rather either
wait for the socket to become readable to be able to get the
response headers or if we are still sending the request, wait
for write. */
if(tunnel_want_send(ts))
result = Curl_pollset_set_out_only(data, ps, sock);
else
result = Curl_pollset_set_in_only(data, ps, sock);
}
else
result = Curl_pollset_set_out_only(data, ps, sock);
}
else {
if(cf->next)
result = cf->next->cft->adjust_pollset(cf->next, data, ps);
}
return result;
}
static bool cf_h1_proxy_data_pending(struct Curl_cfilter *cf,
const struct Curl_easy *data)
{
return cf->next ? cf->next->cft->has_data_pending(cf->next, data) : FALSE;
}
static void cf_h1_proxy_destroy(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
struct cf_h1_proxy_ctx *pctx = cf->ctx;
CURL_TRC_CF(data, cf, "destroy");
if(pctx) {
cf_tunnel_free(cf, data);
Curl_peer_unlink(&pctx->peer);
curlx_safefree(cf->ctx);
}
}
static CURLcode cf_h1_proxy_query(struct Curl_cfilter *cf,
struct Curl_easy *data,
int query, int *pres1, void *pres2)
{
struct cf_h1_proxy_ctx *pctx = cf->ctx;
struct h1_tunnel_state *ts = pctx ? pctx->ts : NULL;
switch(query) {
case CF_QUERY_HOST_PORT:
if(!ts || !ts->dest)
break;
*pres1 = (int)ts->dest->port;
*((const char **)pres2) = ts->dest->hostname;
return CURLE_OK;
case CF_QUERY_ALPN_NEGOTIATED: {
const char **palpn = pres2;
DEBUGASSERT(palpn);
*palpn = NULL;
return CURLE_OK;
}
default:
break;
}
return cf->next ?
cf->next->cft->query(cf->next, data, query, pres1, pres2) :
CURLE_UNKNOWN_OPTION;
}
struct Curl_cftype Curl_cft_h1_proxy = {
"H1-PROXY",
CF_TYPE_IP_CONNECT | CF_TYPE_PROXY,
0,
cf_h1_proxy_destroy,
cf_h1_proxy_connect,
Curl_cf_def_shutdown,
cf_h1_proxy_adjust_pollset,
cf_h1_proxy_data_pending,
Curl_cf_def_send,
Curl_cf_def_recv,
Curl_cf_def_cntrl,
Curl_cf_def_conn_is_alive,
Curl_cf_def_conn_keep_alive,
cf_h1_proxy_query,
};
CURLcode Curl_cf_h1_proxy_insert_after(struct Curl_cfilter *cf_at,
struct Curl_easy *data,
struct Curl_peer *peer,
struct Curl_peer *dest,
int httpversion,
bool udp_tunnel)
{
struct Curl_cfilter *cf;
struct cf_h1_proxy_ctx *pctx;
struct h1_tunnel_state *ts;
CURLcode result;
(void)data;
if(!dest)
return CURLE_FAILED_INIT;
if((httpversion < 10) || (httpversion >= 20))
return CURLE_FAILED_INIT;
ts = curlx_calloc(1, sizeof(*ts));
if(!ts) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
Curl_peer_link(&ts->dest, dest);
ts->udp_tunnel = udp_tunnel;
ts->httpversion = httpversion;
curlx_dyn_init(&ts->rcvbuf, DYN_PROXY_CONNECT_HEADERS);
curlx_dyn_init(&ts->request_data, DYN_HTTP_REQUEST);
Curl_httpchunk_init(data, &ts->ch, TRUE, TRUE);
pctx = curlx_calloc(1, sizeof(*pctx));
if(!pctx) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
Curl_peer_link(&pctx->peer, peer);
pctx->ts = ts;
result = Curl_cf_create(&cf, &Curl_cft_h1_proxy, pctx);
if(result) {
Curl_peer_unlink(&pctx->peer);
curlx_free(pctx);
goto out;
}
ts = NULL;
Curl_conn_cf_insert_after(cf_at, cf);
out:
tunnel_free(ts, data);
return result;
}
#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */
+43
View File
@@ -0,0 +1,43 @@
#ifndef HEADER_CURL_H1_PROXY_H
#define HEADER_CURL_H1_PROXY_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
struct Curl_peer;
CURLcode Curl_cf_h1_proxy_insert_after(struct Curl_cfilter *cf_at,
struct Curl_easy *data,
struct Curl_peer *peer,
struct Curl_peer *dest,
int httpversion,
bool udp_tunnel);
extern struct Curl_cftype Curl_cft_h1_proxy;
#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */
#endif /* HEADER_CURL_H1_PROXY_H */
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
#ifndef HEADER_CURL_H2_PROXY_H
#define HEADER_CURL_H2_PROXY_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#if defined(USE_NGHTTP2) && !defined(CURL_DISABLE_PROXY)
CURLcode Curl_cf_h2_proxy_insert_after(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct Curl_peer *peer,
struct Curl_peer *dest,
bool udp_tunnel);
extern struct Curl_cftype Curl_cft_h2_proxy;
#endif /* USE_NGHTTP2 && !CURL_DISABLE_PROXY */
#endif /* HEADER_CURL_H2_PROXY_H */
+241
View File
@@ -0,0 +1,241 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_PROXY
#include "urldata.h"
#include "cfilters.h"
#include "cf-haproxy.h"
#include "connect.h"
#include "curl_addrinfo.h"
#include "curl_trc.h"
#include "select.h"
typedef enum {
HAPROXY_INIT, /* init/default/no tunnel state */
HAPROXY_SEND, /* data_out being sent */
HAPROXY_DONE /* all work done */
} haproxy_state;
struct cf_haproxy_ctx {
int state;
struct dynbuf data_out;
};
static void cf_haproxy_ctx_free(struct cf_haproxy_ctx *ctx)
{
if(ctx) {
curlx_dyn_free(&ctx->data_out);
curlx_free(ctx);
}
}
static CURLcode cf_haproxy_date_out_set(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
/* We fake a client connection report to the upstream server
* with the HAProxy protocol, reporting the client's source
* and destination IP addresses and ports.
* addresses: either the ones used to talk to the upstream
* OR the value supplied by the user
* ports: the ports used in the upstream connection */
const char *client_source_ip;
const char *client_dest_ip;
struct cf_haproxy_ctx *ctx = cf->ctx;
CURLcode result;
struct ip_quadruple ipquad;
bool is_ipv6;
DEBUGASSERT(ctx);
DEBUGASSERT(ctx->state == HAPROXY_INIT);
#ifdef USE_UNIX_SOCKETS
if(Curl_conn_get_first_peer(cf->conn, cf->sockindex)->unix_socket)
/* the buffer is large enough to hold this! */
result = curlx_dyn_addn(&ctx->data_out, STRCONST("PROXY UNKNOWN\r\n"));
else {
#endif /* USE_UNIX_SOCKETS */
result = Curl_conn_cf_get_ip_info(cf->next, data, &is_ipv6, &ipquad);
if(result)
return result;
client_source_ip = CURL_EASY_STR(data, STRING_HAPROXY_CLIENT_IP);
if(client_source_ip) {
client_dest_ip = client_source_ip;
is_ipv6 = !Curl_is_ipv4addr(client_source_ip);
}
else {
client_source_ip = ipquad.local_ip;
client_dest_ip = ipquad.remote_ip;
}
result = curlx_dyn_addf(&ctx->data_out, "PROXY %s %s %s %d %d\r\n",
is_ipv6 ? "TCP6" : "TCP4",
client_source_ip, client_dest_ip,
ipquad.local_port, ipquad.remote_port);
#ifdef USE_UNIX_SOCKETS
}
#endif /* USE_UNIX_SOCKETS */
return result;
}
static CURLcode cf_haproxy_connect(struct Curl_cfilter *cf,
struct Curl_easy *data,
bool *done)
{
struct cf_haproxy_ctx *ctx = cf->ctx;
CURLcode result;
size_t len;
DEBUGASSERT(ctx);
if(cf->connected) {
*done = TRUE;
return CURLE_OK;
}
result = cf->next->cft->do_connect(cf->next, data, done);
if(result || !*done)
return result;
switch(ctx->state) {
case HAPROXY_INIT:
result = cf_haproxy_date_out_set(cf, data);
if(result)
goto out;
ctx->state = HAPROXY_SEND;
FALLTHROUGH();
case HAPROXY_SEND:
len = curlx_dyn_len(&ctx->data_out);
if(len > 0) {
size_t nwritten;
result = Curl_conn_cf_send(cf->next, data,
curlx_dyn_uptr(&ctx->data_out), len, FALSE,
&nwritten);
if(result) {
if(result != CURLE_AGAIN)
goto out;
result = CURLE_OK;
nwritten = 0;
}
curlx_dyn_tail(&ctx->data_out, len - nwritten);
if(curlx_dyn_len(&ctx->data_out) > 0) {
result = CURLE_OK;
goto out;
}
}
ctx->state = HAPROXY_DONE;
FALLTHROUGH();
default:
curlx_dyn_free(&ctx->data_out);
break;
}
out:
*done = (!result) && (ctx->state == HAPROXY_DONE);
cf->connected = *done;
return result;
}
static void cf_haproxy_destroy(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
CURL_TRC_CF(data, cf, "destroy");
cf_haproxy_ctx_free(cf->ctx);
}
static CURLcode cf_haproxy_adjust_pollset(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct easy_pollset *ps)
{
if(cf->next->connected && !cf->connected) {
/* If we are not connected, but the filter "below" is
* and not waiting on something, we are sending. */
return Curl_pollset_set_out_only(
data, ps, Curl_conn_cf_get_socket(cf, data));
}
return CURLE_OK;
}
struct Curl_cftype Curl_cft_haproxy = {
"HAPROXY",
CF_TYPE_PROXY | CF_TYPE_SETUP,
0,
cf_haproxy_destroy,
cf_haproxy_connect,
Curl_cf_def_shutdown,
cf_haproxy_adjust_pollset,
Curl_cf_def_data_pending,
Curl_cf_def_send,
Curl_cf_def_recv,
Curl_cf_def_cntrl,
Curl_cf_def_conn_is_alive,
Curl_cf_def_conn_keep_alive,
Curl_cf_def_query,
};
static CURLcode cf_haproxy_create(struct Curl_cfilter **pcf,
struct Curl_easy *data)
{
struct Curl_cfilter *cf = NULL;
struct cf_haproxy_ctx *ctx;
CURLcode result;
(void)data;
ctx = curlx_calloc(1, sizeof(*ctx));
if(!ctx) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
ctx->state = HAPROXY_INIT;
curlx_dyn_init(&ctx->data_out, DYN_HAXPROXY);
result = Curl_cf_create(&cf, &Curl_cft_haproxy, ctx);
if(result)
goto out;
ctx = NULL;
out:
cf_haproxy_ctx_free(ctx);
*pcf = result ? NULL : cf;
return result;
}
CURLcode Curl_cf_haproxy_insert_after(struct Curl_cfilter *cf_at,
struct Curl_easy *data)
{
struct Curl_cfilter *cf;
CURLcode result;
result = cf_haproxy_create(&cf, data);
if(result)
goto out;
Curl_conn_cf_insert_after(cf_at, cf);
out:
return result;
}
#endif /* !CURL_DISABLE_PROXY */
+39
View File
@@ -0,0 +1,39 @@
#ifndef HEADER_CURL_CF_HAPROXY_H
#define HEADER_CURL_CF_HAPROXY_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include "urldata.h"
#ifndef CURL_DISABLE_PROXY
CURLcode Curl_cf_haproxy_insert_after(struct Curl_cfilter *cf_at,
struct Curl_easy *data);
extern struct Curl_cftype Curl_cft_haproxy;
#endif /* !CURL_DISABLE_PROXY */
#endif /* HEADER_CURL_CF_HAPROXY_H */
+825
View File
@@ -0,0 +1,825 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_HTTP
#include "urldata.h"
#include "curl_trc.h"
#include "cfilters.h"
#include "cf-setup.h"
#include "connect.h"
#include "multiif.h"
#include "cf-https-connect.h"
#include "http2.h"
#include "progress.h"
#include "select.h"
#include "vdns/cf-dns.h"
#include "vdns/hostip.h"
#include "vdns/httpsrr.h"
#include "vquic/vquic.h"
typedef enum {
CF_HC_RESOLV,
CF_HC_INIT,
CF_HC_CONNECT,
CF_HC_SUCCESS,
CF_HC_FAILURE
} cf_hc_state;
struct cf_hc_baller {
const char *name;
struct Curl_cfilter *cf;
CURLcode result;
int reply_ms;
uint8_t transport;
enum alpnid alpn_id;
BIT(shutdown);
};
static void cf_hc_baller_discard(struct cf_hc_baller *b,
struct Curl_easy *data)
{
if(b->cf) {
Curl_conn_cf_discard_chain(&b->cf, data);
b->cf = NULL;
}
}
static bool cf_hc_baller_is_connecting(struct cf_hc_baller *b)
{
return b->cf && !b->result;
}
static bool cf_hc_baller_has_started(struct cf_hc_baller *b)
{
return !!b->cf;
}
static int cf_hc_baller_reply_ms(struct cf_hc_baller *b,
struct Curl_easy *data)
{
if(b->cf && (b->reply_ms < 0))
b->cf->cft->query(b->cf, data, CF_QUERY_CONNECT_REPLY_MS,
&b->reply_ms, NULL);
return b->reply_ms;
}
static bool cf_hc_baller_data_pending(struct cf_hc_baller *b,
const struct Curl_easy *data)
{
return b->cf && !b->result && b->cf->cft->has_data_pending(b->cf, data);
}
static bool cf_hc_baller_needs_flush(struct cf_hc_baller *b,
struct Curl_easy *data)
{
return b->cf && !b->result && Curl_conn_cf_needs_flush(b->cf, data);
}
static CURLcode cf_hc_baller_cntrl(struct cf_hc_baller *b,
struct Curl_easy *data,
int event, int arg1, void *arg2)
{
if(b->cf && !b->result)
return Curl_conn_cf_cntrl(b->cf, data, FALSE, event, arg1, arg2);
return CURLE_OK;
}
struct cf_hc_ctx {
cf_hc_state state;
struct Curl_peer *destination; /* who we ultimately want to talk to */
struct curltime started; /* when connect started */
CURLcode result; /* overall result */
CURLcode check_h3_result;
struct cf_hc_baller ballers[2];
size_t baller_count;
timediff_t soft_eyeballs_timeout_ms;
timediff_t hard_eyeballs_timeout_ms;
uint8_t def_transport;
BIT(httpsrr_resolved);
BIT(checked_h3);
BIT(ballers_complete);
};
static void cf_hc_ctx_destroy(struct Curl_easy *data,
struct cf_hc_ctx *ctx)
{
if(ctx) {
size_t i;
for(i = 0; i < ctx->baller_count; ++i)
cf_hc_baller_discard(&ctx->ballers[i], data);
Curl_peer_unlink(&ctx->destination);
curlx_free(ctx);
}
}
static void cf_hc_baller_assign(struct cf_hc_baller *b,
enum alpnid alpn_id,
uint8_t def_transport)
{
b->alpn_id = alpn_id;
b->transport = def_transport;
b->cf = NULL;
b->result = CURLE_OK;
b->reply_ms = -1;
b->shutdown = FALSE;
switch(b->alpn_id) {
case ALPN_h3:
b->name = "h3";
b->transport = TRNSPRT_QUIC;
break;
case ALPN_h2:
b->name = "h2";
break;
case ALPN_h1:
b->name = "h1";
break;
case ALPN_none:
b->name = "no-alpn";
break;
default:
b->result = CURLE_FAILED_INIT;
break;
}
}
static void cf_hc_baller_init(struct cf_hc_baller *b,
struct Curl_cfilter *cf,
struct Curl_easy *data)
{
struct Curl_cfilter *save = cf->next;
cf->next = NULL;
b->result = Curl_cf_setup_insert_after(cf, data, b->transport,
CURL_CF_SSL_ENABLE);
b->cf = cf->next;
cf->next = save;
}
static CURLcode cf_hc_baller_connect(struct cf_hc_baller *b,
struct Curl_cfilter *cf,
struct Curl_easy *data,
bool *done)
{
struct Curl_cfilter *save = cf->next;
cf->next = b->cf;
b->result = Curl_conn_cf_connect(cf->next, data, done);
b->cf = cf->next; /* it might mutate */
cf->next = save;
return b->result;
}
static CURLcode baller_connected(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct cf_hc_baller *winner)
{
struct cf_hc_ctx *ctx = cf->ctx;
/* Make the winner's connection filter out own sub-filter, check, move,
* close all remaining. */
if(cf->next) {
DEBUGASSERT(0);
return CURLE_FAILED_INIT;
}
if(!winner->cf) {
DEBUGASSERT(0);
return CURLE_FAILED_INIT;
}
cf->next = winner->cf;
winner->cf = NULL;
ctx->state = CF_HC_SUCCESS;
cf->connected = TRUE;
/* ballers may have failf()'d, the winner resets it, so our
* errorbuf is clean again. */
Curl_reset_fail(data);
#ifdef USE_NGHTTP2
{
/* For a negotiated HTTP/2 connection insert the h2 filter. */
const char *alpn = Curl_conn_cf_get_alpn_negotiated(cf->next, data);
if(alpn && !strcmp("h2", alpn)) {
CURLcode result = Curl_http2_switch_at(cf, data);
if(result) {
ctx->state = CF_HC_FAILURE;
ctx->result = result;
return result;
}
}
}
#endif
return CURLE_OK;
}
static bool time_to_start_baller2(struct Curl_cfilter *cf,
struct Curl_easy *data,
const struct curltime *pnow)
{
struct cf_hc_ctx *ctx = cf->ctx;
timediff_t elapsed_ms;
if(ctx->baller_count < 2)
return FALSE;
else if(cf_hc_baller_has_started(&ctx->ballers[1]))
return FALSE;
else if(ctx->ballers[0].result) {
CURL_TRC_CF(data, cf, "%s baller failed, starting %s",
ctx->ballers[0].name, ctx->ballers[1].name);
return TRUE;
}
elapsed_ms = curlx_ptimediff_ms(pnow, &ctx->started);
if(elapsed_ms >= ctx->hard_eyeballs_timeout_ms) {
CURL_TRC_CF(data, cf, "%s inconclusive after %" FMT_TIMEDIFF_T ", "
"starting %s", ctx->ballers[0].name,
ctx->hard_eyeballs_timeout_ms, ctx->ballers[1].name);
return TRUE;
}
else if(elapsed_ms >= ctx->soft_eyeballs_timeout_ms) {
if(cf_hc_baller_reply_ms(&ctx->ballers[0], data) < 0) {
CURL_TRC_CF(data, cf, "%s has not seen any data after %"
FMT_TIMEDIFF_T "ms, starting %s",
ctx->ballers[0].name, ctx->soft_eyeballs_timeout_ms,
ctx->ballers[1].name);
return TRUE;
}
/* set the effective hard timeout again */
Curl_expire_set(data, EXPIRE_ALPN_EYEBALLS,
ctx->hard_eyeballs_timeout_ms - elapsed_ms, pnow);
}
return FALSE;
}
static bool cf_hc_may_h3(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
struct cf_hc_ctx *ctx = cf->ctx;
if(!ctx->checked_h3) {
ctx->check_h3_result =
Curl_conn_may_http3(data, cf->conn);
ctx->checked_h3 = TRUE;
}
return !ctx->check_h3_result;
}
static enum alpnid cf_hc_get_httpsrr_alpn(struct Curl_cfilter *cf,
struct Curl_easy *data,
enum alpnid not_this_one)
{
#ifdef USE_HTTPSRR
struct cf_hc_ctx *ctx = cf->ctx;
/* Is there an HTTPSRR use its ALPNs here.
* We are here after having selected a connection to a host+port and
* can no longer change that. Any HTTPSRR advice for other hosts and ports
* we need to ignore. */
const struct Curl_https_rrinfo *rr;
size_t i;
/* Do we have HTTPS-RR information? */
rr = Curl_conn_dns_get_https(data, cf->sockindex, ctx->destination);
CURL_TRC_CF(data, cf, "HTTPS-RR %savailable", rr ? "" : "not ");
/* We do not support `rr->no_def_alpn`. */
if(Curl_httpsrr_applicable(data, rr) && !rr->no_def_alpn) {
for(i = 0; i < CURL_ARRAYSIZE(rr->alpns); ++i) {
enum alpnid alpn_rr = (enum alpnid)rr->alpns[i];
if(alpn_rr == not_this_one) /* do not want this one */
continue;
switch(alpn_rr) {
case ALPN_h3:
if((data->state.http_neg.allowed & CURL_HTTP_V3x) &&
cf_hc_may_h3(cf, data)) {
return alpn_rr;
}
break;
case ALPN_h2:
if(data->state.http_neg.allowed & CURL_HTTP_V2x) {
return alpn_rr;
}
break;
case ALPN_h1:
if(data->state.http_neg.allowed & CURL_HTTP_V1x) {
return alpn_rr;
}
break;
default: /* ignore */
break;
}
}
}
#else
(void)cf;
(void)data;
(void)not_this_one;
#endif
return ALPN_none;
}
static enum alpnid cf_hc_get_pref_alpn(struct Curl_cfilter *cf,
struct Curl_easy *data,
enum alpnid not_this_one)
{
if((data->state.http_neg.preferred & data->state.http_neg.allowed)) {
switch(data->state.http_neg.preferred) {
case CURL_HTTP_V3x:
if(cf_hc_may_h3(cf, data) && (ALPN_h3 != not_this_one))
return ALPN_h3;
break;
case CURL_HTTP_V2x:
if(ALPN_h2 != not_this_one)
return ALPN_h2;
break;
case CURL_HTTP_V1x:
/* If we are trying h2 already, h1 is already used as fallback */
if((ALPN_h1 != not_this_one) && (ALPN_h2 != not_this_one))
return ALPN_h1;
break;
default:
break;
}
}
return ALPN_none;
}
static enum alpnid cf_hc_get_first_alpn(struct Curl_cfilter *cf,
struct Curl_easy *data,
http_majors choices,
enum alpnid not_this_one)
{
/* When told to not try h2, we also do not try h1 and vice versa */
bool allow_h1_or_h2 = (not_this_one != ALPN_h1) &&
(not_this_one != ALPN_h2);
if((ALPN_h3 != not_this_one) && (choices & CURL_HTTP_V3x) &&
cf_hc_may_h3(cf, data)) {
return ALPN_h3;
}
if(allow_h1_or_h2 && (choices & CURL_HTTP_V2x)) {
return ALPN_h2;
}
if(allow_h1_or_h2 && (choices & CURL_HTTP_V1x)) {
return ALPN_h1;
}
return ALPN_none;
}
static CURLcode cf_hc_set_baller1(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
struct cf_hc_ctx *ctx = cf->ctx;
enum alpnid alpn1 = ALPN_none;
VERBOSE(const char *source = "HTTPS-RR");
DEBUGASSERT(cf->conn->bits.tls_enable_alpn);
alpn1 = cf_hc_get_httpsrr_alpn(cf, data, ALPN_none);
if(alpn1 == ALPN_none) {
/* preference is configured and allowed, can we use it? */
VERBOSE(source = "preferred version");
alpn1 = cf_hc_get_pref_alpn(cf, data, ALPN_none);
}
if(alpn1 == ALPN_none) {
VERBOSE(source = "wanted versions");
alpn1 = cf_hc_get_first_alpn(cf, data,
data->state.http_neg.wanted,
ALPN_none);
}
if(alpn1 == ALPN_none) {
VERBOSE(source = "allowed versions");
alpn1 = cf_hc_get_first_alpn(cf, data,
data->state.http_neg.allowed,
ALPN_none);
}
if(alpn1 == ALPN_none) {
/* None of the wanted/allowed HTTP versions could be chosen */
if(ctx->check_h3_result) {
CURL_TRC_CF(data, cf, "unable to use HTTP/3");
return ctx->check_h3_result;
}
CURL_TRC_CF(data, cf, "unable to select HTTP version");
return CURLE_FAILED_INIT;
}
cf_hc_baller_assign(&ctx->ballers[0], alpn1, ctx->def_transport);
ctx->baller_count = 1;
CURL_TRC_CF(data, cf, "1st attempt uses %s from %s",
ctx->ballers[0].name, source);
switch(alpn1) {
case ALPN_h1:
/* We really want h1, switch off h2 to make it disappear in ALPN */
data->state.http_neg.wanted &= (uint8_t)~CURL_HTTP_V2x;
break;
default:
break;
}
return CURLE_OK;
}
static void cf_hc_set_baller2(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
struct cf_hc_ctx *ctx = cf->ctx;
enum alpnid alpn2 = ALPN_none, alpn1 = ctx->ballers[0].alpn_id;
VERBOSE(const char *source = "HTTPS-RR");
if(ctx->ballers_complete)
return; /* already done */
if(!ctx->httpsrr_resolved)
return; /* HTTPS-RR pending */
alpn2 = cf_hc_get_httpsrr_alpn(cf, data, alpn1);
if(alpn2 == ALPN_none) {
/* preference is configured and allowed, can we use it? */
VERBOSE(source = "preferred version");
alpn2 = cf_hc_get_pref_alpn(cf, data, alpn1);
}
if(alpn2 == ALPN_none) {
VERBOSE(source = "wanted versions");
alpn2 = cf_hc_get_first_alpn(cf, data,
data->state.http_neg.wanted,
alpn1);
}
if(alpn2 != ALPN_none) {
cf_hc_baller_assign(&ctx->ballers[1], alpn2, ctx->def_transport);
ctx->baller_count = 2;
CURL_TRC_CF(data, cf, "2nd attempt uses %s from %s",
ctx->ballers[1].name, source);
}
ctx->ballers_complete = TRUE;
}
static CURLcode cf_hc_connect(struct Curl_cfilter *cf,
struct Curl_easy *data,
bool *done)
{
struct cf_hc_ctx *ctx = cf->ctx;
CURLcode result = CURLE_OK;
const struct curltime *pnow = NULL;
if(cf->connected) {
*done = TRUE;
return CURLE_OK;
}
*done = FALSE;
if(!ctx->httpsrr_resolved) {
ctx->httpsrr_resolved = Curl_conn_dns_resolved_https(
data, cf->sockindex, ctx->destination);
#ifdef DEBUGBUILD
if(!ctx->httpsrr_resolved && getenv("CURL_DBG_AWAIT_HTTPSRR")) {
CURL_TRC_CF(data, cf, "awaiting HTTPS-RR");
return CURLE_OK;
}
#endif
}
switch(ctx->state) {
case CF_HC_RESOLV:
ctx->state = CF_HC_INIT;
FALLTHROUGH();
case CF_HC_INIT:
DEBUGASSERT(!cf->next);
CURL_TRC_CF(data, cf, "connect, init");
result = cf_hc_set_baller1(cf, data);
if(result) {
ctx->result = result;
ctx->state = CF_HC_FAILURE;
goto out;
}
cf_hc_set_baller2(cf, data);
pnow = Curl_pgrs_now(data);
ctx->started = *pnow;
cf_hc_baller_init(&ctx->ballers[0], cf, data);
if((ctx->baller_count > 1) || !ctx->ballers_complete) {
Curl_expire_set(data, EXPIRE_ALPN_EYEBALLS,
ctx->soft_eyeballs_timeout_ms, pnow);
}
ctx->state = CF_HC_CONNECT;
FALLTHROUGH();
case CF_HC_CONNECT:
if(!ctx->ballers_complete)
cf_hc_set_baller2(cf, data);
if(cf_hc_baller_is_connecting(&ctx->ballers[0])) {
result = cf_hc_baller_connect(&ctx->ballers[0], cf, data, done);
if(!result && *done) {
result = baller_connected(cf, data, &ctx->ballers[0]);
goto out;
}
}
pnow = Curl_pgrs_now(data);
if(time_to_start_baller2(cf, data, pnow)) {
cf_hc_baller_init(&ctx->ballers[1], cf, data);
}
if(cf_hc_baller_is_connecting(&ctx->ballers[1])) {
result = cf_hc_baller_connect(&ctx->ballers[1], cf, data, done);
if(!result && *done) {
result = baller_connected(cf, data, &ctx->ballers[1]);
goto out;
}
}
if(ctx->ballers[0].result &&
(ctx->ballers[1].result ||
(ctx->ballers_complete && (ctx->baller_count < 2)))) {
/* all have failed. we give up */
CURL_TRC_CF(data, cf, "connect, all attempts failed");
ctx->result = result = ctx->ballers[0].result;
ctx->state = CF_HC_FAILURE;
goto out;
}
result = CURLE_OK;
*done = FALSE;
break;
case CF_HC_FAILURE:
result = ctx->result;
cf->connected = FALSE;
*done = FALSE;
break;
case CF_HC_SUCCESS:
result = CURLE_OK;
cf->connected = TRUE;
*done = TRUE;
break;
}
out:
CURL_TRC_CF(data, cf, "connect -> %d, done=%d", (int)result, *done);
return result;
}
static CURLcode cf_hc_shutdown(struct Curl_cfilter *cf,
struct Curl_easy *data, bool *done)
{
struct cf_hc_ctx *ctx = cf->ctx;
size_t i;
CURLcode result = CURLE_OK;
DEBUGASSERT(data);
if(cf->connected) {
*done = TRUE;
return CURLE_OK;
}
/* shutdown all ballers that have not done so already. If one fails,
* continue shutting down others until all are shutdown. */
for(i = 0; i < ctx->baller_count; i++) {
struct cf_hc_baller *b = &ctx->ballers[i];
bool bdone = FALSE;
if(!cf_hc_baller_is_connecting(b) || b->shutdown)
continue;
b->result = b->cf->cft->do_shutdown(b->cf, data, &bdone);
if(b->result || bdone)
b->shutdown = TRUE; /* treat a failed shutdown as done */
}
*done = TRUE;
for(i = 0; i < ctx->baller_count; i++) {
if(!ctx->ballers[i].shutdown)
*done = FALSE;
}
if(*done) {
for(i = 0; i < ctx->baller_count; i++) {
if(ctx->ballers[i].result)
result = ctx->ballers[i].result;
}
}
CURL_TRC_CF(data, cf, "shutdown -> %d, done=%d", (int)result, *done);
return result;
}
static CURLcode cf_hc_adjust_pollset(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct easy_pollset *ps)
{
CURLcode result = CURLE_OK;
if(!cf->connected) {
struct cf_hc_ctx *ctx = cf->ctx;
size_t i;
for(i = 0; (i < ctx->baller_count) && !result; i++) {
struct cf_hc_baller *b = &ctx->ballers[i];
if(!cf_hc_baller_is_connecting(b))
continue;
result = Curl_conn_cf_adjust_pollset(b->cf, data, ps);
}
CURL_TRC_CF(data, cf, "adjust_pollset -> %d, %u socks", (int)result,
ps->n);
}
return result;
}
static bool cf_hc_data_pending(struct Curl_cfilter *cf,
const struct Curl_easy *data)
{
struct cf_hc_ctx *ctx = cf->ctx;
size_t i;
if(cf->connected)
return cf->next->cft->has_data_pending(cf->next, data);
for(i = 0; i < ctx->baller_count; i++)
if(cf_hc_baller_data_pending(&ctx->ballers[i], data))
return TRUE;
return FALSE;
}
static CURLcode cf_hc_query(struct Curl_cfilter *cf,
struct Curl_easy *data,
int query, int *pres1, void *pres2)
{
struct cf_hc_ctx *ctx = cf->ctx;
size_t i;
if(!cf->connected) {
switch(query) {
case CF_QUERY_NEED_FLUSH: {
for(i = 0; i < ctx->baller_count; i++)
if(cf_hc_baller_needs_flush(&ctx->ballers[i], data)) {
*pres1 = TRUE;
return CURLE_OK;
}
break;
}
default:
break;
}
}
return cf->next ?
cf->next->cft->query(cf->next, data, query, pres1, pres2) :
CURLE_UNKNOWN_OPTION;
}
static CURLcode cf_hc_cntrl(struct Curl_cfilter *cf,
struct Curl_easy *data,
int event, int arg1, void *arg2)
{
struct cf_hc_ctx *ctx = cf->ctx;
CURLcode result = CURLE_OK;
size_t i;
if(!cf->connected) {
switch(event) {
case CF_CTRL_REPORT_STATS:
case CF_CTRL_CONN_INFO_UPDATE:
for(i = 0; i < ctx->baller_count; i++) {
/* Make the first baller that connected at network level report */
if(Curl_conn_cf_is_ip_connected(ctx->ballers[i].cf, data)) {
Curl_conn_cf_cntrl(ctx->ballers[i].cf, data, TRUE,
event, arg1, arg2);
break;
}
}
break;
default:
for(i = 0; i < ctx->baller_count; i++) {
result = cf_hc_baller_cntrl(&ctx->ballers[i], data, event, arg1, arg2);
if(result && (result != CURLE_AGAIN))
goto out;
}
result = CURLE_OK;
break;
}
}
out:
return result;
}
static void cf_hc_destroy(struct Curl_cfilter *cf, struct Curl_easy *data)
{
struct cf_hc_ctx *ctx = cf->ctx;
CURL_TRC_CF(data, cf, "destroy");
cf_hc_ctx_destroy(data, ctx);
}
struct Curl_cftype Curl_cft_http_connect = {
"HTTPS-CONNECT",
CF_TYPE_SETUP,
CURL_LOG_LVL_NONE,
cf_hc_destroy,
cf_hc_connect,
cf_hc_shutdown,
cf_hc_adjust_pollset,
cf_hc_data_pending,
Curl_cf_def_send,
Curl_cf_def_recv,
cf_hc_cntrl,
Curl_cf_def_conn_is_alive,
Curl_cf_def_conn_keep_alive,
cf_hc_query,
};
static CURLcode cf_hc_create(struct Curl_cfilter **pcf,
struct Curl_easy *data,
struct Curl_peer *destination,
uint8_t def_transport)
{
struct Curl_cfilter *cf = NULL;
struct cf_hc_ctx *ctx;
CURLcode result = CURLE_OK;
ctx = curlx_calloc(1, sizeof(*ctx));
if(!ctx) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
Curl_peer_link(&ctx->destination, destination);
ctx->def_transport = def_transport;
ctx->hard_eyeballs_timeout_ms = data->set.happy_eyeballs_timeout;
ctx->soft_eyeballs_timeout_ms = data->set.happy_eyeballs_timeout / 2;
result = Curl_cf_create(&cf, &Curl_cft_http_connect, ctx);
if(result)
goto out;
ctx = NULL;
out:
*pcf = result ? NULL : cf;
cf_hc_ctx_destroy(data, ctx);
return result;
}
static CURLcode cf_hc_add(struct Curl_easy *data,
struct Curl_peer *destination,
struct connectdata *conn,
int8_t sockindex,
uint8_t def_transport)
{
struct Curl_cfilter *cf;
CURLcode result = CURLE_OK;
DEBUGASSERT(data);
result = cf_hc_create(&cf, data, destination, def_transport);
if(result)
goto out;
Curl_conn_cf_add(data, conn, sockindex, cf);
#ifdef USE_HTTPSRR
result = Curl_conn_dns_add_https_resolve(data, cf->conn, cf->sockindex,
destination);
#endif
out:
return result;
}
CURLcode Curl_cf_https_setup(struct Curl_easy *data,
struct Curl_peer *destination,
struct connectdata *conn,
int8_t sockindex)
{
CURLcode result = CURLE_OK;
DEBUGASSERT(conn->scheme->protocol == CURLPROTO_HTTPS);
/* This filter is intended for HTTPS using ALPN and does
* not support HTTPS Eyeballing to a proxy. */
if((conn->scheme->protocol != CURLPROTO_HTTPS) ||
#ifndef CURL_DISABLE_PROXY
conn->bits.origin_is_proxy ||
#endif
!conn->bits.tls_enable_alpn)
goto out;
result = cf_hc_add(data, destination, conn, sockindex,
conn->transport_wanted);
out:
return result;
}
#endif /* !CURL_DISABLE_HTTP */
+44
View File
@@ -0,0 +1,44 @@
#ifndef HEADER_CURL_CF_HTTP_H
#define HEADER_CURL_CF_HTTP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_HTTP
struct Curl_cfilter;
struct Curl_easy;
struct connectdata;
struct Curl_cftype;
struct Curl_peer;
extern struct Curl_cftype Curl_cft_http_connect;
CURLcode Curl_cf_https_setup(struct Curl_easy *data,
struct Curl_peer *destination,
struct connectdata *conn,
int8_t sockindex);
#endif /* !CURL_DISABLE_HTTP */
#endif /* HEADER_CURL_CF_HTTP_H */
File diff suppressed because it is too large Load Diff
+73
View File
@@ -0,0 +1,73 @@
#ifndef HEADER_CURL_IP_HAPPY_H
#define HEADER_CURL_IP_HAPPY_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
struct connectdata;
struct Curl_addrinfo;
struct Curl_cfilter;
struct Curl_easy;
struct Curl_peer;
struct Curl_sockaddr_ex;
/**
* Create a cfilter to connect to `origin` via an optional `peer`
* using `transport_peer` and `addr`.
* With a `tunnel_peer` present, the filter will be used to proxy tunnel
* to it and the tunnel will use `tunnel_transport`.
* `pcf`: the filter created on success
* `data`: the transfer initiating the connect
* `conn`: the connection that gets connected
*
* The filter is used in "happy eyeball" scenarios. Once connected,
* it MAY be installed in the connection filter chain to serve transfers.
*/
typedef CURLcode cf_ip_connect_create(struct Curl_cfilter **pcf,
struct Curl_easy *data,
struct Curl_peer *origin,
struct Curl_peer *peer,
uint8_t transport_peer,
struct connectdata *conn,
struct Curl_sockaddr_ex *addr,
struct Curl_peer *tunnel_peer,
uint8_t tunnel_transport);
/**
* Create an IP happy eyeball connection filter that connects to `origin`
* via an optional `peer` using `transport_peer`.
* With a `tunnel_peer` present, the filter will be used to proxy tunnel
* to it and the tunnel will use `tunnel_transport`.
*/
CURLcode Curl_cf_ip_happy_insert_after(struct Curl_cfilter *cf_at,
struct Curl_easy *data,
struct Curl_peer *origin,
struct Curl_peer *peer,
uint8_t transport_peer,
struct Curl_peer *tunnel_peer,
uint8_t tunnel_transport);
extern struct Curl_cftype Curl_cft_ip_happy;
#endif /* HEADER_CURL_IP_HAPPY_H */
+157
View File
@@ -0,0 +1,157 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_WEBSOCKETS
/* only used for this protocol, so far */
#include "urldata.h"
#include "bufq.h"
#include "cfilters.h"
#include "cf-recvbuf.h"
#include "curl_trc.h"
#define CURL_CF_RECVBUF_CHUNK (16 * 1024)
struct cf_recvbuf_ctx {
struct bufq recvbuf;
};
static void cf_recvbuf_destroy(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
struct cf_recvbuf_ctx *ctx = cf->ctx;
(void)data;
if(ctx) {
Curl_bufq_free(&ctx->recvbuf);
curlx_free(ctx);
}
}
static CURLcode cf_recvbuf_recv(struct Curl_cfilter *cf,
struct Curl_easy *data,
char *buf, size_t len,
size_t *pnread)
{
struct cf_recvbuf_ctx *ctx = cf->ctx;
if(!Curl_bufq_is_empty(&ctx->recvbuf)) {
return Curl_bufq_cread(&ctx->recvbuf, buf, len, pnread);
}
if(cf->next)
return cf->next->cft->do_recv(cf->next, data, buf, len, pnread);
*pnread = 0;
return CURLE_RECV_ERROR;
}
static bool cf_recvbuf_data_pending(struct Curl_cfilter *cf,
const struct Curl_easy *data)
{
struct cf_recvbuf_ctx *ctx = cf->ctx;
if(!Curl_bufq_is_empty(&ctx->recvbuf))
return TRUE;
return cf->next ?
cf->next->cft->has_data_pending(cf->next, data) : FALSE;
}
struct Curl_cftype Curl_cft_recvbuf = {
"RECVBUF",
0,
CURL_LOG_LVL_NONE,
cf_recvbuf_destroy,
Curl_cf_def_connect,
Curl_cf_def_shutdown,
Curl_cf_def_adjust_pollset,
cf_recvbuf_data_pending,
Curl_cf_def_send,
cf_recvbuf_recv,
Curl_cf_def_cntrl,
Curl_cf_def_conn_is_alive,
Curl_cf_def_conn_keep_alive,
Curl_cf_def_query,
};
static CURLcode cf_recvbuf_create(struct Curl_cfilter **pcf,
struct Curl_easy *data,
const uint8_t *buf, size_t blen)
{
struct Curl_cfilter *cf = NULL;
struct cf_recvbuf_ctx *ctx;
CURLcode result = CURLE_OK;
size_t nwritten = 0;
(void)data;
ctx = curlx_calloc(1, sizeof(*ctx));
if(!ctx) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
Curl_bufq_init2(&ctx->recvbuf, CURL_CF_RECVBUF_CHUNK,
(blen / CURL_CF_RECVBUF_CHUNK) + 1,
(BUFQ_OPT_SOFT_LIMIT | BUFQ_OPT_NO_SPARES));
result = Curl_bufq_write(&ctx->recvbuf, buf, blen, &nwritten);
if(result)
goto out;
if(nwritten != blen) {
result = CURLE_FAILED_INIT;
goto out;
}
result = Curl_cf_create(&cf, &Curl_cft_recvbuf, ctx);
if(result)
goto out;
ctx = NULL;
out:
*pcf = result ? NULL : cf;
if(ctx) {
Curl_bufq_free(&ctx->recvbuf);
curlx_free(ctx);
}
return result;
}
CURLcode Curl_cf_recvbuf_add(struct Curl_easy *data,
struct connectdata *conn,
int8_t sockindex,
const uint8_t *buf, size_t blen)
{
struct Curl_cfilter *cf;
CURLcode result = CURLE_OK;
DEBUGASSERT(data);
result = cf_recvbuf_create(&cf, data, buf, blen);
if(result)
goto out;
cf->connected = Curl_conn_is_connected(conn, sockindex);
Curl_conn_cf_add(data, conn, sockindex, cf);
out:
return result;
}
#endif /* !CURL_DISABLE_WEBSOCKETS */
+40
View File
@@ -0,0 +1,40 @@
#ifndef HEADER_CURL_CF_RECVBUF_H
#define HEADER_CURL_CF_RECVBUF_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_WEBSOCKETS
/* only used for this protocol, so far */
CURLcode Curl_cf_recvbuf_add(struct Curl_easy *data,
struct connectdata *conn,
int8_t sockindex,
const uint8_t *buf, size_t blen);
extern struct Curl_cftype Curl_cft_recvbuf;
#endif /* !CURL_DISABLE_WEBSOCKETS */
#endif /* HEADER_CURL_CF_RECVBUF_H */
+479
View File
@@ -0,0 +1,479 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include "urldata.h"
#include "cfilters.h"
#include "cf-haproxy.h"
#include "cf-ip-happy.h"
#include "cf-setup.h"
#include "curl_trc.h"
#include "connect.h"
#include "http_proxy.h"
#include "socks.h"
#include "vquic/cf-capsule.h"
#include "vquic/vquic.h"
#include "vtls/vtls.h"
typedef enum {
CF_SETUP_INIT,
CF_SETUP_CNNCT_EYEBALLS,
CF_SETUP_CNNCT_SOCKS,
CF_SETUP_CNNCT_HTTP_PROXY,
CF_SETUP_CNNCT_HAPROXY,
CF_SETUP_CNNCT_SSL,
CF_SETUP_DONE
} cf_setup_state;
struct cf_setup_ctx {
cf_setup_state state;
int ssl_mode;
uint8_t transport;
uint8_t retry_count;
};
#ifndef CURL_DISABLE_PROXY
static CURLcode cf_setup_add_haproxy(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
struct cf_setup_ctx *ctx = cf->ctx;
CURLcode result = CURLE_OK;
if(ctx->state < CF_SETUP_CNNCT_HAPROXY) {
if(data->set.haproxyprotocol) {
if(ctx->transport == TRNSPRT_QUIC) {
failf(data, "haproxy protocol does not support QUIC");
return CURLE_UNSUPPORTED_PROTOCOL;
}
result = Curl_cf_haproxy_insert_after(cf, data);
if(result) {
CURL_TRC_CF(data, cf, "adding HAPROXY filter failed -> %d",
(int)result);
return result;
}
CURL_TRC_CF(data, cf, "added HAPROXY filter");
}
ctx->state = CF_SETUP_CNNCT_HAPROXY;
}
return result;
}
static CURLcode cf_setup_add_socks(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
struct cf_setup_ctx *ctx = cf->ctx;
CURLcode result = CURLE_OK;
if(ctx->state < CF_SETUP_CNNCT_SOCKS && cf->conn->socks_proxy.peer) {
/* Add a SOCKS proxy to go through `first_peer` to `second_peer`*/
struct Curl_peer *second_peer;
if(cf->conn->http_proxy.peer)
second_peer = cf->conn->http_proxy.peer;
else
second_peer = Curl_conn_get_destination(cf->conn, cf->sockindex);
if(!second_peer)
return CURLE_FAILED_INIT;
result = Curl_cf_socks_proxy_insert_after(
cf, data, second_peer, cf->conn->ip_version,
cf->conn->socks_proxy.proxytype,
cf->conn->socks_proxy.creds);
if(result) {
CURL_TRC_CF(data, cf, "adding SOCKS filter failed -> %d", (int)result);
return result;
}
CURL_TRC_CF(data, cf, "added SOCKS filter to %s:%u",
second_peer->hostname, second_peer->port);
ctx->state = CF_SETUP_CNNCT_SOCKS;
}
return result;
}
#ifndef CURL_DISABLE_HTTP
static CURLcode cf_setup_add_http_proxy(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
struct cf_setup_ctx *ctx = cf->ctx;
CURLcode result = CURLE_OK;
if(ctx->state < CF_SETUP_CNNCT_HTTP_PROXY &&
cf->conn->http_proxy.peer && !cf->conn->bits.origin_is_proxy) {
struct Curl_peer *peer = cf->conn->http_proxy.peer;
struct Curl_peer *tunnel_peer =
Curl_conn_get_destination(cf->conn, cf->sockindex);
#ifdef USE_SSL
if(CURL_PROXY_IS_HTTPS(cf->conn->http_proxy.proxytype) &&
!Curl_conn_is_ssl(cf->conn, cf->sockindex)) {
result = Curl_cf_ssl_proxy_insert_after(
cf, data, cf->conn->http_proxy.peer);
if(result) {
CURL_TRC_CF(data, cf, "adding SSL filter for HTTP proxy failed -> %d",
(int)result);
return result;
}
CURL_TRC_CF(data, cf, "added SSL filter for HTTP proxy");
}
#endif /* USE_SSL */
result = Curl_cf_http_proxy_insert_after(
cf, data, peer, tunnel_peer,
ctx->transport, cf->conn->http_proxy.proxytype);
if(result) {
CURL_TRC_CF(data, cf, "adding HTTP proxy tunnel filter failed -> %d",
(int)result);
return result;
}
CURL_TRC_CF(data, cf, "added HTTP proxy tunnel filter");
ctx->state = CF_SETUP_CNNCT_HTTP_PROXY;
}
return result;
}
#endif /* !CURL_DISABLE_HTTP */
#endif /* CURL_DISABLE_PROXY */
/* Get the origin curl connects its socket to.
* Can be origin or the first proxy. */
static struct Curl_peer *conn_get_first_origin(struct connectdata *conn,
int8_t sockindex)
{
#ifndef CURL_DISABLE_PROXY
if(conn->socks_proxy.peer)
return conn->socks_proxy.peer;
if(conn->http_proxy.peer)
return conn->http_proxy.peer;
#endif
return (sockindex == SECONDARYSOCKET) ? conn->origin2 : conn->origin;
}
static CURLcode cf_setup_add_ip_happy(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
struct cf_setup_ctx *ctx = cf->ctx;
CURLcode result = CURLE_OK;
if(ctx->state < CF_SETUP_CNNCT_EYEBALLS) {
/* What is the first hop we directly connect to and what transport
* do we use for it? Only on the first hop we can do Happy Eyeballs.
* first_origin and first_peer differ on --connect-to. */
struct Curl_peer *first_origin =
conn_get_first_origin(cf->conn, cf->sockindex);
struct Curl_peer *first_peer =
Curl_conn_get_first_peer(cf->conn, cf->sockindex);
struct Curl_peer *tunnel_peer = NULL;
uint8_t first_transport = ctx->transport;
if(!first_peer)
return CURLE_FAILED_INIT;
#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
if(cf->conn->http_proxy.peer && !cf->conn->bits.origin_is_proxy) {
first_transport =
Curl_http_proxy_transport(cf->conn->http_proxy.proxytype);
tunnel_peer = Curl_conn_get_destination(cf->conn, cf->sockindex);
if((first_transport == TRNSPRT_QUIC) && cf->conn->socks_proxy.peer) {
failf(data, "HTTP/3 proxy not possible via SOCKS");
return CURLE_UNSUPPORTED_PROTOCOL;
}
}
#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */
result = Curl_cf_ip_happy_insert_after(cf, data, first_origin, first_peer,
first_transport,
tunnel_peer, ctx->transport);
if(result) {
CURL_TRC_CF(data, cf, "adding happy eyeballs failed -> %d", (int)result);
return result;
}
if(tunnel_peer && (first_transport == TRNSPRT_QUIC)) {
CURL_TRC_CF(data, cf, "happy eyeballing to HTTP/3 proxy %s:%u",
first_peer->hostname, first_peer->port);
ctx->state = CF_SETUP_CNNCT_HTTP_PROXY;
}
else {
CURL_TRC_CF(data, cf, "happy eyeballing to %s %s:%u",
tunnel_peer ? "proxy" : "origin",
first_peer->hostname, first_peer->port);
ctx->state = CF_SETUP_CNNCT_EYEBALLS;
}
}
return result;
}
static CURLcode cf_setup_add_origin_filters(struct Curl_cfilter *cf,
struct Curl_easy *data)
{
struct cf_setup_ctx *ctx = cf->ctx;
CURLcode result = CURLE_OK;
(void)data; /* not used in all builds */
if(ctx->state < CF_SETUP_CNNCT_SSL) {
#if !defined(CURL_DISABLE_HTTP) && defined(USE_HTTP3) && \
!defined(CURL_DISABLE_PROXY)
/* Wanting QUIC with an HTTP tunneling filter, we now need to add
* the QUIC filter on top. Without tunneling, this has already
* happened in the Happy Eyeball filter. */
if(ctx->transport == TRNSPRT_QUIC &&
cf->conn->http_proxy.peer && !cf->conn->bits.origin_is_proxy) {
struct Curl_peer *origin = Curl_conn_get_origin(cf->conn, cf->sockindex);
struct Curl_peer *peer =
Curl_conn_get_destination(cf->conn, cf->sockindex);
result = Curl_cf_capsule_insert_after(cf, data);
if(result) {
CURL_TRC_CF(data, cf, "adding capsule filter failed -> %d",
(int)result);
return result;
}
result = Curl_cf_quic_insert_after(cf, data, origin, peer);
if(result) {
CURL_TRC_CF(data, cf, "adding QUIC filter failed -> %d", (int)result);
return result;
}
CURL_TRC_CF(data, cf, "added QUIC filter for origin");
}
else
#endif /* !CURL_DISABLE_HTTP && USE_HTTP3 && CURL_DISABLE_PROXY */
#ifdef USE_SSL
if((ctx->ssl_mode == CURL_CF_SSL_ENABLE ||
(ctx->ssl_mode != CURL_CF_SSL_DISABLE &&
cf->conn->scheme->flags & PROTOPT_SSL)) && /* we want SSL */
!Curl_conn_is_ssl(cf->conn, cf->sockindex)) { /* it is missing */
#ifndef CURL_DISABLE_PROXY
if(cf->conn->bits.origin_is_proxy) {
result = Curl_cf_ssl_proxy_insert_after(cf, data, cf->conn->origin);
}
else
#endif
{
/* FTP is a bitch. Wherever we really connect to on the DATA
* (secondary) connection, many servers require TLS sessions reuse
* to prove they are talking to the same client.
* For the TLS session lookup to work, we need to instantiate
* the SSL filter with the same peers as FIRSTSOCKET. See #22225
* Meaning: cf->sockindex does not matter here. */
result = Curl_cf_ssl_insert_after(cf, data,
Curl_conn_get_origin(cf->conn, FIRSTSOCKET),
Curl_conn_get_destination(cf->conn, FIRSTSOCKET));
}
if(result) {
CURL_TRC_CF(data, cf, "adding SSL filter for origin failed -> %d",
(int)result);
return result;
}
CURL_TRC_CF(data, cf, "added SSL filter for origin");
}
#endif /* USE_SSL */
ctx->state = CF_SETUP_CNNCT_SSL;
}
return result;
}
static CURLcode cf_setup_connect_steps(struct Curl_cfilter *cf,
struct Curl_easy *data,
bool *done)
{
struct cf_setup_ctx *ctx = cf->ctx;
CURLcode result = CURLE_OK;
if(cf->connected) {
*done = TRUE;
return CURLE_OK;
}
/* connect current sub-chain */
connect_sub_chain:
VERBOSE(Curl_conn_trc_filters(data, cf->sockindex, "cf_setup_connect"));
if(cf->next && !cf->next->connected) {
result = Curl_conn_cf_connect(cf->next, data, done);
if(result || !*done)
return result;
}
result = cf_setup_add_ip_happy(cf, data);
if(result)
return result;
if(!cf->next || !cf->next->connected)
goto connect_sub_chain;
#ifndef CURL_DISABLE_PROXY
result = cf_setup_add_socks(cf, data);
if(result)
return result;
if(!cf->next || !cf->next->connected)
goto connect_sub_chain;
#ifndef CURL_DISABLE_HTTP
result = cf_setup_add_http_proxy(cf, data);
if(result)
return result;
if(!cf->next || !cf->next->connected)
goto connect_sub_chain;
#endif /* !CURL_DISABLE_HTTP */
result = cf_setup_add_haproxy(cf, data);
if(result)
return result;
if(!cf->next || !cf->next->connected)
goto connect_sub_chain;
#endif /* !CURL_DISABLE_PROXY */
result = cf_setup_add_origin_filters(cf, data);
if(result)
return result;
if(!cf->next || !cf->next->connected)
goto connect_sub_chain;
ctx->state = CF_SETUP_DONE;
cf->connected = TRUE;
*done = TRUE;
return CURLE_OK;
}
static CURLcode cf_setup_connect(struct Curl_cfilter *cf,
struct Curl_easy *data,
bool *done)
{
struct cf_setup_ctx *ctx = cf->ctx;
CURLcode result;
/* In some situations, a server/proxy may close the connection and
* we need to connect again (HTTP/1.x proxy auth, for example).
* We used to close the filters and reuse them for another attempt,
* however that complicates filter code and it is simpler to tear them
* all down and start over. */
retry:
result = cf_setup_connect_steps(cf, data, done);
if(result == CURLE_AGAIN) {
++ctx->retry_count;
if(ctx->retry_count > 5) /* arbitrary limit, better just timeout? */
return CURLE_COULDNT_CONNECT;
CURL_TRC_CF(data, cf, "retrying connect, %d. time", ctx->retry_count);
Curl_conn_cf_discard_chain(&cf->next, data);
ctx->state = CF_SETUP_INIT;
goto retry;
}
return result;
}
static void cf_setup_destroy(struct Curl_cfilter *cf, struct Curl_easy *data)
{
struct cf_setup_ctx *ctx = cf->ctx;
CURL_TRC_CF(data, cf, "destroy");
curlx_safefree(ctx);
}
struct Curl_cftype Curl_cft_setup = {
"SETUP",
CF_TYPE_SETUP,
CURL_LOG_LVL_NONE,
cf_setup_destroy,
cf_setup_connect,
Curl_cf_def_shutdown,
Curl_cf_def_adjust_pollset,
Curl_cf_def_data_pending,
Curl_cf_def_send,
Curl_cf_def_recv,
Curl_cf_def_cntrl,
Curl_cf_def_conn_is_alive,
Curl_cf_def_conn_keep_alive,
Curl_cf_def_query,
};
static CURLcode cf_setup_create(struct Curl_cfilter **pcf,
struct Curl_easy *data,
uint8_t transport,
int ssl_mode)
{
struct Curl_cfilter *cf = NULL;
struct cf_setup_ctx *ctx;
CURLcode result = CURLE_OK;
(void)data;
ctx = curlx_calloc(1, sizeof(*ctx));
if(!ctx) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
ctx->state = CF_SETUP_INIT;
ctx->ssl_mode = ssl_mode;
ctx->transport = transport;
result = Curl_cf_create(&cf, &Curl_cft_setup, ctx);
if(result)
goto out;
ctx = NULL;
out:
*pcf = result ? NULL : cf;
if(ctx) {
curlx_free(ctx);
}
return result;
}
CURLcode Curl_cf_setup_add(struct Curl_easy *data,
struct connectdata *conn,
int8_t sockindex,
uint8_t transport,
int ssl_mode)
{
struct Curl_cfilter *cf;
CURLcode result = CURLE_OK;
DEBUGASSERT(data);
result = cf_setup_create(&cf, data, transport, ssl_mode);
if(result)
goto out;
Curl_conn_cf_add(data, conn, sockindex, cf);
out:
return result;
}
CURLcode Curl_cf_setup_insert_after(struct Curl_cfilter *cf_at,
struct Curl_easy *data,
uint8_t transport,
int ssl_mode)
{
struct Curl_cfilter *cf;
CURLcode result;
DEBUGASSERT(data);
result = cf_setup_create(&cf, data, transport, ssl_mode);
if(result)
goto out;
Curl_conn_cf_insert_after(cf_at, cf);
out:
return result;
}
+46
View File
@@ -0,0 +1,46 @@
#ifndef HEADER_CURL_CF_SETUP_H
#define HEADER_CURL_CF_SETUP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
struct Curl_dns_entry;
struct ip_quadruple;
struct Curl_peer;
struct Curl_str;
CURLcode Curl_cf_setup_add(struct Curl_easy *data,
struct connectdata *conn,
int8_t sockindex,
uint8_t transport,
int ssl_mode);
CURLcode Curl_cf_setup_insert_after(struct Curl_cfilter *cf_at,
struct Curl_easy *data,
uint8_t transport,
int ssl_mode);
extern struct Curl_cftype Curl_cft_setup;
#endif /* HEADER_CURL_CF_SETUP_H */
File diff suppressed because it is too large Load Diff
+154
View File
@@ -0,0 +1,154 @@
#ifndef HEADER_CURL_CF_SOCKET_H
#define HEADER_CURL_CF_SOCKET_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
struct Curl_addrinfo;
struct Curl_cfilter;
struct Curl_easy;
struct connectdata;
struct Curl_sockaddr_ex;
struct ip_quadruple;
#define curl_sa_addr addr.sa
#define curl_sa_addrbuf addr.buf
/*
* Parse interface option, and return the interface name and the host part.
*/
CURLcode Curl_parse_interface(const char *input,
char **dev, char **iface, char **host);
CURLcode Curl_socket_addr_from_ai(struct Curl_sockaddr_ex *addr,
const struct Curl_addrinfo *ai,
uint8_t transport);
/*
* Create a socket based on info from 'conn' and 'ai'.
*
* Fill in 'addr' and 'sockfd' accordingly if OK is returned. If the open
* socket callback is set, used that!
*
*/
CURLcode Curl_socket_open(struct Curl_easy *data,
const struct Curl_addrinfo *ai,
struct Curl_sockaddr_ex *addr,
uint8_t transport,
curl_socket_t *sockfd);
#ifdef USE_SO_NOSIGPIPE
/* Set SO_NOSIGPIPE on socket, return < 0 on error. */
int Curl_sock_nosigpipe(curl_socket_t sockfd);
#endif
int Curl_socket_close(struct Curl_easy *data, struct connectdata *conn,
curl_socket_t sock);
/**
* Creates a cfilter that opens a TCP socket to the given address
* when calling its `connect` implementation.
* The filter will not touch any connection/data flags and can be
* used in happy eyeballing. Once selected for use, its `_active()`
* method needs to be called.
*/
CURLcode Curl_cf_tcp_create(struct Curl_cfilter **pcf,
struct Curl_easy *data,
struct Curl_peer *origin,
struct Curl_peer *peer,
uint8_t transport_peer,
struct connectdata *conn,
struct Curl_sockaddr_ex *addr,
struct Curl_peer *tunnel_peer,
uint8_t tunnel_transport);
/**
* Creates a cfilter that opens a UDP socket to the given address
* when calling its `connect` implementation.
* The filter will not touch any connection/data flags and can be
* used in happy eyeballing. Once selected for use, its `_active()`
* method needs to be called.
*/
CURLcode Curl_cf_udp_create(struct Curl_cfilter **pcf,
struct Curl_easy *data,
struct Curl_peer *origin,
struct Curl_peer *peer,
uint8_t transport_peer,
struct connectdata *conn,
struct Curl_sockaddr_ex *addr,
struct Curl_peer *tunnel_peer,
uint8_t tunnel_transport);
/**
* Creates a cfilter that opens a UNIX socket to the given address
* when calling its `connect` implementation.
* The filter will not touch any connection/data flags and can be
* used in happy eyeballing. Once selected for use, its `_active()`
* method needs to be called.
*/
CURLcode Curl_cf_unix_create(struct Curl_cfilter **pcf,
struct Curl_easy *data,
struct Curl_peer *origin,
struct Curl_peer *peer,
uint8_t transport_peer,
struct connectdata *conn,
struct Curl_sockaddr_ex *addr,
struct Curl_peer *tunnel_peer,
uint8_t tunnel_transport);
/**
* Creates a cfilter that keeps a listening socket.
*/
CURLcode Curl_conn_tcp_listen_set(struct Curl_easy *data,
struct connectdata *conn,
int8_t sockindex,
curl_socket_t *s);
/**
* Return TRUE iff the last filter at `sockindex` was set via
* Curl_conn_tcp_listen_set().
*/
bool Curl_conn_is_tcp_listen(struct Curl_easy *data,
int8_t sockindex);
/**
* Peek at the socket and remote ip/port the socket filter is using.
* The filter owns all returned values.
* @param psock pointer to hold socket descriptor or NULL
* @param paddr pointer to hold addr reference or NULL
* @param pip pointer to get IP quadruple or NULL
* Returns error if the filter is of invalid type.
*/
CURLcode Curl_cf_socket_peek(struct Curl_cfilter *cf,
struct Curl_easy *data,
curl_socket_t *psock,
const struct Curl_sockaddr_ex **paddr,
struct ip_quadruple *pip) WARN_UNUSED_RESULT;
extern struct Curl_cftype Curl_cft_tcp;
extern struct Curl_cftype Curl_cft_udp;
extern struct Curl_cftype Curl_cft_unix;
extern struct Curl_cftype Curl_cft_tcp_accept;
#endif /* HEADER_CURL_CF_SOCKET_H */
File diff suppressed because it is too large Load Diff
+692
View File
@@ -0,0 +1,692 @@
#ifndef HEADER_CURL_CFILTERS_H
#define HEADER_CURL_CFILTERS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curlx/timediff.h"
struct bufq;
struct Curl_cfilter;
struct Curl_easy;
struct Curl_dns_entry;
struct connectdata;
struct ip_quadruple;
struct curl_tlssessioninfo;
/* Callback to destroy resources held by this filter instance.
* Implementations MUST NOT chain calls to cf->next.
*/
typedef void Curl_cft_destroy_this(struct Curl_cfilter *cf,
struct Curl_easy *data);
/* Callback to close the connection filter gracefully, non-blocking.
* Implementations MUST NOT chain calls to cf->next.
*/
typedef CURLcode Curl_cft_shutdown(struct Curl_cfilter *cf,
struct Curl_easy *data,
bool *done);
typedef CURLcode Curl_cft_connect(struct Curl_cfilter *cf,
struct Curl_easy *data,
bool *done);
struct easy_pollset;
/* Passing in an easy_pollset for monitoring of sockets, let
* filters add or remove sockets actions (CURL_POLL_OUT, CURL_POLL_IN).
* This may add a socket or, in case no actions remain, remove
* a socket from the set.
*
* Filter implementations need to call filters "below" *after* they have
* made their adjustments. This allows lower filters to override "upper"
* actions. If a "lower" filter is unable to write, it needs to be able
* to disallow POLL_OUT.
*
* A filter without own restrictions/preferences should not modify
* the pollset. Filters, whose filter "below" is not connected, should
* also do no adjustments.
*
* Examples: a TLS handshake, while ongoing, might remove POLL_IN when it
* needs to write, or vice versa. An HTTP/2 filter might remove POLL_OUT when
* a stream window is exhausted and a WINDOW_UPDATE needs to be received first
* and add instead POLL_IN.
*
* @param cf the filter to ask
* @param data the easy handle the pollset is about
* @param ps the pollset (inout) for the easy handle
*/
typedef CURLcode Curl_cft_adjust_pollset(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct easy_pollset *ps);
typedef bool Curl_cft_data_pending(struct Curl_cfilter *cf,
const struct Curl_easy *data);
typedef CURLcode Curl_cft_send(struct Curl_cfilter *cf,
struct Curl_easy *data, /* transfer */
const uint8_t *buf, /* data to write */
size_t len, /* amount to write */
bool eos, /* last chunk */
size_t *pnwritten); /* how much sent */
typedef CURLcode Curl_cft_recv(struct Curl_cfilter *cf,
struct Curl_easy *data, /* transfer */
char *buf, /* store data here */
size_t len, /* amount to read */
size_t *pnread); /* how much received */
typedef bool Curl_cft_conn_is_alive(struct Curl_cfilter *cf,
struct Curl_easy *data,
bool *input_pending);
typedef CURLcode Curl_cft_conn_keep_alive(struct Curl_cfilter *cf,
struct Curl_easy *data);
/**
* Events/controls for connection filters, their arguments and
* return code handling. Filter callbacks are invoked "top down".
* Return code handling:
* "first fail" meaning that the first filter returning != CURLE_OK, will
* abort further event distribution and determine the result.
* "ignored" meaning return values are ignored and the event is distributed
* to all filters in the chain. Overall result is always CURLE_OK.
*/
/* data event arg1 arg2 return */
#define CF_CTRL_DATA_SETUP 4 /* 0 NULL first fail */
/* unused now 5 */
#define CF_CTRL_DATA_PAUSE 6 /* on/off NULL first fail */
#define CF_CTRL_DATA_DONE 7 /* premature NULL ignored */
#define CF_CTRL_DATA_DONE_SEND 8 /* 0 NULL ignored */
/* update conn info at connection and data */
#define CF_CTRL_CONN_INFO_UPDATE (256 + 0) /* 0 NULL ignored */
#define CF_CTRL_FORGET_SOCKET (256 + 1) /* 0 NULL ignored */
#define CF_CTRL_FLUSH (256 + 2) /* 0 NULL first fail */
#define CF_CTRL_REPORT_STATS (256 + 3) /* 0 NULL ignored */
/**
* Handle event/control for the filter.
* Implementations MUST NOT chain calls to cf->next.
*/
typedef CURLcode Curl_cft_cntrl(struct Curl_cfilter *cf,
struct Curl_easy *data,
int event, int arg1, void *arg2);
/**
* Queries to ask via a `Curl_cft_query *query` method on a cfilter chain.
* - MAX_CONCURRENT: the maximum number of parallel transfers the filter
* chain expects to handle at the same time.
* default: 1 if no filter overrides.
* - CONNECT_REPLY_MS: milliseconds until the first indication of a server
* response was received on a connect. For TCP, this
* reflects the time until the socket connected. On UDP
* this gives the time the first bytes from the server
* were received.
* -1 if not determined yet.
* - CF_QUERY_SOCKET: the socket used by the filter chain
* - CF_QUERY_NEED_FLUSH: TRUE iff any of the filters have unsent data
* - CF_QUERY_IP_INFO: res1 says if connection used IPv6, res2 is the
* ip quadruple
* - CF_QUERY_HOST_PORT: the remote hostname and port a filter talks to
* - CF_QUERY_SSL_INFO: fill out the passed curl_tlssessioninfo with the
* internal from the SSL secured connection when
* available.
* - CF_QUERY_SSL_CTX_INFO: same as CF_QUERY_SSL_INFO, but give the SSL_CTX
* when available, or the same internal pointer
* when the TLS stack does not differentiate.
* - CF_QUERY_ALPN_NEGOTIATED: The ALPN selected by the server as
null-terminated string or NULL if none
selected/handshake not done. Implemented by filter
types CF_TYPE_SSL or CF_TYPE_IP_CONNECT.
* - CF_QUERY_REALLY_CONNECTED: implemented in socket filters to return
* if a reply from a server has really arrived. For
* non-UDP sockets this is TRUE when the socket became
* writable. For UDP sockets, this is TRUE when the
* first byte from the peer was received.
*/
/* query res1 res2 */
#define CF_QUERY_MAX_CONCURRENT 1 /* number - */
#define CF_QUERY_CONNECT_REPLY_MS 2 /* number - */
#define CF_QUERY_SOCKET 3 /* - curl_socket_t */
/* unused 4 + 5 */
#define CF_QUERY_STREAM_ERROR 6 /* error code - */
#define CF_QUERY_NEED_FLUSH 7 /* TRUE/FALSE - */
#define CF_QUERY_IP_INFO 8 /* TRUE/FALSE struct ip_quadruple */
#define CF_QUERY_HTTP_VERSION 9 /* number (10/11/20/30) - */
/* pass in a `const struct Curl_sockaddr_ex **` as `pres2`. Gets set
* to NULL when not connected. */
#define CF_QUERY_REMOTE_ADDR 10 /* - `Curl_sockaddr_ex *` */
#define CF_QUERY_HOST_PORT 11 /* port const char * */
#define CF_QUERY_SSL_INFO 12 /* - struct curl_tlssessioninfo * */
#define CF_QUERY_SSL_CTX_INFO 13 /* - struct curl_tlssessioninfo * */
#define CF_QUERY_TRANSPORT 14 /* TRNSPRT_* - * */
#define CF_QUERY_ALPN_NEGOTIATED 15 /* - const char * */
#define CF_QUERY_REALLY_CONNECTED 16 /* TRUE/FALSE - */
/**
* Query the cfilter for properties. Filters ignorant of a query will
* pass it "down" the filter chain.
*/
typedef CURLcode Curl_cft_query(struct Curl_cfilter *cf,
struct Curl_easy *data,
int query, int *pres1, void *pres2);
/**
* Type flags for connection filters. A filter can have none, one or
* many of those. Use to evaluate state/capabilities of a filter chain.
*
* CF_TYPE_IP_CONNECT: provides an IP connection or sth equivalent, like
* a CONNECT tunnel, a UNIX domain socket, a QUIC
* connection, etc.
* CF_TYPE_SSL: provide SSL/TLS
* CF_TYPE_MULTIPLEX: provides multiplexing of easy handles
* CF_TYPE_PROXY provides proxying
* CF_TYPE_HTTP implement a version of the HTTP protocol
* CF_TYPE_SETUP filter is only needed for connection setup and
* can be removed once connected
* CF_TYPE_DNS filter managing DNS resolve operations
*/
#define CF_TYPE_IP_CONNECT (1 << 0)
#define CF_TYPE_SSL (1 << 1)
#define CF_TYPE_MULTIPLEX (1 << 2)
#define CF_TYPE_PROXY (1 << 3)
#define CF_TYPE_HTTP (1 << 4)
#define CF_TYPE_SETUP (1 << 5)
#define CF_TYPE_DNS (1 << 6)
/* A connection filter type, e.g. specific implementation. */
struct Curl_cftype {
const char *name; /* name of the filter type */
int flags; /* flags of filter type */
int log_level; /* log level for such filters */
Curl_cft_destroy_this *destroy; /* destroy resources of this cf */
Curl_cft_connect *do_connect; /* establish connection */
Curl_cft_shutdown *do_shutdown; /* shutdown conn */
Curl_cft_adjust_pollset *adjust_pollset; /* adjust transfer poll set */
Curl_cft_data_pending *has_data_pending; /* conn has data pending */
Curl_cft_send *do_send; /* send data */
Curl_cft_recv *do_recv; /* receive data */
Curl_cft_cntrl *cntrl; /* events/control */
Curl_cft_conn_is_alive *is_alive; /* FALSE if conn is dead, Jim! */
Curl_cft_conn_keep_alive *keep_alive; /* try to keep it alive */
Curl_cft_query *query; /* query filter chain */
};
/* A connection filter instance, e.g. registered at a connection */
struct Curl_cfilter {
const struct Curl_cftype *cft; /* the type providing implementation */
struct Curl_cfilter *next; /* next filter in chain */
void *ctx; /* filter type specific settings */
struct connectdata *conn; /* the connection this filter belongs to */
int8_t sockindex; /* the index the filter is installed at */
BIT(connected); /* != 0 iff this filter is connected */
BIT(shutdown); /* != 0 iff this filter has shut down */
};
/* Default implementations for the type functions, implementing nop. */
void Curl_cf_def_destroy_this(struct Curl_cfilter *cf,
struct Curl_easy *data);
/* Default implementations for the type functions, implementing pass-through
* the filter chain. */
CURLcode Curl_cf_def_adjust_pollset(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct easy_pollset *ps);
bool Curl_cf_def_data_pending(struct Curl_cfilter *cf,
const struct Curl_easy *data);
CURLcode Curl_cf_def_send(struct Curl_cfilter *cf, struct Curl_easy *data,
const uint8_t *buf, size_t len, bool eos,
size_t *pnwritten);
CURLcode Curl_cf_def_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
char *buf, size_t len, size_t *pnread);
CURLcode Curl_cf_def_cntrl(struct Curl_cfilter *cf,
struct Curl_easy *data,
int event, int arg1, void *arg2);
bool Curl_cf_def_conn_is_alive(struct Curl_cfilter *cf,
struct Curl_easy *data,
bool *input_pending);
CURLcode Curl_cf_def_conn_keep_alive(struct Curl_cfilter *cf,
struct Curl_easy *data);
CURLcode Curl_cf_def_query(struct Curl_cfilter *cf,
struct Curl_easy *data,
int query, int *pres1, void *pres2);
CURLcode Curl_cf_def_shutdown(struct Curl_cfilter *cf,
struct Curl_easy *data, bool *done);
CURLcode Curl_cf_def_connect(struct Curl_cfilter *cf,
struct Curl_easy *data, bool *done);
/**
* Create a new filter instance, unattached to the filter chain.
* Use Curl_conn_cf_add() to add it to the chain.
* @param pcf on success holds the created instance
* @param cft the filter type
* @param ctx the type specific context to use
*/
CURLcode Curl_cf_create(struct Curl_cfilter **pcf,
const struct Curl_cftype *cft,
void *ctx);
/**
* Add a filter instance to the `sockindex` filter chain at connection
* `conn`. The filter must not already be attached. It is inserted at
* the start of the chain (top).
*/
void Curl_conn_cf_add(struct Curl_easy *data,
struct connectdata *conn,
int8_t sockindex,
struct Curl_cfilter *cf);
/**
* Insert a filter (chain) after `cf_at`.
* `cf_new` must not already be attached.
*/
void Curl_conn_cf_insert_after(struct Curl_cfilter *cf_at,
struct Curl_cfilter *cf_new);
/**
* Extract filter `*pcf` from its connection filter chain.
* Destroy `*pcf`, even if it was not part of the chain and NULL it.
* Returns TRUE of cf has been part of chain.
*/
bool Curl_conn_cf_discard(struct Curl_cfilter **pcf,
struct Curl_easy *data);
/**
* Discard all cfilters starting with `*pcf` and clearing it afterwards.
*/
void Curl_conn_cf_discard_chain(struct Curl_cfilter **pcf,
struct Curl_easy *data);
/**
* Remove and destroy all filters at chain `sockindex` on connection `conn`.
*/
void Curl_conn_cf_discard_all(struct Curl_easy *data,
struct connectdata *conn, int8_t sockindex);
CURLcode Curl_conn_cf_connect(struct Curl_cfilter *cf,
struct Curl_easy *data,
bool *done);
CURLcode Curl_conn_cf_send(struct Curl_cfilter *cf, struct Curl_easy *data,
const uint8_t *buf, size_t len, bool eos,
size_t *pnwritten);
CURLcode Curl_conn_cf_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
char *buf, size_t len, size_t *pnread);
CURLcode Curl_conn_cf_cntrl(struct Curl_cfilter *cf,
struct Curl_easy *data,
bool ignore_result,
int event, int arg1, void *arg2);
/**
* Get the socket used by the filter chain starting at `cf`.
* Returns CURL_SOCKET_BAD if not available.
*/
curl_socket_t Curl_conn_cf_get_socket(struct Curl_cfilter *cf,
struct Curl_easy *data);
CURLcode Curl_conn_cf_get_ip_info(struct Curl_cfilter *cf,
struct Curl_easy *data,
bool *is_ipv6, struct ip_quadruple *ipquad);
bool Curl_conn_cf_needs_flush(struct Curl_cfilter *cf,
struct Curl_easy *data);
bool Curl_conn_cf_is_ip_connected(struct Curl_cfilter *cf,
struct Curl_easy *data);
unsigned char Curl_conn_cf_get_transport(struct Curl_cfilter *cf,
struct Curl_easy *data);
int Curl_socktype_for_transport(uint8_t transport);
int Curl_protocol_for_transport(uint8_t transport);
const char *Curl_conn_cf_get_alpn_negotiated(struct Curl_cfilter *cf,
struct Curl_easy *data);
#define CURL_CF_SSL_DEFAULT (-1)
#define CURL_CF_SSL_DISABLE 0
#define CURL_CF_SSL_ENABLE 1
/**
* Check if a filter chain at `sockindex` for connection `conn` exists.
*/
bool Curl_conn_is_setup(struct connectdata *conn, int8_t sockindex);
/**
* Check if the filter chain at `sockindex` for connection `conn` is
* completely connected.
*/
bool Curl_conn_is_connected(struct connectdata *conn, int8_t sockindex);
/**
* Determine if we have reached the remote host on IP level, e.g.
* have a TCP connection. This turns TRUE before a possible SSL
* handshake has been started/done.
*/
bool Curl_conn_is_ip_connected(struct Curl_easy *data, int8_t sockindex);
/**
* Determine if the connection is using SSL to the remote host
* (or will be once connected). This will return FALSE, if SSL
* is only used in proxying and not for the tunnel itself.
*/
bool Curl_conn_is_ssl(struct connectdata *conn, int8_t sockindex);
/* Determine if the connection has one or more proxy filters.
* e.g. is tunneling. */
bool Curl_conn_is_tunneling(struct connectdata *conn, int8_t sockindex);
/*
* Fill `info` with information about the TLS instance securing the connection
* when available, otherwise e.g. when Curl_conn_is_ssl() is FALSE, return
* FALSE. 'query' should be CF_QUERY_SSL_INFO or CF_QUERY_SSL_CTX_INFO.
*/
bool Curl_conn_get_ssl_info(struct Curl_easy *data,
struct connectdata *conn, int8_t sockindex,
int query,
struct curl_tlssessioninfo *info);
CURLcode Curl_conn_get_ip_info(struct Curl_easy *data,
struct connectdata *conn, int8_t sockindex,
bool *is_ipv6, struct ip_quadruple *ipquad);
/**
* Connection provides multiplexing of easy handles at `socketindex`.
*/
bool Curl_conn_is_multiplex(struct connectdata *conn, int8_t sockindex);
/**
* Return the HTTP version used on the FIRSTSOCKET connection filters
* or 0 if unknown. Value otherwise is 09, 10, 11, etc.
*/
unsigned char Curl_conn_http_version(struct Curl_easy *data,
struct connectdata *conn);
/* Get the TRNSPRT_* the connection is using */
unsigned char Curl_conn_get_transport(struct Curl_easy *data,
struct connectdata *conn);
/* Get the negotiated ALPN protocol or NULL if none in play */
const char *Curl_conn_get_alpn_negotiated(struct Curl_easy *data,
struct connectdata *conn);
void Curl_conn_cntrl_update_info(struct Curl_easy *data,
struct connectdata *conn);
void Curl_conn_cntrl_report_stats(struct Curl_easy *data,
struct connectdata *conn,
int sockindex);
void Curl_conn_remove_setup_filters(struct Curl_easy *data,
int8_t sockindex);
/**
* Return if data is pending in some connection filter at chain
* `sockindex` for connection `data->conn`.
*/
bool Curl_conn_data_pending(struct Curl_easy *data,
int8_t sockindex);
/**
* Return TRUE if any of the connection filters at chain `sockindex`
* have data still to send.
*/
bool Curl_conn_needs_flush(struct Curl_easy *data, int8_t sockindex);
/**
* Flush any pending data on the connection filters at chain `sockindex`.
*/
CURLcode Curl_conn_flush(struct Curl_easy *data, int8_t sockindex);
/**
* Return the socket used on data's connection for FIRSTSOCKET,
* querying filters if the whole chain has not connected yet.
* Returns CURL_SOCKET_BAD if not available.
*/
curl_socket_t Curl_conn_get_first_socket(struct Curl_easy *data);
/* Return a pointer to the connected socket address or NULL. */
const struct Curl_sockaddr_ex *
Curl_conn_get_remote_addr(struct Curl_easy *data, int8_t sockindex);
/**
* Tell filters to forget about the socket at sockindex.
*/
void Curl_conn_forget_socket(struct Curl_easy *data, int8_t sockindex);
/**
* Adjust the pollset for the filter chain starting at `cf`.
*/
CURLcode Curl_conn_cf_adjust_pollset(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct easy_pollset *ps);
/**
* Adjust pollset from filters installed at transfer's connection.
*/
CURLcode Curl_conn_adjust_pollset(struct Curl_easy *data,
struct connectdata *conn,
struct easy_pollset *ps);
/**
* Curl_poll() the filter chain at `cf` with timeout `timeout_ms`.
* Returns 0 on timeout, negative on error or number of sockets
* with requested poll events.
*/
int Curl_conn_cf_poll(struct Curl_cfilter *cf,
struct Curl_easy *data,
timediff_t timeout_ms);
/**
* Receive data through the filter chain at `sockindex` for connection
* `data->conn`. Copy at most `len` bytes into `buf`. Return the
* actual number of bytes copied in `*pnread`or an error.
*/
CURLcode Curl_cf_recv(struct Curl_easy *data, int8_t sockindex, char *buf,
size_t len, size_t *pnread);
/**
* Send `len` bytes of data from `buf` through the filter chain `sockindex`
* at connection `data->conn`. Return the actual number of bytes written
* in `*pnwritten` or on error.
*/
CURLcode Curl_cf_send(struct Curl_easy *data, int8_t sockindex,
const uint8_t *buf, size_t len, bool eos,
size_t *pnwritten);
/**
* Receive bytes from connection filter `cf` into `bufq`.
* Convenience wrapper around `Curl_bufq_sipn()`,
* so users do not have to implement a callback.
*/
CURLcode Curl_cf_recv_bufq(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct bufq *bufq,
size_t maxlen,
size_t *pnread);
/**
* Send bytes in `bufq` using connection filter `cf`.
* A convenience wrapper around `Curl_bufq_write_pass()`,
* so users do not have to implement a callback.
*/
CURLcode Curl_cf_send_bufq(struct Curl_cfilter *cf,
struct Curl_easy *data,
struct bufq *bufq,
const unsigned char *buf, size_t blen,
size_t *pnwritten);
/**
* Notify connection filters that they need to setup data for
* a transfer.
*/
CURLcode Curl_conn_ev_data_setup(struct Curl_easy *data);
/**
* Notify connection filters that the transfer represented by `data`
* is done with sending data (e.g. has uploaded everything).
*/
void Curl_conn_ev_data_done_send(struct Curl_easy *data);
/**
* Notify connection filters that the transfer represented by `data`
* is finished - eventually premature, e.g. before being complete.
*/
void Curl_conn_ev_data_done(struct Curl_easy *data, bool premature);
/**
* Notify connection filters that the transfer of data is paused/unpaused.
*/
CURLcode Curl_conn_ev_data_pause(struct Curl_easy *data, bool do_pause);
/**
* Check if FIRSTSOCKET's cfilter chain deems connection alive.
*/
bool Curl_conn_is_alive(struct Curl_easy *data, struct connectdata *conn,
bool *input_pending);
/**
* Try to upkeep the connection filters.
*/
CURLcode Curl_conn_keep_alive(struct Curl_easy *data,
struct connectdata *conn);
/**
* Get the remote hostname and port that the connection is currently
* talking to (or will talk to).
* Once connected or before connect starts,
* it is `conn->origin->hostname` and `conn->origin->port`.
* During connect, when tunneling proxies are involved (http or socks),
* it will be the name and port the proxy currently negotiates with.
*/
void Curl_conn_get_current_host(struct Curl_easy *data, int8_t sockindex,
const char **phost, int *pport);
/**
* Get the maximum number of parallel transfers the connection
* expects to be able to handle at `sockindex`.
*/
size_t Curl_conn_get_max_concurrent(struct Curl_easy *data,
struct connectdata *conn,
int8_t sockindex);
/**
* Get the underlying error code for a transfer stream or 0 if not known.
*/
int Curl_conn_get_stream_error(struct Curl_easy *data,
struct connectdata *conn,
int8_t sockindex);
#ifdef CURLVERBOSE
void Curl_conn_trc_filters(struct Curl_easy *data,
int8_t sockindex, const char *info);
#endif
/**
* Get the index of the given socket in the connection's sockets.
* Useful in calling `Curl_conn_send()/Curl_conn_recv()` with the
* correct socket index.
*/
int8_t Curl_conn_sockindex(struct Curl_easy *data, curl_socket_t sockfd);
/*
* Receive data on the connection, using FIRSTSOCKET/SECONDARYSOCKET.
* Return CURLE_AGAIN iff blocked on receiving.
*/
CURLcode Curl_conn_recv(struct Curl_easy *data, int8_t sockindex,
char *buf, size_t len, size_t *pnread);
/*
* Send data on the connection, using FIRSTSOCKET/SECONDARYSOCKET.
* Return CURLE_AGAIN iff blocked on sending.
*/
CURLcode Curl_conn_send(struct Curl_easy *data, int8_t sockindex,
const void *buf, size_t len, bool eos,
size_t *pnwritten);
/**
* Types and macros used to keep the current easy handle in filter calls,
* allowing for nested invocations. See #10336.
*
* `cf_call_data` is intended to be a member of the cfilter's `ctx` type.
* A filter defines the macro `CF_CTX_CALL_DATA` to give access to that.
*
* With all values 0, the default, this indicates that there is no cfilter
* call with `data` ongoing.
* Macro `CF_DATA_SAVE` preserves the current `cf_call_data` in a local
* variable and sets the `data` given, incrementing the `depth` counter.
*
* Macro `CF_DATA_RESTORE` restores the old values from the local variable,
* while checking that `depth` values are as expected (debug build), catching
* cases where a "lower" RESTORE was not called.
*
* Finally, macro `CF_DATA_CURRENT` gives the easy handle of the current
* invocation.
*/
struct cf_call_data {
struct Curl_easy *data;
#ifdef DEBUGBUILD
int depth;
#endif
};
/**
* define to access the `struct cf_call_data for a cfilter. Normally
* a member in the cfilter's `ctx`.
*
* #define CF_CTX_CALL_DATA(cf) -> struct cf_call_data instance
*/
#ifdef DEBUGBUILD
#define CF_DATA_SAVE(save, cf, data) \
do { \
(save) = CF_CTX_CALL_DATA(cf); \
DEBUGASSERT(!(save).data || (save).depth > 0); \
CF_CTX_CALL_DATA(cf).depth++; \
CF_CTX_CALL_DATA(cf).data = (struct Curl_easy *)CURL_UNCONST(data); \
} while(0)
#define CF_DATA_RESTORE(cf, save) \
do { \
DEBUGASSERT(CF_CTX_CALL_DATA(cf).depth == (save).depth + 1); \
DEBUGASSERT(!(save).data || (save).depth > 0); \
CF_CTX_CALL_DATA(cf) = (save); \
} while(0)
#else /* DEBUGBUILD */
#define CF_DATA_SAVE(save, cf, data) \
do { \
(save) = CF_CTX_CALL_DATA(cf); \
CF_CTX_CALL_DATA(cf).data = (struct Curl_easy *)CURL_UNCONST(data); \
} while(0)
#define CF_DATA_RESTORE(cf, save) \
do { \
CF_CTX_CALL_DATA(cf) = (save); \
} while(0)
#endif /* !DEBUGBUILD */
#define CF_DATA_CURRENT(cf) ((cf) ? (CF_CTX_CALL_DATA(cf).data) : NULL)
#endif /* HEADER_CURL_CFILTERS_H */
+83
View File
@@ -0,0 +1,83 @@
#ifndef HEADER_CURL_CONFIG_MAC_H
#define HEADER_CURL_CONFIG_MAC_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
/* =================================================================== */
/* Handcrafted config file for Mac OS 9 */
/* =================================================================== */
/* On macOS you must run configure to generate curl_config.h file */
/* =================================================================== */
#ifndef CURL_OS
#define CURL_OS "mac"
#endif
#include <ConditionalMacros.h>
/* Define if you want the built-in manual */
#define USE_MANUAL 1
#define HAVE_NETINET_IN_H 1
#define HAVE_NETDB_H 1
#define HAVE_ARPA_INET_H 1
#define HAVE_UNISTD_H 1
#define HAVE_NET_IF_H 1
#define HAVE_SYS_TYPES_H 1
#define HAVE_GETTIMEOFDAY 1
#define HAVE_FCNTL_H 1
#define HAVE_UTIME_H 1
#define HAVE_SYS_UTIME_H 1
#define HAVE_SYS_IOCTL_H 1
#define HAVE_ALARM 1
#define HAVE_UTIME 1
#define HAVE_SOCKET 1
#define HAVE_STRUCT_TIMEVAL 1
#define HAVE_SIGACTION 1
#define CURL_DISABLE_LDAP
#define HAVE_IOCTL_FIONBIO 1
#define SIZEOF_INT 4
#define SIZEOF_LONG 4
#define SIZEOF_SIZE_T 4
#define SIZEOF_CURL_OFF_T 8
#define HAVE_RECV 1
#define RECV_TYPE_ARG1 int
#define RECV_TYPE_ARG2 void *
#define RECV_TYPE_ARG3 size_t
#define RECV_TYPE_ARG4 int
#define RECV_TYPE_RETV ssize_t
#define HAVE_SEND 1
#define SEND_TYPE_ARG1 int
#define SEND_TYPE_ARG2 void *
#define SEND_TYPE_ARG3 size_t
#define SEND_TYPE_ARG4 int
#define SEND_TYPE_RETV ssize_t
#endif /* HEADER_CURL_CONFIG_MAC_H */
+292
View File
@@ -0,0 +1,292 @@
#ifndef HEADER_CURL_CONFIG_OS400_H
#define HEADER_CURL_CONFIG_OS400_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
/* ================================================================ */
/* Handcrafted config file for OS/400 */
/* ================================================================ */
#pragma enum(int)
/* ---------------------------------------------------------------- */
/* Global configuration parameters: normally generated by autoconf. */
/* ---------------------------------------------------------------- */
/* Location of default CA bundle */
/* Use the system keyring as the default CA bundle. */
#define CURL_CA_BUNDLE "/QIBM/UserData/ICSS/Cert/Server/DEFAULT.KDB"
/* Definition to make a library symbol externally visible. */
#define CURL_EXTERN_SYMBOL
/* cpu-machine-OS */
#ifndef CURL_OS
#define CURL_OS "OS/400"
#endif
/* Define to 1 if you have the alarm function. */
#define HAVE_ALARM 1
/* Define if you have the <arpa/inet.h> header file. */
#define HAVE_ARPA_INET_H 1
/* if you have <dirent.h> */
#define HAVE_DIRENT_H
/* Define to 1 if you have the 'fchmod' function. */
#define HAVE_FCHMOD 1
/* Define to 1 if you have the fcntl function. */
#define HAVE_FCNTL 1
/* Define to 1 if you have the <fcntl.h> header file. */
#define HAVE_FCNTL_H 1
/* Define to 1 if you have a working fcntl O_NONBLOCK function. */
#define HAVE_FCNTL_O_NONBLOCK 1
/* Define to 1 if you have the freeaddrinfo function. */
#define HAVE_FREEADDRINFO 1
/* Define to 1 if you have a working getaddrinfo function. */
#define HAVE_GETADDRINFO 1
/* Define to 1 if the getaddrinfo function is thread-safe. */
#define HAVE_GETADDRINFO_THREADSAFE 1
/* Define to 1 if you have the 'geteuid' function. */
#define HAVE_GETEUID 1
/* Define to 1 if you have the gethostname function. */
#define HAVE_GETHOSTNAME 1
/* Define to 1 if you have the getpeername function. */
#define HAVE_GETPEERNAME 1
/* Define to 1 if you have the 'getppid' function. */
#define HAVE_GETPPID 1
/* Define to 1 if you have the 'getpwuid' function. */
#define HAVE_GETPWUID 1
/* Define to 1 if you have the getsockname function. */
#define HAVE_GETSOCKNAME 1
/* Define to 1 if you have the 'gettimeofday' function. */
#define HAVE_GETTIMEOFDAY 1
/* if you have GSS-API libraries */
#define HAVE_GSSAPI
/* Define to 1 if you have a working ioctl FIONBIO function. */
#define HAVE_IOCTL_FIONBIO 1
/* Define to 1 if you have a working ioctl SIOCGIFADDR function. */
#define HAVE_IOCTL_SIOCGIFADDR 1
/* Define to 1 if you have the lber.h header file. */
#define HAVE_LBER_H 1
/* Define to 1 if you have the ldap.h header file. */
#define HAVE_LDAP_H 1
/* Define to 1 if you have a working localtime_r function. */
#define HAVE_LOCALTIME_R 1
/* Define to 1 if you have the <netdb.h> header file. */
#define HAVE_NETDB_H 1
/* Define to 1 if you have the <netinet/in.h> header file. */
#define HAVE_NETINET_IN_H 1
/* Define to 1 if you have the <netinet/tcp.h> header file. */
#define HAVE_NETINET_TCP_H 1
/* Define to 1 if you have the <netinet/udp.h> header file. */
#define HAVE_NETINET_UDP_H 1
/* Define to 1 if you have the <net/if.h> header file. */
#define HAVE_NET_IF_H 1
/* if you have opendir */
#define HAVE_OPENDIR
/* Define to 1 if you have the 'pipe' function. */
#define HAVE_PIPE 1
/* Define to 1 if you have the <pwd.h> header file. */
#define HAVE_PWD_H 1
/* Define to 1 if you have the recv function. */
#define HAVE_RECV 1
/* Define to 1 if symbol `sa_family_t' exists */
#define HAVE_SA_FAMILY_T 1
/* Define to 1 if you have the send function. */
#define HAVE_SEND 1
/* Define to 1 if you have the 'sendmsg' function. */
#define HAVE_SENDMSG 1
/* Define to 1 if you have the sigaction function. */
#define HAVE_SIGACTION 1
/* Define to 1 if struct sockaddr_in6 has the sin6_scope_id member */
#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
/* Define to 1 if you have the socketpair function. */
#define HAVE_SOCKET 1
/* Define to 1 if you have the <stdbool.h> header file. */
#define HAVE_STDBOOL_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdio.h> header file. */
#define HAVE_STDIO_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the stricmp function. */
#define HAVE_STRICMP 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* if struct sockaddr_storage is defined */
#define HAVE_STRUCT_SOCKADDR_STORAGE
/* Define to 1 if you have the timeval struct. */
#define HAVE_STRUCT_TIMEVAL 1
/* Define to 1 if you have the <sys/ioctl.h> header file. */
#define HAVE_SYS_IOCTL_H 1
/* Define to 1 if you have the <sys/param.h> header file. */
#define HAVE_SYS_PARAM_H 1
/* Define to 1 if you have the <sys/resource.h> header file. */
#define HAVE_SYS_RESOURCE_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <sys/un.h> header file. */
#define HAVE_SYS_UN_H 1
/* Define to 1 if you have the <unicode/uidna.h> header file. */
#define HAVE_UNICODE_UIDNA_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if you have the 'utime' function. */
#define HAVE_UTIME 1
/* Define to 1 if you have the <utime.h> header file. */
#define HAVE_UTIME_H 1
/* Size of curl_off_t in number of bytes */
#define SIZEOF_CURL_OFF_T 8
/* Size of curl_socket_t in number of bytes */
#define SIZEOF_CURL_SOCKET_T 4
/* Size of int in number of bytes */
#define SIZEOF_INT 4
/* Size of long in number of bytes */
#define SIZEOF_LONG 4
/* Size of off_t in number of bytes */
#define SIZEOF_OFF_T 8 /* _LARGE_FILES (*IFS64IO) version. */
/* Size of size_t in number of bytes */
#define SIZEOF_SIZE_T 4
/* Size of time_t in number of bytes */
#define SIZEOF_TIME_T 4
/* Define if you want to enable IPv6 support */
#define USE_IPV6
/* Use Unix domain sockets */
#define USE_UNIX_SOCKETS
/* Define to 1 if OS is AIX. */
#ifndef _ALL_SOURCE
# undef _ALL_SOURCE
#endif
/* ---------------------------------------------------------------- */
/* recv/send parameter types (see lib/functypes.h) */
/* ---------------------------------------------------------------- */
/* int recv(int, char *, int, int); */
#define RECV_TYPE_ARG1 int
#define RECV_TYPE_ARG2 char *
#define RECV_TYPE_ARG3 int
#define RECV_TYPE_ARG4 int
#define RECV_TYPE_RETV int
/* int send(int, char *, int, int); */
#define SEND_TYPE_ARG1 int
#define SEND_NONCONST_ARG2
#define SEND_TYPE_ARG2 char *
#define SEND_TYPE_ARG3 int
#define SEND_TYPE_ARG4 int
#define SEND_TYPE_RETV int
/* ---------------------------------------------------------------- */
/* Additional definitions specific to OS/400 */
/* ---------------------------------------------------------------- */
/* The <gssapi.h> header file is in the main system include directory. */
#define HAVE_GSSAPI_H
/* Define to use the OS/400 crypto library. */
#define USE_OS400CRYPTO
/* The following definition is required on OS/400 to enable strcmpi(),
stricmp() and strdup(). */
#define __cplusplus__strings__
/* The following must be defined BEFORE system header files inclusion. */
#define __ptr128 /* No teraspace. */
#define qadrt_use_fputc_inline /* Generate fputc() wrapper inline. */
#define qadrt_use_fread_inline /* Generate fread() wrapper inline. */
#define qadrt_use_fwrite_inline /* Generate fwrite() wrapper inline. */
#endif /* HEADER_CURL_CONFIG_OS400_H */
+123
View File
@@ -0,0 +1,123 @@
#ifndef HEADER_CURL_CONFIG_WIN32_H
#define HEADER_CURL_CONFIG_WIN32_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
/* Handcrafted config file for building via Visual Studio IDE Project Files */
#if !defined(_MSC_VER) || _MSC_VER > 1800
#error This manual configuration requires MSVC 2010-2013 (IDE Project builds)
#endif
/*
* Headers and functions
*/
#define HAVE_FCNTL_H 1
#define HAVE_IO_H 1
#define HAVE_LOCALE_H 1
#if _MSC_VER >= 1800
#define HAVE_STDBOOL_H 1
#define HAVE_BOOL_T 1
#endif
#define HAVE_SYS_TYPES_H 1
#define HAVE_SYS_UTIME_H 1
#define HAVE_CLOSESOCKET 1
#define HAVE_FREEADDRINFO 1
#define HAVE_GETADDRINFO 1
#define HAVE_GETADDRINFO_THREADSAFE 1
#define HAVE_GETHOSTNAME 1
#define HAVE_GETPEERNAME 1
#define HAVE_GETSOCKNAME 1
#define HAVE_IOCTLSOCKET 1
#define HAVE_IOCTLSOCKET_FIONBIO 1
#define HAVE_SETLOCALE 1
#define HAVE_SOCKET 1
#define HAVE_UTIME 1
#define HAVE_RECV 1
#define RECV_TYPE_ARG1 SOCKET
#define RECV_TYPE_ARG2 char *
#define RECV_TYPE_ARG3 int
#define RECV_TYPE_ARG4 int
#define RECV_TYPE_RETV int
#define HAVE_SEND 1
#define SEND_TYPE_ARG1 SOCKET
#define SEND_TYPE_ARG2 char *
#define SEND_TYPE_ARG3 int
#define SEND_TYPE_ARG4 int
#define SEND_TYPE_RETV int
#define HAVE_SIGNAL 1
/*
* Types and sizes
*/
#define SIZEOF_INT 4
#define SIZEOF_LONG 4
#ifdef _WIN64
# define SIZEOF_SIZE_T 8
# define ssize_t __int64
#else
# define SIZEOF_SIZE_T 4
# define ssize_t int
#endif
#define SIZEOF_CURL_OFF_T 8
/* Default to 64-bit time_t unless _USE_32BIT_TIME_T is defined */
#ifndef _USE_32BIT_TIME_T
# define SIZEOF_TIME_T 8
#else
# define SIZEOF_TIME_T 4
#endif
#define SIZEOF_OFF_T 4
#define HAVE_STRUCT_SOCKADDR_STORAGE 1
#define HAVE_STRUCT_TIMEVAL 1
#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
/*
* Additional definitions
*/
/* Default define to enable threaded asynchronous DNS lookups. */
#if !defined(USE_RESOLV_THREADED) && !defined(USE_SYNC_DNS)
# define USE_RESOLV_THREADED 1
#endif
#define HAVE_LDAP_SSL 1
#define USE_WIN32_LDAP 1
#define USE_WIN32_CRYPTO 1
#define USE_UNIX_SOCKETS 1
#ifndef CURL_OS
# ifdef _M_IX86
# define CURL_OS "i386-pc-win32"
# elif defined(_M_X64)
# define CURL_OS "x86_64-pc-win32"
# else
# define CURL_OS "unknown-pc-win32"
# endif
#endif
#endif /* HEADER_CURL_CONFIG_WIN32_H */
File diff suppressed because it is too large Load Diff
+174
View File
@@ -0,0 +1,174 @@
#ifndef HEADER_CURL_CONNCACHE_H
#define HEADER_CURL_CONNCACHE_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
* Copyright (C) Linus Nielsen Feltzing, <linus@haxx.se>
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "uint-bset.h"
#include "uint-table.h"
#include "curlx/timeval.h"
struct connectdata;
struct Curl_easy;
struct curl_pollfds;
struct Curl_waitfds;
struct Curl_multi;
struct Curl_share;
/**
* Close and destroy the connection.
* If the connection is in a cpool, remove it.
* If a `cshutdn` is available (e.g. data has a multi handle),
* pass the connection to that for controlled shutdown.
* Otherwise terminate it right away.
* Takes ownership of `conn`.
* `data` should not be attached to a connection.
*/
void Curl_conn_close(struct Curl_easy *data,
struct connectdata *conn,
bool aborted);
struct cpool {
struct uint32_tbl conns; /* connections added to this pool */
struct uint32_bset idles; /* pool_ids of conns being idle */
struct Curl_hash dest2bundle; /* conn destination sets */
curl_off_t next_connection_id;
curl_off_t next_easy_id;
struct curltime last_cleanup;
struct Curl_share *share; /* != NULL if pool belongs to share */
BIT(locked);
BIT(initialized);
BIT(in_shutdown);
};
/* Get connection pool instance for data or NULL if none exists */
struct cpool *Curl_cpool_get_instance(struct Curl_easy *data);
/* Init the pool, pass multi only if pool is owned by it.
* Cannot fail.
*/
void Curl_cpool_init(struct cpool *cpool,
struct Curl_share *share,
size_t size);
/* Destroy all connections and free all members */
void Curl_cpool_destroy(struct cpool *cpool,
struct Curl_easy *admin);
/* Init the transfer to be used within its connection pool.
* Assigns `data->id`. */
void Curl_cpool_xfer_init(struct Curl_easy *data);
/* Get the connection last used by data,
* if there was one and it still exists. */
struct connectdata *Curl_cpool_get_last_conn(struct Curl_easy *data);
/* Add the connection to the pool. */
CURLcode Curl_cpool_add(struct Curl_easy *data,
struct connectdata *conn,
uint32_t max_total,
uint32_t max_host,
const struct curltime *pnow) WARN_UNUSED_RESULT;
/* Connection was used at the given time. */
void Curl_cpool_conn_was_used(struct Curl_easy *data,
struct connectdata *conn,
const struct curltime *pnow);
/* Return connection age in milliseconds since its creation. */
timediff_t Curl_cpool_conn_age_ms(struct Curl_easy *data,
struct connectdata *conn,
const struct curltime *pnow);
typedef enum {
CPOOL_MATCH_FOUND, /* The passed `conn` matches, stop looking further */
CPOOL_MATCH_CONT, /* No match, continue looking */
CPOOL_MATCH_CLOSE, /* No match, close `conn`, continue looking */
CPOOL_MATCH_TOO_OLD /* No match, `conn` is too old, close when idle */
} cpool_match_result;
/* Return of conn is suitable. If so, stops iteration. */
typedef cpool_match_result
Curl_cpool_conn_match_cb(struct connectdata *conn, void *userdata);
/* Act on the result of the find, may override it. */
typedef bool Curl_cpool_done_match_cb(void *userdata);
/**
* Find a connection in the pool matching `destination`.
* All callbacks are invoked while the pool's lock is held.
* @param data current transfer
* @param destination match against `conn->destination` in pool
* @param prune_dead perform reaping of dead connections at start
* @param pnow timestamp of operation
* @param conn_cb must be present, called for each connection in the
* bundle until it returns TRUE
* @return combined result of last conn_db and result_cb or FALSE if no
connections were present.
*/
bool Curl_cpool_find(struct Curl_easy *data,
const char *destination,
bool prune_dead,
const struct curltime *pnow,
Curl_cpool_conn_match_cb *conn_cb,
Curl_cpool_done_match_cb *done_cb,
void *userdata);
/**
* Perform upkeep actions on connections in the transfer's pool.
*/
CURLcode Curl_cpool_upkeep(struct Curl_easy *data);
typedef enum {
CPOOL_DO_KEEP, /* Keep the connection, still in use */
CPOOL_DO_IDLE, /* Connection is idle, may get closed now */
CPOOL_DO_CLOSE, /* Close the connection (clean) */
CPOOL_DO_TERMINATE /* Terminate the connection (unclean) */
} cpool_do_result;
typedef cpool_do_result Curl_cpool_return_cb(struct Curl_easy *data,
struct connectdata *conn,
void *cbdata,
const struct curltime *pnow);
/**
* Invoked the callback for the given data + connection under the
* connection pool's lock.
* The callback is always invoked, even if the transfer has no connection
* pool associated.
*/
void Curl_cpool_return(struct Curl_easy *data,
struct connectdata *conn,
Curl_cpool_return_cb *cb, void *cbdata,
const struct curltime *pnow);
/* Close all unused connections, prevent reuse of existing ones. */
void Curl_cpool_nw_changed(struct cpool *cpool, struct Curl_easy *admin);
/* Return TRUE iff the given connection is considered healthy, e.g.
* usable for more transfers. */
bool Curl_cpool_conn_seems_healthy(struct connectdata *conn,
struct Curl_easy *data,
const struct curltime *pnow);
#endif /* HEADER_CURL_CONNCACHE_H */
+415
View File
@@ -0,0 +1,415 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include "urldata.h"
#include "curl_trc.h"
#include "strerror.h"
#include "cfilters.h"
#include "connect.h"
#include "cf-https-connect.h"
#include "cf-setup.h"
#include "multiif.h"
#include "progress.h"
#include "conncache.h"
#include "multihandle.h"
#include "select.h"
#include "vdns/cf-dns.h"
#include "curlx/strparse.h"
#if !defined(CURL_DISABLE_ALTSVC) || defined(USE_HTTPSRR)
enum alpnid Curl_alpn2alpnid(const unsigned char *name, size_t len)
{
if(len == 2) {
if(!memcmp(name, "h1", 2))
return ALPN_h1;
if(!memcmp(name, "h2", 2))
return ALPN_h2;
if(!memcmp(name, "h3", 2))
return ALPN_h3;
}
else if(len == 8 && !memcmp(name, "http/1.1", 8))
return ALPN_h1;
return ALPN_none; /* unknown, probably rubbish input */
}
#endif
/*
* timeleft_now_ms() returns the amount of milliseconds left allowed for the
* transfer/connection. If the value is 0, there is no timeout (ie there is
* infinite time left). If the value is negative, the timeout time has already
* elapsed.
*
* @unittest 1303
*/
UNITTEST timediff_t timeleft_now_ms(struct Curl_easy *data,
const struct curltime *pnow);
UNITTEST timediff_t timeleft_now_ms(struct Curl_easy *data,
const struct curltime *pnow)
{
timediff_t timeleft_ms = 0;
timediff_t ctimeleft_ms = 0;
if(data->conn && CURL_CONN_IN_SHUTDOWN(data->conn, FIRSTSOCKET))
return Curl_cshutdn_timeleft_ms(data, data->conn, FIRSTSOCKET);
else if(Curl_is_connecting(data)) {
timediff_t ctimeout_ms = (data->set.connecttimeout > 0) ?
data->set.connecttimeout : DEFAULT_CONNECT_TIMEOUT;
ctimeleft_ms = ctimeout_ms -
Curl_pgrs_since_ms(data, pnow, TIMER_STARTSINGLE);
if(!ctimeleft_ms)
ctimeleft_ms = -1; /* 0 is "no limit", fake 1 ms expiry */
}
else if(!data->set.timeout || data->set.connect_only) {
return 0; /* no timeout in place or checked, return "no limit" */
}
if(data->set.timeout) {
timeleft_ms = data->set.timeout -
Curl_pgrs_since_ms(data, pnow, TIMER_STARTOP);
if(!timeleft_ms)
timeleft_ms = -1; /* 0 is "no limit", fake 1 ms expiry */
}
if(!ctimeleft_ms)
return timeleft_ms;
else if(!timeleft_ms)
return ctimeleft_ms;
return CURLMIN(ctimeleft_ms, timeleft_ms);
}
timediff_t Curl_timeleft_ms(struct Curl_easy *data)
{
return timeleft_now_ms(data, Curl_pgrs_now(data));
}
timediff_t Curl_timeleft_now_ms(struct Curl_easy *data,
const struct curltime *pnow)
{
return timeleft_now_ms(data, pnow);
}
/*
* Used to extract socket and connectdata struct for the most recent
* transfer on the given Curl_easy.
*
* The returned socket will be CURL_SOCKET_BAD in case of failure!
*/
curl_socket_t Curl_getconnectinfo(struct Curl_easy *data,
struct connectdata **connp)
{
/* this works for an easy handle:
* - that has been used for curl_easy_perform()
* - that is associated with a multi handle, and whose connection
* was detached with CURLOPT_CONNECT_ONLY
*/
struct connectdata *conn = Curl_cpool_get_last_conn(data);
if(connp)
*connp = conn;
return conn ? conn->sock[FIRSTSOCKET] : CURL_SOCKET_BAD;
}
void Curl_conncontrol(struct connectdata *conn, int ctrl)
{
if(!conn) {
DEBUGASSERT(0);
return;
}
switch(ctrl) {
case CONNCTRL_CONN_KEEP:
conn->bits.close = FALSE;
break;
case CONNCTRL_CONN_CLOSE:
conn->bits.close = TRUE;
break;
case CONNCTRL_STREAM_CLOSE:
/* stream close when multiplexing does not affect connection */
if(!Curl_conn_is_multiplex(conn, FIRSTSOCKET))
conn->bits.close = TRUE;
break;
default:
DEBUGASSERT(0);
break;
}
}
CURLcode Curl_conn_setup(struct Curl_easy *data,
struct connectdata *conn,
int8_t sockindex,
int ssl_mode)
{
struct Curl_peer *first_peer = Curl_conn_get_first_peer(conn, sockindex);
CURLcode result = CURLE_OK;
uint8_t dns_queries;
DEBUGASSERT(data);
DEBUGASSERT(conn->scheme);
DEBUGASSERT(!conn->cfilter[sockindex]);
if(!first_peer)
return CURLE_FAILED_INIT;
#ifndef CURL_DISABLE_HTTP
if(!conn->cfilter[sockindex] &&
conn->scheme->protocol == CURLPROTO_HTTPS) {
DEBUGASSERT(ssl_mode != CURL_CF_SSL_DISABLE);
result = Curl_cf_https_setup(
data, Curl_conn_get_destination(conn, sockindex), conn, sockindex);
if(result)
goto out;
}
#endif /* !CURL_DISABLE_HTTP */
/* Still no cfilter set, apply default. */
if(!conn->cfilter[sockindex]) {
result = Curl_cf_setup_add(data, conn, sockindex,
conn->transport_wanted, ssl_mode);
if(result)
goto out;
}
/* Whatever the filter chain will be in the end, it will need the
* resolving of `first_peer`. Add that now so the resolve is started
* right away. */
dns_queries = Curl_resolv_dns_queries(data, conn->ip_version);
result = Curl_conn_dns_add_addr_resolve(data, conn, sockindex,
first_peer, dns_queries,
conn->transport_wanted);
if(result)
goto out;
DEBUGASSERT(conn->cfilter[sockindex]);
out:
return result;
}
#ifdef CURLVERBOSE
static CURLcode conn_connect_trace(struct Curl_easy *data,
struct Curl_cfilter *cf)
{
if(Curl_trc_is_verbose(data)) {
struct ip_quadruple ipquad;
bool is_ipv6;
CURLcode result;
result = Curl_conn_cf_get_ip_info(cf, data, &is_ipv6, &ipquad);
if(result)
return result;
infof(data, "Established %sconnection to %s (%s port %u) from %s port %u ",
(cf->sockindex == SECONDARYSOCKET) ? "2nd " : "",
CURL_CONN_HOST_DISPNAME(data->conn),
ipquad.remote_ip, ipquad.remote_port,
ipquad.local_ip, ipquad.local_port);
}
return CURLE_OK;
}
#endif
/**
* Update connection statistics
*/
static void conn_report_stats(struct Curl_easy *data, int sockindex)
{
/* We do gather stats for the second socket...yet */
if(sockindex == FIRSTSOCKET) {
Curl_conn_cntrl_report_stats(data, data->conn, sockindex);
}
}
void Curl_conn_report_failed(struct Curl_easy *data, int8_t sockindex)
{
if(!data->conn || (sockindex != FIRSTSOCKET))
return;
/* Only filters connected at IP level have info to update. Filters
* still racing for a connection, like happy eyeballing, pass it on
* to a connected one only. */
(void)Curl_conn_cf_cntrl(data->conn->cfilter[sockindex], data, TRUE,
CF_CTRL_CONN_INFO_UPDATE, 0, NULL);
conn_report_stats(data, sockindex);
}
CURLcode Curl_conn_connect(struct Curl_easy *data,
int8_t sockindex,
bool blocking,
bool *done)
{
#define CF_CONN_NUM_POLLS_ON_STACK 5
struct pollfd a_few_on_stack[CF_CONN_NUM_POLLS_ON_STACK];
struct easy_pollset ps;
struct curl_pollfds cpfds;
struct Curl_cfilter *cf;
CURLcode result = CURLE_OK;
DEBUGASSERT(data);
DEBUGASSERT(data->conn);
if(!CONN_SOCK_IDX_VALID(sockindex))
return CURLE_BAD_FUNCTION_ARGUMENT;
if(data->conn->scheme->flags & PROTOPT_NONETWORK) {
*done = TRUE;
return CURLE_OK;
}
cf = data->conn->cfilter[sockindex];
if(!cf) {
*done = FALSE;
return CURLE_FAILED_INIT;
}
*done = (bool)cf->connected;
if(*done)
return CURLE_OK;
Curl_pollset_init(&ps);
Curl_pollfds_init(&cpfds, a_few_on_stack, CF_CONN_NUM_POLLS_ON_STACK);
while(!*done) {
if(Curl_conn_needs_flush(data, sockindex)) {
DEBUGF(infof(data, "Curl_conn_connect(index=%d), flush", sockindex));
result = Curl_conn_flush(data, sockindex);
if(result && (result != CURLE_AGAIN))
goto out;
}
result = cf->cft->do_connect(cf, data, done);
CURL_TRC_CF(data, cf, "Curl_conn_connect(block=%d) -> %d, done=%d",
blocking, (int)result, *done);
if(!result && *done) {
/* A final sanity check on connection security */
if((data->state.origin->scheme->flags & PROTOPT_SSL) &&
(sockindex == FIRSTSOCKET) &&
!Curl_conn_is_ssl(data->conn, FIRSTSOCKET)) {
DEBUGASSERT(0);
failf(data, "transfer requires SSL, but not connected via SSL");
result = CURLE_FAILED_INIT;
goto out;
}
/* Now that the complete filter chain is connected, let all filters
* persist information at the connection. E.g. cf-socket sets the
* socket and ip related information. */
Curl_conn_cntrl_update_info(data, data->conn);
conn_report_stats(data, sockindex);
Curl_cpool_conn_was_used(data, data->conn, Curl_pgrs_now(data));
VERBOSE(result = conn_connect_trace(data, cf));
VERBOSE(Curl_conn_trc_filters(data, sockindex, "connected"));
Curl_conn_remove_setup_filters(data, sockindex);
VERBOSE(Curl_conn_trc_filters(data, sockindex, "reduced to"));
goto out;
}
else if(result) {
CURL_TRC_CF(data, cf, "Curl_conn_connect(), filter returned %d",
(int)result);
VERBOSE(Curl_conn_trc_filters(data, sockindex, "failed to connect"));
Curl_conn_report_failed(data, sockindex);
goto out;
}
if(!blocking)
goto out;
else {
/* check allowed time left */
const timediff_t timeout_ms = Curl_timeleft_ms(data);
curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
int rc;
if(timeout_ms < 0) {
/* no need to continue if time already is up */
failf(data, "connect timeout");
result = CURLE_OPERATION_TIMEDOUT;
goto out;
}
CURL_TRC_CF(data, cf, "Curl_conn_connect(block=1), do poll");
Curl_pollset_reset(&ps);
Curl_pollfds_reset(&cpfds);
/* In general, we want to send after connect, wait on that. */
if(sockfd != CURL_SOCKET_BAD)
result = Curl_pollset_set_out_only(data, &ps, sockfd);
if(!result)
result = Curl_conn_adjust_pollset(data, data->conn, &ps);
if(result)
goto out;
result = Curl_pollfds_add_ps(&cpfds, &ps);
if(result)
goto out;
rc = Curl_poll(cpfds.pfds, cpfds.n,
CURLMIN(timeout_ms ? timeout_ms : 1000,
(cpfds.n ? 1000 : 10)));
CURL_TRC_CF(data, cf, "Curl_conn_connect(block=1), Curl_poll() -> %d",
rc);
if(rc < 0) {
result = CURLE_COULDNT_CONNECT;
goto out;
}
/* continue iterating */
}
}
out:
Curl_pollset_cleanup(&ps);
Curl_pollfds_cleanup(&cpfds);
return result;
}
void Curl_conn_set_multiplex(struct connectdata *conn)
{
if(!conn->bits.multiplex) {
conn->bits.multiplex = TRUE;
if(conn->attached_multi) {
Curl_multi_connchanged(conn->attached_multi);
}
}
}
struct Curl_peer *Curl_conn_get_origin(struct connectdata *conn,
int8_t sockindex)
{
return (sockindex == SECONDARYSOCKET) ?
conn->origin2 : conn->origin;
}
struct Curl_peer *Curl_conn_get_destination(struct connectdata *conn,
int8_t sockindex)
{
return (sockindex == SECONDARYSOCKET) ?
(conn->via_peer2 ? conn->via_peer2 : conn->origin2) :
(conn->via_peer ? conn->via_peer : conn->origin);
}
struct Curl_peer *Curl_conn_get_first_peer(struct connectdata *conn,
int8_t sockindex)
{
#ifndef CURL_DISABLE_PROXY
if(conn->socks_proxy.peer)
return conn->socks_proxy.peer;
if(conn->http_proxy.peer)
return conn->http_proxy.peer;
#endif
return (sockindex == SECONDARYSOCKET) ?
(conn->via_peer2 ? conn->via_peer2 : conn->origin2) :
(conn->via_peer ? conn->via_peer : conn->origin);
}
+117
View File
@@ -0,0 +1,117 @@
#ifndef HEADER_CURL_CONNECT_H
#define HEADER_CURL_CONNECT_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include "vdns/hostip.h"
#include "curlx/timeval.h"
struct Curl_peer;
struct Curl_str;
enum alpnid Curl_alpn2alpnid(const unsigned char *name, size_t len);
/* generic function that returns how much time there is left to run, according
to the timeouts set */
timediff_t Curl_timeleft_ms(struct Curl_easy *data);
timediff_t Curl_timeleft_now_ms(struct Curl_easy *data,
const struct curltime *pnow);
#define DEFAULT_CONNECT_TIMEOUT 300000 /* milliseconds == five minutes */
/*
* Used to extract socket and connectdata struct for the most recent
* transfer on the given Curl_easy.
*
* The returned socket will be CURL_SOCKET_BAD in case of failure!
*/
curl_socket_t Curl_getconnectinfo(struct Curl_easy *data,
struct connectdata **connp);
/*
* Curl_conncontrol() manipulates the `conn->bits.close` bit on
* a connection:
* - CONNCTRL_CONN_KEEP: clear the bit
* - CONNCTRL_CONN_CLOSE: set the bit
* - CONNCTRL_STREAM_CLOSE: set the bit when the connection is not
* multiplexed
* The call does *NOT* cause any immediate connection close.
*/
#define CONNCTRL_CONN_KEEP 0
#define CONNCTRL_CONN_CLOSE 1
#define CONNCTRL_STREAM_CLOSE 2
void Curl_conncontrol(struct connectdata *conn, int ctrl);
#define streamclose(x) Curl_conncontrol((x), CONNCTRL_STREAM_CLOSE)
#define connclose(x) Curl_conncontrol((x), CONNCTRL_CONN_CLOSE)
#define connkeep(x) Curl_conncontrol((x), CONNCTRL_CONN_KEEP)
/**
* Setup the cfilters at `sockindex` in connection `conn`.
* If no filter chain is installed yet, inspects the configuration
* in `data` and `conn` to install a suitable filter chain.
*/
CURLcode Curl_conn_setup(struct Curl_easy *data,
struct connectdata *conn,
int8_t sockindex,
int ssl_mode);
/**
* Bring the filter chain at `sockindex` for connection `data->conn` into
* connected state. Which will set `*done` to TRUE.
* This can be called on an already connected chain with no side effects.
* When not `blocking`, calls may return without error and `*done != TRUE`,
* while the individual filters negotiated the connection.
*/
CURLcode Curl_conn_connect(struct Curl_easy *data, int8_t sockindex,
bool blocking, bool *done);
/**
* The filter chain at `sockindex` failed to connect, e.g. the TLS handshake
* timed out. Let the filters that did connect, like the TCP socket, report
* their IP information and stats to the transfer.
*/
void Curl_conn_report_failed(struct Curl_easy *data, int8_t sockindex);
/* Set conn to allow multiplexing. */
void Curl_conn_set_multiplex(struct connectdata *conn);
/* Get the origin peer at sockindex. */
struct Curl_peer *Curl_conn_get_origin(struct connectdata *conn,
int8_t sockindex);
/* Get the peer the connection actually connects to at sockindex.
* Often the same as "origin", but can be redirected via "connect-to"
* or "alt-svc". May tunnel through proxies. */
struct Curl_peer *Curl_conn_get_destination(struct connectdata *conn,
int8_t sockindex);
/* Get the peer curl connects its socket to.
* Can be origin, "connect-to" or the first proxy. */
struct Curl_peer *Curl_conn_get_first_peer(struct connectdata *conn,
int8_t sockindex);
#endif /* HEADER_CURL_CONNECT_H */
+877
View File
@@ -0,0 +1,877 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include "urldata.h"
#include "curlx/dynbuf.h"
#ifdef HAVE_LIBZ
#include <zlib.h>
#endif
#ifdef HAVE_BROTLI
#ifdef CURL_HAVE_DIAG
/* Ignore -Wvla warnings in brotli headers */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wvla"
#endif
#include <brotli/decode.h>
#ifdef CURL_HAVE_DIAG
#pragma GCC diagnostic pop
#endif
#endif
#ifdef HAVE_ZSTD
#include <zstd.h>
#endif
#include "connect.h"
#include "sendf.h"
#include "curl_trc.h"
#include "content_encoding.h"
#define CONTENT_ENCODING_DEFAULT "identity"
#ifndef CURL_DISABLE_HTTP
/* allow no more than 5 "chained" compression steps */
#define MAX_ENCODE_STACK 5
#if defined(HAVE_LIBZ) || defined(HAVE_BROTLI) || defined(HAVE_ZSTD)
#define DECOMPRESS_BUFFER_SIZE 16384 /* buffer size for decompressed data */
#endif
#ifdef HAVE_LIBZ
#if !defined(ZLIB_VERNUM) || (ZLIB_VERNUM < 0x1252)
#error "zlib 1.2.5.2 or greater required"
#endif
typedef enum {
ZLIB_UNINIT, /* uninitialized */
ZLIB_INIT, /* initialized */
ZLIB_INFLATING, /* inflating started. */
ZLIB_EXTERNAL_TRAILER, /* reading external trailer */
ZLIB_INIT_GZIP /* initialized in transparent gzip mode */
} zlibInitState;
/* Deflate and gzip writer. */
struct zlib_writer {
struct Curl_cwriter super;
zlibInitState zlib_init; /* zlib init state */
char buffer[DECOMPRESS_BUFFER_SIZE]; /* Put the decompressed data here. */
uInt trailerlen; /* Remaining trailer byte count. */
z_stream z; /* State structure for zlib. */
};
static voidpf zalloc_cb(voidpf opaque, unsigned int items, unsigned int size)
{
(void)opaque;
/* not a typo, keep it curlx_calloc() */
return curlx_calloc(items, size);
}
static void zfree_cb(voidpf opaque, voidpf ptr)
{
(void)opaque;
curlx_free(ptr);
}
static CURLcode process_zlib_error(struct Curl_easy *data, z_stream *z)
{
if(z->msg)
failf(data, "Error while processing content unencoding: %s", z->msg);
else
failf(data, "Error while processing content unencoding: "
"Unknown failure within decompression software.");
return CURLE_BAD_CONTENT_ENCODING;
}
static CURLcode exit_zlib(struct Curl_easy *data, z_stream *z,
zlibInitState *zlib_init, CURLcode result)
{
if(*zlib_init != ZLIB_UNINIT) {
if(inflateEnd(z) != Z_OK && result == CURLE_OK)
result = process_zlib_error(data, z);
*zlib_init = ZLIB_UNINIT;
}
return result;
}
static CURLcode process_trailer(struct Curl_easy *data, struct zlib_writer *zp)
{
z_stream *z = &zp->z;
CURLcode result = CURLE_OK;
uInt len = z->avail_in < zp->trailerlen ? z->avail_in : zp->trailerlen;
/* Consume expected trailer bytes. Terminate stream if exhausted.
Issue an error if unexpected bytes follow. */
zp->trailerlen -= len;
z->avail_in -= len;
z->next_in += len;
if(z->avail_in)
result = CURLE_WRITE_ERROR;
if(result || !zp->trailerlen)
result = exit_zlib(data, z, &zp->zlib_init, result);
else {
/* Only occurs for gzip with zlib < 1.2.0.4 or raw deflate. */
zp->zlib_init = ZLIB_EXTERNAL_TRAILER;
}
return result;
}
static CURLcode inflate_stream(struct Curl_easy *data,
struct Curl_cwriter *writer, int type,
zlibInitState started)
{
struct zlib_writer *zp = (struct zlib_writer *)writer;
z_stream *z = &zp->z; /* zlib state structure */
uInt nread = z->avail_in;
z_const Bytef *orig_in = z->next_in;
bool done = FALSE;
CURLcode result = CURLE_OK; /* Curl_client_write status */
int i = 0;
/* Check state. */
if(zp->zlib_init != ZLIB_INIT &&
zp->zlib_init != ZLIB_INFLATING &&
zp->zlib_init != ZLIB_INIT_GZIP)
return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR);
/* because the buffer size is fixed, iteratively decompress and transfer to
the client via next_write function. */
while(!done) {
int status; /* zlib status */
done = TRUE;
if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) {
/* check every MB of output if we are not exceeding time limit */
i = 0;
if(Curl_timeleft_ms(data) < 0) {
failf(data, "Operation timed out while decoding payload");
return exit_zlib(data, z, &zp->zlib_init, CURLE_OPERATION_TIMEDOUT);
}
}
/* (re)set buffer for decompressed output for every iteration */
z->next_out = (Bytef *)zp->buffer;
z->avail_out = DECOMPRESS_BUFFER_SIZE;
status = inflate(z, Z_BLOCK);
/* Flush output data if some. */
if(z->avail_out != DECOMPRESS_BUFFER_SIZE) {
if(status == Z_OK || status == Z_STREAM_END) {
zp->zlib_init = started; /* Data started. */
result = Curl_cwriter_write(data, writer->next, type, zp->buffer,
DECOMPRESS_BUFFER_SIZE - z->avail_out);
if(result) {
exit_zlib(data, z, &zp->zlib_init, result);
break;
}
}
}
/* Dispatch by inflate() status. */
switch(status) {
case Z_OK:
/* Always loop: there may be unflushed latched data in zlib state. */
done = FALSE;
break;
case Z_BUF_ERROR:
/* No more data to flush: exit loop. */
break;
case Z_STREAM_END:
if((started == ZLIB_INIT_GZIP) && (z->avail_in >= 2) &&
(z->next_in[0] == 0x1f) && (z->next_in[1] == 0x8b)) {
/* a second gzip member follows; curl does not support
multi-member gzip responses */
failf(data, "Multi-member gzip response not supported");
result = exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR);
break;
}
result = process_trailer(data, zp);
break;
case Z_DATA_ERROR:
/* some servers seem to not generate zlib headers, so this is an attempt
to fix and continue anyway */
if(zp->zlib_init == ZLIB_INIT) {
if(inflateReset2(z, -MAX_WBITS) == Z_OK) {
z->next_in = orig_in;
z->avail_in = nread;
zp->zlib_init = ZLIB_INFLATING;
zp->trailerlen = 4; /* Tolerate up to 4 unknown trailer bytes. */
done = FALSE;
break;
}
zp->zlib_init = ZLIB_UNINIT; /* inflateEnd() already called. */
}
result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));
break;
default:
result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));
break;
}
}
/* We are about to leave this call so the `nread' data bytes will not be seen
again. If we are in a state that would wrongly allow restart in raw mode
at the next call, assume output has already started. */
if(nread && zp->zlib_init == ZLIB_INIT)
zp->zlib_init = started; /* Cannot restart anymore. */
return result;
}
/* Deflate handler. */
static CURLcode deflate_do_init(struct Curl_easy *data,
struct Curl_cwriter *writer)
{
struct zlib_writer *zp = (struct zlib_writer *)writer;
z_stream *z = &zp->z; /* zlib state structure */
/* Initialize zlib */
z->zalloc = (alloc_func)zalloc_cb;
z->zfree = (free_func)zfree_cb;
if(inflateInit(z) != Z_OK)
return process_zlib_error(data, z);
zp->zlib_init = ZLIB_INIT;
return CURLE_OK;
}
static CURLcode deflate_do_write(struct Curl_easy *data,
struct Curl_cwriter *writer, int type,
const char *buf, size_t nbytes)
{
struct zlib_writer *zp = (struct zlib_writer *)writer;
z_stream *z = &zp->z; /* zlib state structure */
if(!(type & CLIENTWRITE_BODY) || !nbytes)
return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
/* Set the compressed input when this function is called */
z->next_in = (z_const Bytef *)buf;
z->avail_in = (uInt)nbytes;
if(zp->zlib_init == ZLIB_EXTERNAL_TRAILER)
return process_trailer(data, zp);
/* Now uncompress the data */
return inflate_stream(data, writer, type, ZLIB_INFLATING);
}
static void deflate_do_close(struct Curl_easy *data,
struct Curl_cwriter *writer)
{
struct zlib_writer *zp = (struct zlib_writer *)writer;
z_stream *z = &zp->z; /* zlib state structure */
exit_zlib(data, z, &zp->zlib_init, CURLE_OK);
}
static const struct Curl_cwtype deflate_encoding = {
"deflate",
NULL,
CURL_CW_FLAG_BLOWUP,
deflate_do_init,
deflate_do_write,
Curl_cwriter_def_flush,
deflate_do_close,
sizeof(struct zlib_writer)
};
/*
* Gzip handler.
*/
static CURLcode gzip_do_init(struct Curl_easy *data,
struct Curl_cwriter *writer)
{
struct zlib_writer *zp = (struct zlib_writer *)writer;
z_stream *z = &zp->z; /* zlib state structure */
/* Initialize zlib */
z->zalloc = (alloc_func)zalloc_cb;
z->zfree = (free_func)zfree_cb;
if(inflateInit2(z, MAX_WBITS + 32) != Z_OK)
return process_zlib_error(data, z);
zp->zlib_init = ZLIB_INIT_GZIP; /* Transparent gzip decompress state */
return CURLE_OK;
}
static CURLcode gzip_do_write(struct Curl_easy *data,
struct Curl_cwriter *writer, int type,
const char *buf, size_t nbytes)
{
struct zlib_writer *zp = (struct zlib_writer *)writer;
z_stream *z = &zp->z; /* zlib state structure */
if(!(type & CLIENTWRITE_BODY) || !nbytes)
return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
if(zp->zlib_init == ZLIB_INIT_GZIP) {
/* Let zlib handle the gzip decompression entirely */
z->next_in = (z_const Bytef *)buf;
z->avail_in = (uInt)nbytes;
/* Now uncompress the data */
return inflate_stream(data, writer, type, ZLIB_INIT_GZIP);
}
/* We are running with an old version: return error. */
return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR);
}
static void gzip_do_close(struct Curl_easy *data,
struct Curl_cwriter *writer)
{
struct zlib_writer *zp = (struct zlib_writer *)writer;
z_stream *z = &zp->z; /* zlib state structure */
exit_zlib(data, z, &zp->zlib_init, CURLE_OK);
}
static const struct Curl_cwtype gzip_encoding = {
"gzip",
"x-gzip",
CURL_CW_FLAG_BLOWUP,
gzip_do_init,
gzip_do_write,
Curl_cwriter_def_flush,
gzip_do_close,
sizeof(struct zlib_writer)
};
#endif /* HAVE_LIBZ */
#ifdef HAVE_BROTLI
/* Brotli writer. */
struct brotli_writer {
struct Curl_cwriter super;
char buffer[DECOMPRESS_BUFFER_SIZE];
BrotliDecoderState *br; /* State structure for brotli. */
};
static CURLcode brotli_map_error(BrotliDecoderErrorCode be)
{
switch(be) {
case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:
case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:
case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:
case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:
case BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:
case BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:
case BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:
case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:
case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:
case BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:
case BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:
case BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:
case BROTLI_DECODER_ERROR_FORMAT_PADDING_1:
case BROTLI_DECODER_ERROR_FORMAT_PADDING_2:
#ifdef BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY /* brotli v1.1.0+ */
case BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY:
#endif
case BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:
case BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:
return CURLE_BAD_CONTENT_ENCODING;
case BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:
case BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:
case BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:
case BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:
case BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:
case BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:
return CURLE_OUT_OF_MEMORY;
default:
break;
}
return CURLE_WRITE_ERROR;
}
static CURLcode brotli_do_init(struct Curl_easy *data,
struct Curl_cwriter *writer)
{
struct brotli_writer *bp = (struct brotli_writer *)writer;
(void)data;
bp->br = BrotliDecoderCreateInstance(NULL, NULL, NULL);
return bp->br ? CURLE_OK : CURLE_OUT_OF_MEMORY;
}
static CURLcode brotli_do_write(struct Curl_easy *data,
struct Curl_cwriter *writer, int type,
const char *buf, size_t nbytes)
{
struct brotli_writer *bp = (struct brotli_writer *)writer;
const uint8_t *src = (const uint8_t *)buf;
uint8_t *dst;
size_t dstleft;
CURLcode result = CURLE_OK;
BrotliDecoderResult r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
int i = 0;
if(!(type & CLIENTWRITE_BODY) || !nbytes)
return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
if(!bp->br)
return CURLE_WRITE_ERROR; /* Stream already ended. */
while((nbytes || r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) &&
result == CURLE_OK) {
if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) {
/* check every MB of output if we are not exceeding time limit */
i = 0;
if(Curl_timeleft_ms(data) < 0) {
failf(data, "Operation timed out while decoding payload");
return CURLE_OPERATION_TIMEDOUT;
}
}
dst = (uint8_t *)bp->buffer;
dstleft = DECOMPRESS_BUFFER_SIZE;
r = BrotliDecoderDecompressStream(bp->br,
&nbytes, &src, &dstleft, &dst, NULL);
result = Curl_cwriter_write(data, writer->next, type,
bp->buffer, DECOMPRESS_BUFFER_SIZE - dstleft);
if(result)
break;
switch(r) {
case BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:
case BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:
break;
case BROTLI_DECODER_RESULT_SUCCESS:
BrotliDecoderDestroyInstance(bp->br);
bp->br = NULL;
if(nbytes)
result = CURLE_WRITE_ERROR;
break;
default:
result = brotli_map_error(BrotliDecoderGetErrorCode(bp->br));
break;
}
}
return result;
}
static void brotli_do_close(struct Curl_easy *data,
struct Curl_cwriter *writer)
{
struct brotli_writer *bp = (struct brotli_writer *)writer;
(void)data;
if(bp->br) {
BrotliDecoderDestroyInstance(bp->br);
bp->br = NULL;
}
}
static const struct Curl_cwtype brotli_encoding = {
"br",
NULL,
CURL_CW_FLAG_BLOWUP,
brotli_do_init,
brotli_do_write,
Curl_cwriter_def_flush,
brotli_do_close,
sizeof(struct brotli_writer)
};
#endif
#ifdef HAVE_ZSTD
/* Zstd writer. */
struct zstd_writer {
struct Curl_cwriter super;
ZSTD_DStream *zds; /* State structure for zstd. */
char buffer[DECOMPRESS_BUFFER_SIZE];
};
#ifdef ZSTD_STATIC_LINKING_ONLY
static void *Curl_zstd_alloc(void *opaque, size_t size)
{
(void)opaque;
return Curl_cmalloc(size);
}
static void Curl_zstd_free(void *opaque, void *address)
{
(void)opaque;
Curl_cfree(address);
}
#endif
static CURLcode zstd_do_init(struct Curl_easy *data,
struct Curl_cwriter *writer)
{
struct zstd_writer *zp = (struct zstd_writer *)writer;
(void)data;
#ifdef ZSTD_STATIC_LINKING_ONLY
zp->zds = ZSTD_createDStream_advanced((ZSTD_customMem) {
.customAlloc = Curl_zstd_alloc,
.customFree = Curl_zstd_free,
.opaque = NULL
});
#else
zp->zds = ZSTD_createDStream();
#endif
return zp->zds ? CURLE_OK : CURLE_OUT_OF_MEMORY;
}
static CURLcode zstd_do_write(struct Curl_easy *data,
struct Curl_cwriter *writer, int type,
const char *buf, size_t nbytes)
{
CURLcode result = CURLE_OK;
struct zstd_writer *zp = (struct zstd_writer *)writer;
ZSTD_inBuffer in;
ZSTD_outBuffer out;
size_t errorCode;
int i = 0;
if(!(type & CLIENTWRITE_BODY) || !nbytes)
return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
in.pos = 0;
in.src = buf;
in.size = nbytes;
for(;;) {
if(++i > (1024 * 1024 / DECOMPRESS_BUFFER_SIZE)) {
/* check every MB of output if we are not exceeding time limit */
i = 0;
if(Curl_timeleft_ms(data) < 0) {
failf(data, "Operation timed out while decoding payload");
return CURLE_OPERATION_TIMEDOUT;
}
}
out.pos = 0;
out.dst = zp->buffer;
out.size = DECOMPRESS_BUFFER_SIZE;
errorCode = ZSTD_decompressStream(zp->zds, &out, &in);
if(ZSTD_isError(errorCode)) {
return CURLE_BAD_CONTENT_ENCODING;
}
if(out.pos > 0) {
result = Curl_cwriter_write(data, writer->next, type,
zp->buffer, out.pos);
if(result)
break;
}
if((in.pos == nbytes) && (out.pos < out.size))
break;
}
return result;
}
static void zstd_do_close(struct Curl_easy *data,
struct Curl_cwriter *writer)
{
struct zstd_writer *zp = (struct zstd_writer *)writer;
(void)data;
if(zp->zds) {
ZSTD_freeDStream(zp->zds);
zp->zds = NULL;
}
}
static const struct Curl_cwtype zstd_encoding = {
"zstd",
NULL,
CURL_CW_FLAG_BLOWUP,
zstd_do_init,
zstd_do_write,
Curl_cwriter_def_flush,
zstd_do_close,
sizeof(struct zstd_writer)
};
#endif
/* Identity handler. */
static const struct Curl_cwtype identity_encoding = {
"identity",
"none",
0,
Curl_cwriter_def_init,
Curl_cwriter_def_write,
Curl_cwriter_def_flush,
Curl_cwriter_def_close,
sizeof(struct Curl_cwriter)
};
/* supported general content decoders. */
static const struct Curl_cwtype * const general_unencoders[] = {
&identity_encoding,
#ifdef HAVE_LIBZ
&deflate_encoding,
&gzip_encoding,
#endif
#ifdef HAVE_BROTLI
&brotli_encoding,
#endif
#ifdef HAVE_ZSTD
&zstd_encoding,
#endif
NULL
};
/* supported content decoders only for transfer encodings */
static const struct Curl_cwtype * const transfer_unencoders[] = {
&Curl_httpchunk_unencoder,
NULL
};
/* Return the list of comma-separated names of supported encodings.
*/
char *Curl_get_content_encodings(void)
{
struct dynbuf enc;
const struct Curl_cwtype * const *cep;
CURLcode result = CURLE_OK;
curlx_dyn_init(&enc, 255);
for(cep = general_unencoders; *cep && !result; cep++) {
const struct Curl_cwtype *ce = *cep;
if(!curl_strequal(ce->name, CONTENT_ENCODING_DEFAULT)) {
if(curlx_dyn_len(&enc))
result = curlx_dyn_addn(&enc, ", ", 2);
if(!result)
result = curlx_dyn_add(&enc, ce->name);
}
}
if(!result && !curlx_dyn_len(&enc))
result = curlx_dyn_add(&enc, CONTENT_ENCODING_DEFAULT);
if(!result)
return curlx_dyn_ptr(&enc);
return NULL;
}
/* Deferred error dummy writer. */
static CURLcode error_do_init(struct Curl_easy *data,
struct Curl_cwriter *writer)
{
(void)data;
(void)writer;
return CURLE_OK;
}
static CURLcode error_do_write(struct Curl_easy *data,
struct Curl_cwriter *writer, int type,
const char *buf, size_t nbytes)
{
(void)writer;
(void)buf;
(void)nbytes;
if(!(type & CLIENTWRITE_BODY) || !nbytes)
return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
failf(data, "Unrecognized content encoding type");
return CURLE_BAD_CONTENT_ENCODING;
}
static void error_do_close(struct Curl_easy *data,
struct Curl_cwriter *writer)
{
(void)data;
(void)writer;
}
static const struct Curl_cwtype error_writer = {
"ce-error",
NULL,
0,
error_do_init,
error_do_write,
Curl_cwriter_def_flush,
error_do_close,
sizeof(struct Curl_cwriter)
};
/* Find the content encoding by name. */
static const struct Curl_cwtype *find_unencode_writer(const char *name,
size_t len,
Curl_cwriter_phase phase)
{
const struct Curl_cwtype * const *cep;
if(phase == CURL_CW_TRANSFER_DECODE) {
for(cep = transfer_unencoders; *cep; cep++) {
const struct Curl_cwtype *ce = *cep;
if((curl_strnequal(name, ce->name, len) && !ce->name[len]) ||
(ce->alias && curl_strnequal(name, ce->alias, len) &&
!ce->alias[len]))
return ce;
}
}
/* look among the general decoders */
for(cep = general_unencoders; *cep; cep++) {
const struct Curl_cwtype *ce = *cep;
if((curl_strnequal(name, ce->name, len) && !ce->name[len]) ||
(ce->alias && curl_strnequal(name, ce->alias, len) && !ce->alias[len]))
return ce;
}
return NULL;
}
/* Setup the unencoding stack from the Content-Encoding header value.
* See RFC 7231 section 3.1.2.2. */
CURLcode Curl_build_unencoding_stack(struct Curl_easy *data,
const char *enclist, int is_transfer)
{
Curl_cwriter_phase phase = is_transfer ?
CURL_CW_TRANSFER_DECODE : CURL_CW_CONTENT_DECODE;
CURLcode result;
bool has_chunked = FALSE;
do {
const char *name;
size_t namelen;
bool is_chunked = FALSE;
/* Parse a single encoding name. */
while(ISBLANK(*enclist) || *enclist == ',')
enclist++;
name = enclist;
for(namelen = 0; *enclist && *enclist != ','; enclist++)
if(*enclist > ' ')
namelen = enclist - name + 1;
if(namelen) {
const struct Curl_cwtype *cwt;
struct Curl_cwriter *writer;
CURL_TRC_WRITE(data, "looking for %s decoder: %.*s",
is_transfer ? "transfer" : "content", (int)namelen, name);
is_chunked = (is_transfer && (namelen == 7) &&
curl_strnequal(name, "chunked", 7));
/* if we skip the decoding in this phase, do not look further.
* Exception is "chunked" transfer-encoding which always must happen */
if((is_transfer && !data->set.http_transfer_encoding && !is_chunked) ||
(!is_transfer && data->set.http_ce_skip)) {
bool is_identity = (namelen == 8) &&
curl_strnequal(name, "identity", 8);
/* not requested, ignore */
CURL_TRC_WRITE(data, "decoder not requested, ignored: %.*s",
(int)namelen, name);
if(is_transfer && !data->set.http_te_skip) {
if(has_chunked)
failf(data, "A Transfer-Encoding (%.*s) was listed after chunked",
(int)namelen, name);
else if(is_identity)
continue;
else
failf(data, "Unsolicited Transfer-Encoding (%.*s) found",
(int)namelen, name);
return CURLE_BAD_CONTENT_ENCODING;
}
return CURLE_OK;
}
if(Curl_cwriter_count(data, phase) >= MAX_ENCODE_STACK) {
failf(data, "Reject response exceeding limit of %d %s encodings",
MAX_ENCODE_STACK,
is_transfer ? "transfer" : "content");
return CURLE_BAD_CONTENT_ENCODING;
}
cwt = find_unencode_writer(name, namelen, phase);
if(is_transfer && !is_chunked &&
Curl_cwriter_get_by_name(data, "chunked")) {
/* RFC 9112, ch. 6.1:
* "If any transfer coding other than chunked is applied to a
* response's content, the sender MUST either apply chunked as the
* final transfer coding or terminate the message by closing the
* connection."
* "chunked" must be the last added to be the first in its phase,
* reject this.
*/
failf(data, "Reject response due to 'chunked' not being the last "
"Transfer-Encoding");
return CURLE_BAD_CONTENT_ENCODING;
}
if(cwt && is_chunked && Curl_cwriter_get_by_type(data, cwt)) {
/* A 'chunked' transfer encoding has already been added.
* Ignore duplicates. See #13451.
* Also RFC 9112, ch. 6.1:
* "A sender MUST NOT apply the chunked transfer coding more than
* once to a message body."
*/
CURL_TRC_WRITE(data, "ignoring duplicate 'chunked' decoder");
}
else {
if(!cwt)
cwt = &error_writer; /* Defer error at use. */
result = Curl_cwriter_create(&writer, data, cwt, phase);
CURL_TRC_WRITE(data, "added %s decoder %s -> %d",
is_transfer ? "transfer" : "content", cwt->name,
(int)result);
if(result)
return result;
result = Curl_cwriter_add(data, writer);
if(result) {
Curl_cwriter_free(data, writer);
return result;
}
}
if(is_chunked)
has_chunked = TRUE;
}
} while(*enclist);
return CURLE_OK;
}
#else
/* Stubs for builds without HTTP. */
CURLcode Curl_build_unencoding_stack(struct Curl_easy *data,
const char *enclist, int is_transfer)
{
(void)data;
(void)enclist;
(void)is_transfer;
return CURLE_NOT_BUILT_IN;
}
char *Curl_get_content_encodings(void)
{
return curlx_strdup(CONTENT_ENCODING_DEFAULT);
}
#endif /* CURL_DISABLE_HTTP */
+35
View File
@@ -0,0 +1,35 @@
#ifndef HEADER_CURL_CONTENT_ENCODING_H
#define HEADER_CURL_CONTENT_ENCODING_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
struct Curl_cwriter;
/* returns an allocated string or NULL */
char *Curl_get_content_encodings(void);
CURLcode Curl_build_unencoding_stack(struct Curl_easy *data,
const char *enclist, int is_transfer);
#endif /* HEADER_CURL_CONTENT_ENCODING_H */
File diff suppressed because it is too large Load Diff
+149
View File
@@ -0,0 +1,149 @@
#ifndef HEADER_CURL_COOKIE_H
#define HEADER_CURL_COOKIE_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include "llist.h"
struct Cookie {
struct Curl_llist_node node; /* for the main cookie list */
struct Curl_llist_node getnode; /* for getlist */
char *name; /* <this> = value */
char *value; /* name = <this> */
char *path; /* canonical path */
char *domain; /* domain = <this> */
curl_off_t expires; /* expires = <this> */
unsigned int creationtime; /* time when the cookie was written */
BIT(tailmatch); /* tail-match the domain name */
BIT(secure); /* the 'secure' keyword was used */
BIT(livecookie); /* updated from server, not a stored file */
BIT(httponly); /* the httponly directive is present */
BIT(prefix_secure); /* secure prefix is set */
BIT(prefix_host); /* host prefix is set */
};
/*
* Available cookie prefixes, as defined in
* draft-ietf-httpbis-rfc6265bis-02
*/
#define COOKIE_PREFIX__SECURE (1 << 0)
#define COOKIE_PREFIX__HOST (1 << 1)
#define COOKIE_HASH_SIZE 63
struct CookieInfo {
/* linked lists of cookies we know of */
struct Curl_llist cookielist[COOKIE_HASH_SIZE];
curl_off_t next_expiration; /* the next time at which expiration happens */
unsigned int numcookies; /* number of cookies in the "jar" */
unsigned int lastct; /* last creation-time used in the jar */
BIT(running); /* state info, for cookie adding information */
BIT(newsession); /* new session, discard session cookies on load */
};
/* The maximum sizes we accept for cookies. RFC 6265 section 6.1 says
"general-use user agents SHOULD provide each of the following minimum
capabilities":
- At least 4096 bytes per cookie (as measured by the sum of the length of
the cookie's name, value, and attributes).
In the 6265bis draft document section 5.4 it is phrased even stronger: "If
the sum of the lengths of the name string and the value string is more than
4096 octets, abort these steps and ignore the set-cookie-string entirely."
*/
/** Limits for INCOMING cookies **/
/* The longest we allow a line to be when reading a cookie from an HTTP header
or from a cookie jar */
#define MAX_COOKIE_LINE 5000
/* Maximum length of an incoming cookie name or content we deal with. Longer
cookies are ignored. */
#define MAX_NAME 4096
/* Maximum number of Set-Cookie: lines accepted in a single response. If more
such header lines are received, they are ignored. This value must be less
than 256 since an unsigned char is used to count. */
#define MAX_SET_COOKIE_AMOUNT 50
/** Limits for OUTGOING cookies **/
/* Maximum size for an outgoing cookie line libcurl will use in an http
request. This is the default maximum length used in some versions of Apache
httpd. */
#define MAX_COOKIE_HEADER_LEN 8190
/* Maximum number of cookies libcurl will send in a single request, even if
there might be more cookies that match. One reason to cap the number is to
keep the maximum HTTP request within the maximum allowed size. */
#define MAX_COOKIE_SEND_AMOUNT 150
struct Curl_easy;
struct connectdata;
bool Curl_secure_context(struct Curl_easy *data, const char *host);
/*
* Add a cookie to the internal list of cookies. The domain and path arguments
* are only used if the COOKIE_HTTPHEADER bit is set in the flags.
*/
#define COOKIE_HTTPHEADER (1<<0) /* if HTTP header-style line */
#define COOKIE_NOEXPIRE (1<<1) /* skip remove_expired() */
#define COOKIE_SECURE (1<<2) /* connection is over secure origin */
#define COOKIE_NOPSL (1<<3) /* skip PSL check */
#define COOKIE_NOSESSION (1<<6) /* drop session cookies */
CURLcode Curl_cookie_add(struct Curl_easy *data,
struct CookieInfo *ci,
const char *lineptr,
const char *domain,
const char *path,
const int flags) WARN_UNUSED_RESULT;
CURLcode Curl_cookie_getlist(struct Curl_easy *data,
bool *okay, const char *host,
struct Curl_llist *list) WARN_UNUSED_RESULT;
void Curl_cookie_clearall(struct CookieInfo *ci);
void Curl_cookie_clearsess(struct CookieInfo *ci);
#if defined(CURL_DISABLE_HTTP) || defined(CURL_DISABLE_COOKIES)
#define Curl_cookie_list(x) NULL
#define Curl_cookie_loadfiles(x, y) CURLE_OK
#define Curl_cookie_init() NULL
#define Curl_cookie_run(x) Curl_nop_stmt
#define Curl_cookie_cleanup(x) Curl_nop_stmt
#define Curl_flush_cookies(x, y) Curl_nop_stmt
#else
void Curl_flush_cookies(struct Curl_easy *data, bool cleanup);
void Curl_cookie_cleanup(struct CookieInfo *ci);
struct CookieInfo *Curl_cookie_init(void);
struct curl_slist *Curl_cookie_list(struct Curl_easy *data);
CURLcode Curl_cookie_loadfiles(struct Curl_easy *data,
int flags) WARN_UNUSED_RESULT;
void Curl_cookie_run(struct Curl_easy *data);
#endif
#endif /* HEADER_CURL_COOKIE_H */
+192
View File
@@ -0,0 +1,192 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include <stddef.h> /* for offsetof() */
#include "creds.h"
#include "curl_trc.h"
#include "strcase.h"
#include "urldata.h"
CURLcode Curl_creds_create(const char *user,
const char *passwd,
const char *oauth_bearer,
const char *sasl_authzid,
const char *sasl_service,
uint8_t source,
struct Curl_creds **pcreds)
{
struct Curl_creds *creds = NULL;
size_t ulen = user ? strlen(user) : 0;
size_t plen = passwd ? strlen(passwd) : 0;
size_t olen = oauth_bearer ? strlen(oauth_bearer) : 0;
size_t salen = sasl_authzid ? strlen(sasl_authzid) : 0;
size_t sslen = sasl_service ? strlen(sasl_service) : 0;
char *s, *buf;
size_t bufsize;
CURLcode result = CURLE_OK;
Curl_creds_unlink(pcreds);
/* Everything empty/NULL, this is the NULL credential */
if(!user && !passwd && !olen && !salen && !sslen)
goto out;
if((ulen > CURL_MAX_INPUT_LENGTH) ||
(plen > CURL_MAX_INPUT_LENGTH) ||
(olen > CURL_MAX_INPUT_LENGTH) ||
(salen > CURL_MAX_INPUT_LENGTH) ||
(sslen > CURL_MAX_INPUT_LENGTH)) {
result = CURLE_BAD_FUNCTION_ARGUMENT;
goto out;
}
/* null-terminator for user already part of struct */
bufsize = ulen + plen + 1 + olen + 1 + salen + 1 + sslen + 1;
creds = curlx_calloc(1, sizeof(*creds) + bufsize);
if(!creds) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
creds->bufsize = bufsize;
creds->refcount = 1;
creds->source = source;
/* Some compilers try to be too smart about our dynamic struct size */
buf = ((char *)creds) + offsetof(struct Curl_creds, buf);
creds->user = s = buf;
if(ulen)
memcpy(s, user, ulen + 1);
creds->passwd = s = buf + ulen + 1;
if(plen)
memcpy(s, passwd, plen + 1);
creds->oauth_bearer = s = buf + ulen + 1 + plen + 1;
if(olen)
memcpy(s, oauth_bearer, olen + 1);
creds->sasl_authzid = s = buf + ulen + 1 + plen + 1 + olen + 1;
if(salen)
memcpy(s, sasl_authzid, salen + 1);
creds->sasl_service = s = buf + ulen + 1 + plen + 1 + olen + 1 + salen + 1;
if(sslen)
memcpy(s, sasl_service, sslen + 1);
out:
if(!result)
*pcreds = creds;
else
Curl_creds_unlink(&creds);
return result;
}
CURLcode Curl_creds_merge(const char *user,
const char *passwd,
struct Curl_creds *creds_in,
uint8_t source,
struct Curl_creds **pcreds_out)
{
struct Curl_creds *creds_out = NULL;
CURLcode result;
if(!creds_in) {
result = Curl_creds_create(user, passwd, NULL, NULL, NULL,
source, &creds_out);
}
else {
result = Curl_creds_create(user ? user : Curl_creds_user(creds_in),
passwd ? passwd : Curl_creds_passwd(creds_in),
Curl_creds_oauth_bearer(creds_in),
Curl_creds_sasl_authzid(creds_in),
Curl_creds_sasl_service(creds_in),
source, &creds_out);
}
Curl_creds_link(pcreds_out, creds_out);
Curl_creds_unlink(&creds_out);
return result;
}
void Curl_creds_link(struct Curl_creds **pdest, struct Curl_creds *src)
{
if(*pdest != src) {
Curl_creds_unlink(pdest);
*pdest = src;
if(src) {
DEBUGASSERT(src->refcount < UINT32_MAX);
src->refcount++;
}
}
}
void Curl_creds_unlink(struct Curl_creds **pcreds)
{
if(*pcreds) {
struct Curl_creds *creds = *pcreds;
DEBUGASSERT(creds->refcount);
*pcreds = NULL;
if(creds->refcount)
creds->refcount--;
if(!creds->refcount) {
curlx_memzero(creds, sizeof(*creds) + creds->bufsize);
curlx_free(creds);
}
}
}
bool Curl_creds_same(struct Curl_creds *c1, struct Curl_creds *c2)
{
return (c1 == c2) ||
(c1 && c2 &&
!Curl_timestrcmp(c1->user, c2->user) &&
!Curl_timestrcmp(c1->passwd, c2->passwd) &&
!Curl_timestrcmp(c1->oauth_bearer, c2->oauth_bearer) &&
!Curl_timestrcmp(c1->sasl_authzid, c2->sasl_authzid) &&
!Curl_timestrcmp(c1->sasl_service, c2->sasl_service));
}
bool Curl_creds_equal(struct Curl_creds *c1, struct Curl_creds *c2)
{
return Curl_creds_same(c1, c2) &&
((c1 == c2) || (c1 && c2 && (c1->source == c2->source)));
}
#ifdef CURLVERBOSE
void Curl_creds_trace(struct Curl_easy *data, struct Curl_creds *creds,
const char *msg)
{
if(creds) {
CURL_TRC_M(data, "%s: user=%s, passwd=%s, "
"sasl_authzid=%s, oauth_bearer=%s, source=%d",
msg,
Curl_creds_user(creds),
Curl_creds_has_passwd(creds) ? "***" : "",
Curl_creds_sasl_authzid(creds),
Curl_creds_has_oauth_bearer(creds) ? "***" : "",
creds->source);
}
else
CURL_TRC_M(data, "%s: -", msg);
}
#endif
+92
View File
@@ -0,0 +1,92 @@
#ifndef HEADER_CURL_CREDS_H
#define HEADER_CURL_CREDS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
struct Curl_easy;
#define CREDS_NONE 0 /* used for default username/passwd */
#define CREDS_URL 1 /* username/passwd from URL */
#define CREDS_OPTION 2 /* username/passwd set with a CURLOPT_ */
#define CREDS_NETRC 3 /* username/passwd found in netrc */
struct Curl_creds {
const char *user; /* non-NULL, maybe empty string */
const char *passwd; /* non-NULL, maybe empty string */
const char *oauth_bearer; /* non-NULL, maybe empty string */
const char *sasl_authzid; /* non-NULL, maybe empty string */
const char *sasl_service; /* non-NULL, maybe empty string */
uint32_t refcount;
uint8_t source; /* CREDS_* value */
size_t bufsize; /* extra bytes added to sizeof(struct Curl_creds) */
char buf[1];
};
CURLcode Curl_creds_create(const char *user,
const char *passwd,
const char *oauth_bearer,
const char *sasl_authzid,
const char *sasl_service,
uint8_t source,
struct Curl_creds **pcreds);
/* Create credentials by overriding `user` and/or `passwd` in `creds_in` */
CURLcode Curl_creds_merge(const char *user,
const char *passwd,
struct Curl_creds *creds_in,
uint8_t source,
struct Curl_creds **pcreds_out);
/* Unlink any creds in `*pdest`, assign src, increase src
* refcount when not NULL. */
void Curl_creds_link(struct Curl_creds **pdest, struct Curl_creds *src);
/* Drop a reference, creds may be passed as NULL */
void Curl_creds_unlink(struct Curl_creds **pcreds);
/* TRUE if both creds are NULL or have same values, except source. */
bool Curl_creds_same(struct Curl_creds *c1, struct Curl_creds *c2);
/* TRUE if both creds are NULL or have all values equal. */
bool Curl_creds_equal(struct Curl_creds *c1, struct Curl_creds *c2);
/* Provides properties for creds or, if creds is NULL, the empty string */
#define Curl_creds_has_user(c) ((c) && (c)->user[0])
#define Curl_creds_has_passwd(c) ((c) && (c)->passwd[0])
#define Curl_creds_has_user_or_pass(c) \
((c) && ((c)->user[0] || (c)->passwd[0]))
#define Curl_creds_has_oauth_bearer(c) ((c) && (c)->oauth_bearer[0])
#define Curl_creds_has_sasl_service(c) ((c) && (c)->sasl_service[0])
#define Curl_creds_user(c) ((c) ? (c)->user : "")
#define Curl_creds_passwd(c) ((c) ? (c)->passwd : "")
#define Curl_creds_oauth_bearer(c) ((c) ? (c)->oauth_bearer : "")
#define Curl_creds_sasl_authzid(c) ((c) ? (c)->sasl_authzid : "")
#define Curl_creds_sasl_service(c) ((c) ? (c)->sasl_service : "")
#ifdef CURLVERBOSE
void Curl_creds_trace(struct Curl_easy *data, struct Curl_creds *creds,
const char *msg);
#endif
#endif /* HEADER_CURL_CREDS_H */
+620
View File
@@ -0,0 +1,620 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Linus Nielsen Feltzing, <linus@haxx.se>
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include "urldata.h"
#include "url.h"
#include "cfilters.h"
#include "progress.h"
#include "multiif.h"
#include "multi_ev.h"
#include "curl_trc.h"
#include "cshutdn.h"
#include "sigpipe.h"
#include "connect.h"
#include "select.h"
#include "curlx/strparse.h"
#define DEFAULT_SHUTDOWN_TIMEOUT_MS (2 * 1000)
void Curl_cshutdn_start_timer(struct Curl_easy *data, int8_t sockindex,
int timeout_ms)
{
struct connectdata *conn = data->conn;
const struct curltime *pnow = Curl_pgrs_now(data);
DEBUGASSERT(conn);
conn->shutdown.start_ms[sockindex] =
curlx_ptimediff_ms(pnow, &conn->created);
conn->shutdown.timeout_ms = (timeout_ms > 0) ?
(timediff_t)timeout_ms :
((data->set.shutdowntimeout > 0) ?
data->set.shutdowntimeout : DEFAULT_SHUTDOWN_TIMEOUT_MS);
/* Set a timer, unless we operate on the admin handle */
if(data->mid)
Curl_expire_set(data, EXPIRE_SHUTDOWN, conn->shutdown.timeout_ms, pnow);
CURL_TRC_M(data, "shutdown start on%s connection",
sockindex ? " secondary" : "");
}
timediff_t Curl_cshutdn_timeleft_ms(struct Curl_easy *data,
struct connectdata *conn,
int8_t sockindex)
{
timediff_t left_ms;
if(conn->shutdown.start_ms[sockindex] < 0)
return 0; /* not started or no limits */
left_ms = conn->shutdown.timeout_ms -
(curlx_ptimediff_ms(Curl_pgrs_now(data), &conn->created) -
conn->shutdown.start_ms[sockindex]);
return left_ms ? left_ms : -1;
}
static timediff_t cshutdn_conn_timeleft(struct Curl_easy *data,
struct connectdata *conn)
{
timediff_t left_ms = 0, ms;
int8_t i;
for(i = 0; conn->shutdown.timeout_ms && (i < 2); ++i) {
if(conn->shutdown.start_ms[i] < 0)
continue;
ms = Curl_cshutdn_timeleft_ms(data, conn, i);
if(ms && (!left_ms || ms < left_ms))
left_ms = ms;
}
return left_ms;
}
void Curl_cshutdn_clear_timer(struct Curl_easy *data, int8_t sockindex)
{
data->conn->shutdown.start_ms[sockindex] = -1;
}
static void cshutdn_run_conn_handler(struct Curl_easy *data,
struct connectdata *conn)
{
if(!conn->bits.shutdown_handler) {
if(conn->scheme && conn->scheme->run->disconnect) {
/* Some disconnect handlers do a blocking wait on server responses.
* FTP/IMAP/SMTP and SFTP are among them. When using the internal
* handle, set an overall short timeout so we do not hang for the
* default 120 seconds. */
if(data->state.internal) {
data->set.timeout = DEFAULT_SHUTDOWN_TIMEOUT_MS;
Curl_pgrsTime(data, TIMER_STARTOP);
}
/* This is set if protocol-specific cleanups should be made */
DEBUGF(infof(data, "connection #%" FMT_OFF_T
", shutdown protocol handler (aborted=%d)",
conn->connection_id, conn->bits.aborted));
/* There are protocol handlers that block on retrieving
* server responses here (FTP). Set a short timeout. */
conn->scheme->run->disconnect(data, conn, (bool)conn->bits.aborted);
}
conn->bits.shutdown_handler = TRUE;
}
}
CURLcode Curl_cshutdn_try_once_idx(struct Curl_easy *data,
int8_t sockindex, bool *done)
{
struct Curl_cfilter *cf;
CURLcode result = CURLE_OK;
timediff_t timeout_ms;
DEBUGASSERT(data->conn);
if(!CONN_SOCK_IDX_VALID(sockindex))
return CURLE_BAD_FUNCTION_ARGUMENT;
/* Get the first connected filter that is not shut down already. */
cf = data->conn->cfilter[sockindex];
while(cf && (!cf->connected || cf->shutdown))
cf = cf->next;
if(!cf) {
*done = TRUE;
return CURLE_OK;
}
*done = FALSE;
if(!CURL_CONN_IN_SHUTDOWN(data->conn, sockindex)) {
Curl_cshutdn_start_timer(data, sockindex, 0);
}
else {
timeout_ms = Curl_cshutdn_timeleft_ms(data, data->conn, sockindex);
if(timeout_ms < 0) {
/* info message, since this might be regarded as acceptable */
infof(data, "shutdown timeout");
return CURLE_OPERATION_TIMEDOUT;
}
}
while(cf) {
if(!cf->shutdown) {
bool cfdone = FALSE;
result = cf->cft->do_shutdown(cf, data, &cfdone);
if(result) {
CURL_TRC_CF(data, cf, "shut down failed with %d", (int)result);
return result;
}
else if(!cfdone) {
CURL_TRC_CF(data, cf, "shut down not done yet");
return CURLE_OK;
}
CURL_TRC_CF(data, cf, "shut down successfully");
cf->shutdown = TRUE;
}
cf = cf->next;
}
*done = (!result);
return result;
}
static void cshutdn_run_once(struct Curl_easy *data,
struct connectdata *conn,
bool *done)
{
CURLcode r1, r2;
bool done1, done2;
/* We expect to be attached when called */
DEBUGASSERT(data->conn == conn);
if(!CURL_CONN_IN_SHUTDOWN(conn, FIRSTSOCKET)) {
Curl_cshutdn_start_timer(data, FIRSTSOCKET, 0);
}
cshutdn_run_conn_handler(data, conn);
if(conn->bits.shutdown_filters) {
*done = TRUE;
return;
}
if(!conn->bits.connect_only && Curl_conn_is_connected(conn, FIRSTSOCKET))
r1 = Curl_cshutdn_try_once_idx(data, FIRSTSOCKET, &done1);
else {
r1 = CURLE_OK;
done1 = TRUE;
}
if(!conn->bits.connect_only && Curl_conn_is_connected(conn, SECONDARYSOCKET))
r2 = Curl_cshutdn_try_once_idx(data, SECONDARYSOCKET, &done2);
else {
r2 = CURLE_OK;
done2 = TRUE;
}
/* we are done when any failed or both report success */
*done = (r1 || r2 || (done1 && done2));
if(*done)
conn->bits.shutdown_filters = TRUE;
}
void Curl_cshutdn_try_once(struct Curl_easy *admin,
struct connectdata *conn,
bool *done)
{
DEBUGASSERT(!admin->conn);
DEBUGASSERT(!admin->mid);
Curl_attach_connection(admin, conn, FALSE);
cshutdn_run_once(admin, conn, done);
CURL_TRC_M(admin, "[SHUTDOWN] shutdown, done=%d", *done);
Curl_detach_connection(admin);
}
void Curl_cshutdn_terminate(struct Curl_easy *admin,
struct connectdata *conn,
bool do_shutdown)
{
bool done;
/* there must be a connection to close */
DEBUGASSERT(conn);
/* it must be removed from the connection pool */
DEBUGASSERT(conn->cpid == UINT32_MAX);
/* the transfer must be detached from the connection */
DEBUGASSERT(admin && !admin->conn);
DEBUGASSERT(!admin->mid);
Curl_attach_connection(admin, conn, FALSE);
cshutdn_run_conn_handler(admin, conn);
if(do_shutdown) {
/* Make a last attempt to shutdown handlers and filters, if
* not done so already. */
cshutdn_run_once(admin, conn, &done);
}
CURL_TRC_M(admin, "[SHUTDOWN] %sclosing connection #%" FMT_OFF_T,
conn->bits.shutdown_filters ? "" : "force ",
conn->connection_id);
Curl_conn_cf_discard_all(admin, conn, SECONDARYSOCKET);
Curl_conn_cf_discard_all(admin, conn, FIRSTSOCKET);
Curl_detach_connection(admin);
if(admin->multi)
Curl_multi_ev_conn_done(admin->multi, admin, conn);
Curl_conn_free(admin, conn);
if(admin->multi) {
CURL_TRC_M(admin, "[SHUTDOWN] trigger multi connchanged");
Curl_multi_connchanged(admin->multi);
}
}
static size_t cshutdn_destroy_oldest(struct cshutdn *cshutdn,
struct Curl_easy *admin,
const char *destination,
size_t count)
{
struct Curl_sigpipe_ctx sigpipe_ctx;
size_t removed = 0;
uint32_t i = 0;
sigpipe_init(&sigpipe_ctx);
while((removed < count) && (i < CURL_PTRARRAY_COUNT(&cshutdn->conns))) {
struct connectdata *conn = CURL_PTRARRAY_GET(&cshutdn->conns, i);
if(!destination || !strcmp(destination, conn->destination)) {
Curl_ptrarray_remove(&cshutdn->conns, i);
sigpipe_apply(admin, &sigpipe_ctx);
Curl_cshutdn_terminate(admin, conn, FALSE);
++removed;
}
else
++i;
}
sigpipe_restore(&sigpipe_ctx);
return removed;
}
size_t Curl_cshutdn_close_oldest(struct cshutdn *cshutdn,
struct Curl_easy *admin,
const char *destination,
size_t count)
{
if(cshutdn) {
return cshutdn_destroy_oldest(cshutdn, admin, destination, count);
}
return 0;
}
#define NUM_POLLS_ON_STACK 10
static CURLcode cshutdn_wait(struct cshutdn *cshutdn,
struct Curl_easy *admin,
int timeout_ms)
{
struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK];
struct curl_pollfds cpfds;
CURLcode result;
Curl_pollfds_init(&cpfds, a_few_on_stack, NUM_POLLS_ON_STACK);
result = Curl_cshutdn_add_pollfds(cshutdn, admin, &cpfds);
if(result)
goto out;
Curl_poll(cpfds.pfds, cpfds.n, CURLMIN(timeout_ms, 1000));
out:
Curl_pollfds_cleanup(&cpfds);
return result;
}
static void cshutdn_perform(struct cshutdn *cshutdn,
struct Curl_easy *admin,
struct Curl_sigpipe_ctx *sigpipe_ctx)
{
struct connectdata *conn;
timediff_t next_expire_ms = 0, ms;
uint32_t i = 0;
bool done;
if(!CURL_PTRARRAY_COUNT(&cshutdn->conns))
return;
CURL_TRC_M(admin, "[SHUTDOWN] perform on %u connections",
CURL_PTRARRAY_COUNT(&cshutdn->conns));
sigpipe_apply(admin, sigpipe_ctx);
while(i < CURL_PTRARRAY_COUNT(&cshutdn->conns)) {
conn = CURL_PTRARRAY_GET(&cshutdn->conns, i);
Curl_cshutdn_try_once(admin, conn, &done);
if(done) {
Curl_ptrarray_remove(&cshutdn->conns, i);
Curl_cshutdn_terminate(admin, conn, FALSE);
}
else {
++i;
/* idata has one timer list, but maybe more than one connection.
* Set EXPIRE_SHUTDOWN to the smallest time left for all. */
ms = cshutdn_conn_timeleft(admin, conn);
if(ms && (!next_expire_ms || (ms < next_expire_ms)))
next_expire_ms = ms;
}
}
if(next_expire_ms)
Curl_expire(admin, next_expire_ms, EXPIRE_SHUTDOWN);
}
static void cshutdn_terminate_all(struct cshutdn *cshutdn,
struct Curl_easy *admin,
int timeout_ms)
{
struct curltime started = *Curl_pgrs_now(admin);
struct Curl_sigpipe_ctx sigpipe_ctx;
CURL_TRC_M(admin, "[SHUTDOWN] shutdown all");
sigpipe_init(&sigpipe_ctx);
while(CURL_PTRARRAY_COUNT(&cshutdn->conns)) {
timediff_t spent_ms;
int remain_ms;
cshutdn_perform(cshutdn, admin, &sigpipe_ctx);
if(!CURL_PTRARRAY_COUNT(&cshutdn->conns)) {
CURL_TRC_M(admin, "[SHUTDOWN] shutdown finished cleanly");
break;
}
/* wait for activity, timeout or "nothing" */
spent_ms = curlx_ptimediff_ms(Curl_pgrs_now(admin), &started);
if(spent_ms >= (timediff_t)timeout_ms) {
CURL_TRC_M(admin, "[SHUTDOWN] shutdown finished, %s",
(timeout_ms > 0) ? "timeout" : "best effort done");
break;
}
remain_ms = timeout_ms - (int)spent_ms;
if(cshutdn_wait(cshutdn, admin, remain_ms)) {
CURL_TRC_M(admin, "[SHUTDOWN] shutdown finished, aborted");
break;
}
}
/* Terminate any remaining. */
while(CURL_PTRARRAY_COUNT(&cshutdn->conns)) {
struct connectdata *conn = Curl_ptrarray_remove(&cshutdn->conns, 0);
Curl_cshutdn_terminate(admin, conn, FALSE);
}
DEBUGASSERT(!CURL_PTRARRAY_COUNT(&cshutdn->conns));
sigpipe_restore(&sigpipe_ctx);
}
void Curl_cshutdn_init(struct cshutdn *cshutdn)
{
Curl_ptrarray_init(&cshutdn->conns);
}
void Curl_cshutdn_destroy(struct cshutdn *cshutdn,
struct Curl_easy *admin)
{
if(admin) {
int timeout_ms = 0;
/* for testing, run graceful shutdown */
#ifdef DEBUGBUILD
{
const char *p = getenv("CURL_GRACEFUL_SHUTDOWN");
if(p) {
curl_off_t l;
if(!curlx_str_number(&p, &l, INT_MAX))
timeout_ms = (int)l;
}
}
#endif
if(CURL_PTRARRAY_COUNT(&cshutdn->conns)) {
CURL_TRC_M(admin, "[SHUTDOWN] destroy, %u connections, timeout=%dms",
CURL_PTRARRAY_COUNT(&cshutdn->conns), timeout_ms);
cshutdn_terminate_all(cshutdn, admin, timeout_ms);
}
}
}
size_t Curl_cshutdn_count(struct cshutdn *cshutdn)
{
if(cshutdn) {
return CURL_PTRARRAY_COUNT(&cshutdn->conns);
}
return 0;
}
size_t Curl_cshutdn_dest_count(struct cshutdn *cshutdn,
const char *destination)
{
if(cshutdn) {
size_t n = 0;
uint32_t i = 0;
for(i = 0; i < CURL_PTRARRAY_COUNT(&cshutdn->conns); ++i) {
struct connectdata *conn = CURL_PTRARRAY_GET(&cshutdn->conns, i);
if(!strcmp(destination, conn->destination))
++n;
}
return n;
}
return 0;
}
static CURLMcode cshutdn_update_ev(struct Curl_multi *multi,
struct connectdata *conn)
{
CURLMcode mresult;
Curl_attach_connection(multi->admin, conn, FALSE);
mresult = Curl_multi_ev_assess_conn(multi, multi->admin, conn);
Curl_detach_connection(multi->admin);
return mresult;
}
void Curl_cshutdn_add(struct cshutdn *cshutdn,
struct Curl_multi *multi,
struct connectdata *conn,
size_t max_shutdowns)
{
struct Curl_easy *admin = multi->admin;
/* Add the connection to our shutdown list for non-blocking shutdown
* during multi processing. */
if(max_shutdowns <= CURL_PTRARRAY_COUNT(&cshutdn->conns)) {
CURL_TRC_M(admin, "[SHUTDOWN] discarding oldest shutdown connection "
"due to shutdown limit of %zu", max_shutdowns);
cshutdn_destroy_oldest(cshutdn, admin, NULL, 1);
}
if(multi->socket_cb && cshutdn_update_ev(multi, conn)) {
CURL_TRC_M(admin, "[SHUTDOWN] update events failed, discarding #%"
FMT_OFF_T, conn->connection_id);
Curl_cshutdn_terminate(admin, conn, FALSE);
return;
}
if(Curl_ptrarray_add(&cshutdn->conns, conn)) {
CURL_TRC_M(admin, "[SHUTDOWN] adding failed, discarding #%"
FMT_OFF_T, conn->connection_id);
Curl_cshutdn_terminate(admin, conn, FALSE);
return;
}
CURL_TRC_M(admin, "[SHUTDOWN] added #%" FMT_OFF_T
" to shutdowns, now %u conns in shutdown",
conn->connection_id, CURL_PTRARRAY_COUNT(&cshutdn->conns));
}
void Curl_cshutdn_perform(struct cshutdn *cshutdn,
struct Curl_easy *admin,
struct Curl_sigpipe_ctx *sigpipe_ctx)
{
cshutdn_perform(cshutdn, admin, sigpipe_ctx);
}
/* return fd_set info about the shutdown connections */
void Curl_cshutdn_setfds(struct cshutdn *cshutdn,
struct Curl_easy *admin,
fd_set *read_fd_set, fd_set *write_fd_set,
int *maxfd)
{
if(CURL_PTRARRAY_COUNT(&cshutdn->conns)) {
struct easy_pollset ps;
uint32_t i;
Curl_pollset_init(&ps);
for(i = 0; i < CURL_PTRARRAY_COUNT(&cshutdn->conns); ++i) {
unsigned int j;
struct connectdata *conn = CURL_PTRARRAY_GET(&cshutdn->conns, i);
CURLcode result;
Curl_pollset_reset(&ps);
Curl_attach_connection(admin, conn, FALSE);
result = Curl_conn_adjust_pollset(admin, conn, &ps);
Curl_detach_connection(admin);
if(result)
continue;
for(j = 0; j < ps.n; j++) {
curl_socket_t sock = ps.sockets[j];
if(!FDSET_SOCK(sock))
continue;
if(ps.actions[j] & CURL_POLL_IN)
FD_SET(sock, read_fd_set);
if(ps.actions[j] & CURL_POLL_OUT)
FD_SET(sock, write_fd_set);
if((ps.actions[j] & (CURL_POLL_OUT | CURL_POLL_IN)) &&
((int)sock > *maxfd))
*maxfd = (int)sock;
}
}
Curl_pollset_cleanup(&ps);
}
}
/* return information about the shutdown connections */
unsigned int Curl_cshutdn_add_waitfds(struct cshutdn *cshutdn,
struct Curl_easy *admin,
struct Curl_waitfds *cwfds)
{
unsigned int need = 0;
if(CURL_PTRARRAY_COUNT(&cshutdn->conns)) {
struct easy_pollset ps;
struct connectdata *conn;
uint32_t i;
CURLcode result;
Curl_pollset_init(&ps);
for(i = 0; i < CURL_PTRARRAY_COUNT(&cshutdn->conns); ++i) {
conn = CURL_PTRARRAY_GET(&cshutdn->conns, i);
Curl_pollset_reset(&ps);
Curl_attach_connection(admin, conn, FALSE);
result = Curl_conn_adjust_pollset(admin, conn, &ps);
Curl_detach_connection(admin);
if(!result)
need += Curl_waitfds_add_ps(cwfds, &ps);
}
Curl_pollset_cleanup(&ps);
}
return need;
}
CURLcode Curl_cshutdn_add_pollfds(struct cshutdn *cshutdn,
struct Curl_easy *admin,
struct curl_pollfds *cpfds)
{
CURLcode result = CURLE_OK;
if(CURL_PTRARRAY_COUNT(&cshutdn->conns)) {
struct easy_pollset ps;
struct connectdata *conn;
uint32_t i;
Curl_pollset_init(&ps);
for(i = 0; i < CURL_PTRARRAY_COUNT(&cshutdn->conns); ++i) {
conn = CURL_PTRARRAY_GET(&cshutdn->conns, i);
Curl_pollset_reset(&ps);
Curl_attach_connection(admin, conn, FALSE);
result = Curl_conn_adjust_pollset(admin, conn, &ps);
Curl_detach_connection(admin);
if(!result)
result = Curl_pollfds_add_ps(cpfds, &ps);
if(result) {
Curl_pollset_cleanup(&ps);
Curl_pollfds_cleanup(cpfds);
goto out;
}
}
Curl_pollset_cleanup(&ps);
}
out:
return result;
}
+130
View File
@@ -0,0 +1,130 @@
#ifndef HEADER_CURL_CSHUTDN_H
#define HEADER_CURL_CSHUTDN_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
* Copyright (C) Linus Nielsen Feltzing, <linus@haxx.se>
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "ptrarray.h"
struct connectdata;
struct Curl_easy;
struct curl_pollfds;
struct Curl_waitfds;
struct Curl_multi;
struct Curl_share;
struct Curl_sigpipe_ctx;
/* Terminates the connection, e.g. closes and destroys it.
* If `do_shutdown` is TRUE, the shutdown will be run once.
* Takes ownership of `conn`. `conn` MUST no longer be in
* a pool or on a shutdown list. */
void Curl_cshutdn_terminate(struct Curl_easy *admin,
struct connectdata *conn,
bool do_shutdown);
/* Start the shutdown timer,
* marks the connection sockindex as being shut down. */
void Curl_cshutdn_start_timer(struct Curl_easy *data, int8_t sockindex,
int timeout_ms);
/* Clear the shutdown timer at sockindex again. */
void Curl_cshutdn_clear_timer(struct Curl_easy *data, int8_t sockindex);
/* return how much time there is left to shutdown the connection at
* sockindex. Returns 0 if there is no limit or shutdown has not started. */
timediff_t Curl_cshutdn_timeleft_ms(struct Curl_easy *data,
struct connectdata *conn,
int8_t sockindex);
#define CURL_CONN_IN_SHUTDOWN(c,i) ((c)->shutdown.start_ms[(i)] >= 0)
/* Shutdown the connection at `sockindex` non-blocking.
* Will start the shutdown timer if not already set.
* Return CURLE_OK and *done == FALSE if not finished. */
CURLcode Curl_cshutdn_try_once_idx(struct Curl_easy *data,
int8_t sockindex, bool *done);
/* Run the shutdown of the connection once non-blocking for both
* socket indices. Will start the shutdown timer if not already set.
* Shortly attach/detach the admin handle to `conn` while doing so.
* `done` will be set TRUE if any error was encountered or if
* the connection was shut down completely. */
void Curl_cshutdn_try_once(struct Curl_easy *admin,
struct connectdata *conn, bool *done);
/* A `cshutdown` is always owned by a multi handle to maintain
* the connections to be shut down. It registers timers and
* sockets to monitor via the multi handle. */
struct cshutdn {
struct ptrarray conns; /* connections being shut down */
};
/* Init as part of the given multi handle. */
void Curl_cshutdn_init(struct cshutdn *cshutdn);
/* Terminate all remaining connections and free resources. */
void Curl_cshutdn_destroy(struct cshutdn *cshutdn,
struct Curl_easy *admin);
/* Number of connections being shut down. */
size_t Curl_cshutdn_count(struct cshutdn *cshutdn);
/* Number of connections to the destination being shut down. */
size_t Curl_cshutdn_dest_count(struct cshutdn *cshutdn,
const char *destination);
/* Close the oldest `count` connections in shutdown to destination or,
* when destination is NULL for any destination.
* Return the number of connections closed. */
size_t Curl_cshutdn_close_oldest(struct cshutdn *cshutdn,
struct Curl_easy *admin,
const char *destination,
size_t count);
/* Add a connection to have it shut down. Terminate the oldest
* connection when shutdowns exceed max_shutdowns. */
void Curl_cshutdn_add(struct cshutdn *cshutdn,
struct Curl_multi *multi,
struct connectdata *conn,
size_t max_shutdowns);
/* Add sockets and POLLIN/OUT flags for connections being shut down. */
CURLcode Curl_cshutdn_add_pollfds(struct cshutdn *cshutdn,
struct Curl_easy *admin,
struct curl_pollfds *cpfds);
unsigned int Curl_cshutdn_add_waitfds(struct cshutdn *cshutdn,
struct Curl_easy *admin,
struct Curl_waitfds *cwfds);
void Curl_cshutdn_setfds(struct cshutdn *cshutdn,
struct Curl_easy *admin,
fd_set *read_fd_set, fd_set *write_fd_set,
int *maxfd);
/* Run maintenance on all connections. */
void Curl_cshutdn_perform(struct cshutdn *cshutdn,
struct Curl_easy *admin,
struct Curl_sigpipe_ctx *sigpipe_ctx);
#endif /* HEADER_CURL_CSHUTDN_H */
+647
View File
@@ -0,0 +1,647 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_NETINET_IN6_H
#include <netinet/in6.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#include <stddef.h> /* for offsetof() */
#include "curl_addrinfo.h"
#include "fake_addrinfo.h"
#include "curlx/inet_pton.h"
#include "curlx/strparse.h"
/*
* Curl_freeaddrinfo()
*
* This is used to free a linked list of Curl_addrinfo structs along
* with all its associated allocated storage. This function should be
* called once for each successful call to Curl_getaddrinfo_ex() or to
* any function call which actually allocates a Curl_addrinfo struct.
*/
#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER == 910) && \
defined(__OPTIMIZE__) && defined(__unix__) && defined(__i386__)
/* workaround icc 9.1 optimizer issue */
# define vqualifier volatile
#else
# define vqualifier
#endif
void Curl_freeaddrinfo(struct Curl_addrinfo *cahead)
{
struct Curl_addrinfo *vqualifier canext;
struct Curl_addrinfo *ca;
for(ca = cahead; ca; ca = canext) {
canext = ca->ai_next;
curlx_free(ca);
}
}
struct Curl_addrinfo *Curl_addrinfo_get(struct Curl_addrinfo *ai,
int ai_family,
unsigned int n)
{
unsigned int i;
for(i = 0; ai; ai = ai->ai_next) {
if(ai->ai_family == ai_family) {
if(i == n)
return ai;
++i;
}
}
return NULL;
}
#ifdef HAVE_GETADDRINFO
/*
* Curl_getaddrinfo_ex()
*
* This is a wrapper function around system's getaddrinfo(), with
* the only difference that instead of returning a linked list of
* addrinfo structs this one returns a linked list of Curl_addrinfo
* ones. The memory allocated by this function *MUST* be free'd with
* Curl_freeaddrinfo(). For each successful call to this function
* there must be an associated call later to Curl_freeaddrinfo().
*
* There should be no single call to system's getaddrinfo() in the
* whole library, any such call should be 'routed' through this one.
*/
int Curl_getaddrinfo_ex(const char *nodename,
const char *servname,
const struct addrinfo *hints,
struct Curl_addrinfo **result)
{
const struct addrinfo *ai;
struct addrinfo *aihead;
struct Curl_addrinfo *cafirst = NULL;
struct Curl_addrinfo *calast = NULL;
struct Curl_addrinfo *ca;
size_t ss_size;
int error;
*result = NULL; /* assume failure */
error = CURL_GETADDRINFO(nodename, servname, hints, &aihead);
if(error)
return error;
/* traverse the addrinfo list */
for(ai = aihead; ai; ai = ai->ai_next) {
size_t namelen = ai->ai_canonname ? strlen(ai->ai_canonname) + 1 : 0;
/* ignore elements with unsupported address family,
settle family-specific sockaddr structure size. */
if(ai->ai_family == AF_INET)
ss_size = sizeof(struct sockaddr_in);
#ifdef USE_IPV6
else if(ai->ai_family == AF_INET6)
ss_size = sizeof(struct sockaddr_in6);
#endif
else
continue;
/* ignore elements without required address info */
if(!ai->ai_addr || !(ai->ai_addrlen > 0))
continue;
/* ignore elements with bogus address size */
if((size_t)ai->ai_addrlen < ss_size)
continue;
ca = curlx_malloc(sizeof(struct Curl_addrinfo) + ss_size + namelen);
if(!ca) {
error = EAI_MEMORY;
break;
}
/* copy each structure member individually, member ordering,
size, or padding might be different for each platform. */
ca->ai_flags = ai->ai_flags;
ca->ai_family = ai->ai_family;
ca->ai_socktype = ai->ai_socktype;
ca->ai_protocol = ai->ai_protocol;
ca->ai_addrlen = (curl_socklen_t)ss_size;
ca->ai_addr = NULL;
ca->ai_canonname = NULL;
ca->ai_next = NULL;
ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
memcpy(ca->ai_addr, ai->ai_addr, ss_size);
if(namelen) {
ca->ai_canonname = (void *)((char *)ca->ai_addr + ss_size);
memcpy(ca->ai_canonname, ai->ai_canonname, namelen);
}
/* if the return list is empty, this becomes the first element */
if(!cafirst)
cafirst = ca;
/* add this element last in the return list */
if(calast)
calast->ai_next = ca;
calast = ca;
}
/* destroy the addrinfo list */
if(aihead)
CURL_FREEADDRINFO(aihead);
/* if we failed, also destroy the Curl_addrinfo list */
if(error) {
Curl_freeaddrinfo(cafirst);
cafirst = NULL;
}
else if(!cafirst) {
#ifdef EAI_NONAME
/* rfc3493 conformant */
error = EAI_NONAME;
#else
/* rfc3493 obsoleted */
error = EAI_NODATA;
#endif
#ifdef USE_WINSOCK
SET_SOCKERRNO(error);
#endif
}
*result = cafirst;
/* This is not a CURLcode */
return error;
}
#endif /* HAVE_GETADDRINFO */
/*
* Curl_he2ai()
*
* This function returns a pointer to the first element of a newly allocated
* Curl_addrinfo struct linked list filled with the data of a given hostent.
* Curl_addrinfo is meant to work like the addrinfo struct does for an IPv6
* stack, but usable also for IPv4, all hosts and environments.
*
* The memory allocated by this function *MUST* be free'd later on calling
* Curl_freeaddrinfo(). For each successful call to this function there
* must be an associated call later to Curl_freeaddrinfo().
*
* Curl_addrinfo defined in "lib/curl_addrinfo.h"
*
* struct Curl_addrinfo {
* int ai_flags;
* int ai_family;
* int ai_socktype;
* int ai_protocol;
* curl_socklen_t ai_addrlen; * Follow rfc3493 struct addrinfo *
* char *ai_canonname;
* struct sockaddr *ai_addr;
* struct Curl_addrinfo *ai_next;
* };
*
* hostent defined in <netdb.h>
*
* struct hostent {
* char *h_name;
* char **h_aliases;
* int h_addrtype;
* int h_length;
* char **h_addr_list;
* };
*
* for backward compatibility:
*
* #define h_addr h_addr_list[0]
*/
#if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETADDRINFO_THREADSAFE))
struct Curl_addrinfo *Curl_he2ai(const struct hostent *he, int port)
{
struct Curl_addrinfo *ai;
struct Curl_addrinfo *prevai = NULL;
struct Curl_addrinfo *firstai = NULL;
struct sockaddr_in *addr;
#ifdef USE_IPV6
struct sockaddr_in6 *addr6;
#endif
CURLcode result = CURLE_OK;
int i;
char *curr;
if(!he)
/* no input == no output! */
return NULL;
DEBUGASSERT(he->h_name && he->h_addr_list);
for(i = 0; (curr = he->h_addr_list[i]) != NULL; i++) {
size_t ss_size;
size_t namelen = strlen(he->h_name) + 1; /* include null-terminator */
#ifdef USE_IPV6
if(he->h_addrtype == AF_INET6)
ss_size = sizeof(struct sockaddr_in6);
else
#endif
ss_size = sizeof(struct sockaddr_in);
/* allocate memory to hold the struct, the address and the name */
ai = curlx_calloc(1, sizeof(struct Curl_addrinfo) + ss_size + namelen);
if(!ai) {
result = CURLE_OUT_OF_MEMORY;
break;
}
/* put the address after the struct */
ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo));
/* then put the name after the address */
ai->ai_canonname = (char *)ai->ai_addr + ss_size;
memcpy(ai->ai_canonname, he->h_name, namelen);
if(!firstai)
/* store the pointer we want to return from this function */
firstai = ai;
if(prevai)
/* make the previous entry point to this */
prevai->ai_next = ai;
ai->ai_family = he->h_addrtype;
/* we return all names as STREAM, so when using this address for TFTP
the type must be ignored and conn->socktype be used instead! */
ai->ai_socktype = SOCK_STREAM;
ai->ai_addrlen = (curl_socklen_t)ss_size;
/* leave the rest of the struct filled with zero */
switch(ai->ai_family) {
case AF_INET:
addr = (void *)ai->ai_addr; /* storage area for this info */
memcpy(&addr->sin_addr, curr, sizeof(struct in_addr));
addr->sin_family = (CURL_SA_FAMILY_T)he->h_addrtype;
addr->sin_port = htons((unsigned short)port);
break;
#ifdef USE_IPV6
case AF_INET6:
addr6 = (void *)ai->ai_addr; /* storage area for this info */
memcpy(&addr6->sin6_addr, curr, sizeof(struct in6_addr));
addr6->sin6_family = (CURL_SA_FAMILY_T)he->h_addrtype;
addr6->sin6_port = htons((unsigned short)port);
break;
#endif
}
prevai = ai;
}
if(result) {
Curl_freeaddrinfo(firstai);
firstai = NULL;
}
return firstai;
}
#endif
/*
* ip2addr()
*
* This function takes an Internet address, in binary form, as input parameter
* along with its address family and the string version of the address, and it
* returns a Curl_addrinfo chain filled in correctly with information for the
* given address/host
*/
static CURLcode ip2addr(struct Curl_addrinfo **addrp, int af,
const void *inaddr, const char *hostname, int port)
{
struct Curl_addrinfo *ai;
size_t addrsize;
size_t namelen;
struct sockaddr_in *addr;
#ifdef USE_IPV6
struct sockaddr_in6 *addr6;
#endif
DEBUGASSERT(inaddr && hostname);
namelen = strlen(hostname) + 1;
*addrp = NULL;
if(af == AF_INET)
addrsize = sizeof(struct sockaddr_in);
#ifdef USE_IPV6
else if(af == AF_INET6)
addrsize = sizeof(struct sockaddr_in6);
#endif
else
return CURLE_BAD_FUNCTION_ARGUMENT;
/* allocate memory to hold the struct, the address and the name */
ai = curlx_calloc(1, sizeof(struct Curl_addrinfo) + addrsize + namelen);
if(!ai)
return CURLE_OUT_OF_MEMORY;
/* put the address after the struct */
ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo));
/* then put the name after the address */
ai->ai_canonname = (char *)ai->ai_addr + addrsize;
memcpy(ai->ai_canonname, hostname, namelen);
ai->ai_family = af;
ai->ai_socktype = SOCK_STREAM;
ai->ai_addrlen = (curl_socklen_t)addrsize;
/* leave the rest of the struct filled with zero */
switch(af) {
case AF_INET:
addr = (void *)ai->ai_addr; /* storage area for this info */
memcpy(&addr->sin_addr, inaddr, sizeof(struct in_addr));
addr->sin_family = (CURL_SA_FAMILY_T)af;
addr->sin_port = htons((unsigned short)port);
break;
#ifdef USE_IPV6
case AF_INET6:
addr6 = (void *)ai->ai_addr; /* storage area for this info */
memcpy(&addr6->sin6_addr, inaddr, sizeof(struct in6_addr));
addr6->sin6_family = (CURL_SA_FAMILY_T)af;
addr6->sin6_port = htons((unsigned short)port);
break;
#endif
}
*addrp = ai;
return CURLE_OK;
}
/*
* Given an IPv4 or IPv6 dotted string address, this converts it to a proper
* allocated Curl_addrinfo struct and returns it.
*/
CURLcode Curl_str2addr(const char *dotted, uint16_t port,
struct Curl_addrinfo **addrp)
{
struct in_addr in;
if(curlx_inet_pton(AF_INET, dotted, &in) > 0)
/* This is a dotted IP address 123.123.123.123-style */
return ip2addr(addrp, AF_INET, &in, dotted, port);
#ifdef USE_IPV6
{
struct in6_addr in6;
if(curlx_inet_pton(AF_INET6, dotted, &in6) > 0)
/* This is a dotted IPv6 address ::1-style */
return ip2addr(addrp, AF_INET6, &in6, dotted, port);
}
#endif
return CURLE_BAD_FUNCTION_ARGUMENT; /* bad input format */
}
bool Curl_is_ipv4addr(const char *address)
{
struct in_addr in;
return (curlx_inet_pton(AF_INET, address, &in) > 0);
}
bool Curl_is_ipaddr(const char *address)
{
if(Curl_is_ipv4addr(address))
return TRUE;
#ifdef USE_IPV6
{
struct in6_addr in6;
if(curlx_inet_pton(AF_INET6, address, &in6) > 0)
/* This is a dotted IPv6 address ::1-style */
return TRUE;
}
#endif
return FALSE;
}
bool Curl_looks_like_ipv6(const char *s, size_t len, bool maybe_url_encoded,
struct Curl_str *host, struct Curl_str *zone)
{
const char *zonep = NULL;
size_t i = 0, hlen = 0, zlen = 0;
if(host)
memset(host, 0, sizeof(*host));
if(zone)
memset(zone, 0, sizeof(*zone));
for(i = 0; i < len; ++i, ++hlen) {
if(!s[i] || !(ISXDIGIT(s[i]) || (s[i] == ':') || (s[i] == '.')))
break;
}
if((i < len) && (s[i] == '%')) { /* address followed by a zone? */
i += 1;
if(maybe_url_encoded && !strncmp("25", s + i, 2))
i += 2;
zonep = s + i;
for(; i < len; ++i, ++zlen) {
/* Allow unreserved characters as defined in RFC 3986 */
if(!s[i] || !(ISALPHA(s[i]) || ISXDIGIT(s[i]) || (s[i] == '-') ||
(s[i] == '.') || (s[i] == '_') || (s[i] == '~')))
break;
}
}
if(i != len)
return FALSE; /* invalid chars in zone */
if(host && hlen) {
host->str = s;
host->len = hlen;
}
if(zone && zlen) {
zone->str = zonep;
zone->len = zlen;
}
return TRUE;
}
#ifdef USE_UNIX_SOCKETS
/**
* Given a path to a Unix domain socket, return a newly allocated Curl_addrinfo
* struct initialized with this path.
* Returns CURLE_TOO_LARGE when path is too long.
*/
CURLcode Curl_unix2addr(const char *path, bool abstract,
struct Curl_addrinfo **paddr)
{
struct Curl_addrinfo *ai;
struct sockaddr_un *sa_un;
size_t path_len;
*paddr = NULL;
/* sun_path must be able to store the null-terminated path */
path_len = strlen(path) + 1;
if(path_len > sizeof(sa_un->sun_path))
return CURLE_TOO_LARGE;
ai = curlx_calloc(1,
sizeof(struct Curl_addrinfo) + sizeof(struct sockaddr_un));
if(!ai)
return CURLE_OUT_OF_MEMORY;
ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo));
sa_un = (void *)ai->ai_addr;
sa_un->sun_family = AF_UNIX;
ai->ai_family = AF_UNIX;
ai->ai_socktype = SOCK_STREAM; /* assume reliable transport for HTTP */
ai->ai_addrlen = (curl_socklen_t)
((offsetof(struct sockaddr_un, sun_path) + path_len) & 0x7FFFFFFF);
/* Abstract Unix domain socket have NULL prefix instead of suffix */
if(abstract)
memcpy(sa_un->sun_path + 1, path, path_len - 1);
else
memcpy(sa_un->sun_path, path, path_len); /* copy NUL byte */
*paddr = ai;
return CURLE_OK;
}
#endif
#if defined(CURL_MEMDEBUG) && defined(HAVE_GETADDRINFO) && \
defined(HAVE_FREEADDRINFO)
/*
* curl_dbg_freeaddrinfo()
*
* This is strictly for memory tracing and are using the same style as the
* family otherwise present in memdebug.c. I put these ones here since they
* require a bunch of structs I did not want to include in memdebug.c
*/
void curl_dbg_freeaddrinfo(struct addrinfo *freethis,
int line, const char *source)
{
curl_dbg_log("ADDR %s:%d freeaddrinfo(%p)\n",
source, line, (void *)freethis);
#ifdef USE_LWIPSOCK
lwip_freeaddrinfo(freethis);
#elif defined(USE_FAKE_GETADDRINFO)
{
const char *env = getenv("CURL_DNS_SERVER");
if(env)
r_freeaddrinfo(freethis);
else
/* !checksrc! disable BANNEDFUNC 1 */
freeaddrinfo(freethis);
}
#else
/* !checksrc! disable BANNEDFUNC 1 */
freeaddrinfo(freethis);
#endif
}
#endif /* CURL_MEMDEBUG && HAVE_FREEADDRINFO */
#if defined(CURL_MEMDEBUG) && defined(HAVE_GETADDRINFO)
/*
* curl_dbg_getaddrinfo()
*
* This is strictly for memory tracing and are using the same style as the
* family otherwise present in memdebug.c. I put these ones here since they
* require a bunch of structs I did not want to include in memdebug.c
*/
int curl_dbg_getaddrinfo(const char *hostname,
const char *service,
const struct addrinfo *hints,
struct addrinfo **result,
int line, const char *source)
{
#ifdef USE_LWIPSOCK
int res = lwip_getaddrinfo(hostname, service, hints, result);
#elif defined(USE_FAKE_GETADDRINFO)
int res;
const char *env = getenv("CURL_DNS_SERVER");
if(env)
res = r_getaddrinfo(hostname, service, hints, result);
else
/* !checksrc! disable BANNEDFUNC 1 */
res = getaddrinfo(hostname, service, hints, result);
#else
/* !checksrc! disable BANNEDFUNC 1 */
int res = getaddrinfo(hostname, service, hints, result);
#endif
if(res == 0)
/* success */
curl_dbg_log("ADDR %s:%d getaddrinfo() = %p\n", source, line,
(void *)*result);
else
curl_dbg_log("ADDR %s:%d getaddrinfo() failed\n", source, line);
return res;
}
#endif /* CURL_MEMDEBUG && HAVE_GETADDRINFO */
#if defined(HAVE_GETADDRINFO) && defined(USE_RESOLVE_ON_IPS)
/*
* Works around the sin6_port is always zero bug on iOS 9.3.2 and macOS
* 10.11.5.
*/
void Curl_addrinfo_set_port(struct Curl_addrinfo *addrinfo, int port)
{
struct Curl_addrinfo *ca;
struct sockaddr_in *addr;
#ifdef USE_IPV6
struct sockaddr_in6 *addr6;
#endif
for(ca = addrinfo; ca; ca = ca->ai_next) {
switch(ca->ai_family) {
case AF_INET:
addr = (void *)ca->ai_addr; /* storage area for this info */
addr->sin_port = htons((unsigned short)port);
break;
#ifdef USE_IPV6
case AF_INET6:
addr6 = (void *)ca->ai_addr; /* storage area for this info */
addr6->sin6_port = htons((unsigned short)port);
break;
#endif
}
}
}
#endif
+115
View File
@@ -0,0 +1,115 @@
#ifndef HEADER_CURL_ADDRINFO_H
#define HEADER_CURL_ADDRINFO_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
# include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#ifdef __VMS
# include <in.h>
# include <inet.h>
#endif
struct Curl_str;
/*
* Curl_addrinfo is our internal struct definition that we use to allow
* consistent internal handling of this data. We use this even when the system
* provides an addrinfo structure definition. We use this for all sorts of
* IPv4 and IPV6 builds.
*/
struct Curl_addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
curl_socklen_t ai_addrlen; /* Follow rfc3493 struct addrinfo */
char *ai_canonname;
struct sockaddr *ai_addr;
struct Curl_addrinfo *ai_next;
};
void Curl_freeaddrinfo(struct Curl_addrinfo *cahead);
/* Get the n-th addrinfo of family ai_family. */
struct Curl_addrinfo *Curl_addrinfo_get(struct Curl_addrinfo *ai,
int ai_family,
unsigned int n);
#ifdef HAVE_GETADDRINFO
int Curl_getaddrinfo_ex(const char *nodename,
const char *servname,
const struct addrinfo *hints,
struct Curl_addrinfo **result);
#endif
#if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETADDRINFO_THREADSAFE))
struct Curl_addrinfo *Curl_he2ai(const struct hostent *he, int port);
#endif
bool Curl_is_ipv4addr(const char *address);
bool Curl_is_ipaddr(const char *address);
bool Curl_looks_like_ipv6(const char *s, size_t len, bool maybe_url_encoded,
struct Curl_str *host, struct Curl_str *zone);
CURLcode Curl_str2addr(const char *dotted, uint16_t port,
struct Curl_addrinfo **addrp);
#ifdef USE_UNIX_SOCKETS
CURLcode Curl_unix2addr(const char *path, bool abstract,
struct Curl_addrinfo **paddr);
#endif
#if defined(CURL_MEMDEBUG) && defined(HAVE_GETADDRINFO) && \
defined(HAVE_FREEADDRINFO)
void curl_dbg_freeaddrinfo(struct addrinfo *freethis, int line,
const char *source);
#endif
#if defined(CURL_MEMDEBUG) && defined(HAVE_GETADDRINFO)
int curl_dbg_getaddrinfo(const char *hostname, const char *service,
const struct addrinfo *hints,
struct addrinfo **result, int line,
const char *source);
#endif
#ifdef HAVE_GETADDRINFO
#ifdef USE_RESOLVE_ON_IPS
void Curl_addrinfo_set_port(struct Curl_addrinfo *addrinfo, int port);
#else
#define Curl_addrinfo_set_port(x, y)
#endif
#endif
#endif /* HEADER_CURL_ADDRINFO_H */
+793
View File
@@ -0,0 +1,793 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
/* Location of default CA bundle */
#cmakedefine CURL_CA_BUNDLE "${CURL_CA_BUNDLE}"
/* define "1" to use built-in CA store of TLS backend */
#cmakedefine CURL_CA_FALLBACK 1
/* Location of default CA path */
#cmakedefine CURL_CA_PATH "${CURL_CA_PATH}"
/* Default SSL backend */
#cmakedefine CURL_DEFAULT_SSL_BACKEND "${CURL_DEFAULT_SSL_BACKEND}"
/* Use native CA store */
#cmakedefine CURL_CA_NATIVE 1
/* disables alt-svc */
#cmakedefine CURL_DISABLE_ALTSVC 1
/* disables cookies support */
#cmakedefine CURL_DISABLE_COOKIES 1
/* disables Basic authentication */
#cmakedefine CURL_DISABLE_BASIC_AUTH 1
/* disables Bearer authentication */
#cmakedefine CURL_DISABLE_BEARER_AUTH 1
/* disables Digest authentication */
#cmakedefine CURL_DISABLE_DIGEST_AUTH 1
/* disables Kerberos authentication */
#cmakedefine CURL_DISABLE_KERBEROS_AUTH 1
/* disables negotiate authentication */
#cmakedefine CURL_DISABLE_NEGOTIATE_AUTH 1
/* disables aws-sigv4 */
#cmakedefine CURL_DISABLE_AWS 1
/* disables HTTP Message Signatures (RFC 9421) */
#cmakedefine CURL_DISABLE_HTTPSIG 1
/* disables DICT */
#cmakedefine CURL_DISABLE_DICT 1
/* disables DNS-over-HTTPS */
#cmakedefine CURL_DISABLE_DOH 1
/* disables FILE */
#cmakedefine CURL_DISABLE_FILE 1
/* disables form api */
#cmakedefine CURL_DISABLE_FORM_API 1
/* disables FTP */
#cmakedefine CURL_DISABLE_FTP 1
/* disables curl_easy_options API for existing options to curl_easy_setopt */
#cmakedefine CURL_DISABLE_GETOPTIONS 1
/* disables GOPHER */
#cmakedefine CURL_DISABLE_GOPHER 1
/* disables headers-api support */
#cmakedefine CURL_DISABLE_HEADERS_API 1
/* disables HSTS support */
#cmakedefine CURL_DISABLE_HSTS 1
/* disables HTTP */
#cmakedefine CURL_DISABLE_HTTP 1
/* disabled all HTTP authentication methods */
#cmakedefine CURL_DISABLE_HTTP_AUTH 1
/* disables IMAP */
#cmakedefine CURL_DISABLE_IMAP 1
/* disables LDAP */
#cmakedefine CURL_DISABLE_LDAP 1
/* disables LDAPS */
#cmakedefine CURL_DISABLE_LDAPS 1
/* disables --libcurl option from the curl tool */
#cmakedefine CURL_DISABLE_LIBCURL_OPTION 1
/* disables MIME support */
#cmakedefine CURL_DISABLE_MIME 1
/* disables local binding support */
#cmakedefine CURL_DISABLE_BINDLOCAL 1
/* disables MQTT */
#cmakedefine CURL_DISABLE_MQTT 1
/* disables netrc parser */
#cmakedefine CURL_DISABLE_NETRC 1
/* enables NTLM support */
#cmakedefine CURL_ENABLE_NTLM 1
/* disables date parsing */
#cmakedefine CURL_DISABLE_PARSEDATE 1
/* disables POP3 */
#cmakedefine CURL_DISABLE_POP3 1
/* disables built-in progress meter */
#cmakedefine CURL_DISABLE_PROGRESS_METER 1
/* disables proxies */
#cmakedefine CURL_DISABLE_PROXY 1
/* disables IPFS from the curl tool */
#cmakedefine CURL_DISABLE_IPFS 1
/* disables RTSP */
#cmakedefine CURL_DISABLE_RTSP 1
/* disables SHA-512/256 hash algorithm */
#cmakedefine CURL_DISABLE_SHA512_256 1
/* disabled shuffle DNS feature */
#cmakedefine CURL_DISABLE_SHUFFLE_DNS 1
/* disables SMTP */
#cmakedefine CURL_DISABLE_SMTP 1
/* disabled WebSocket */
#cmakedefine CURL_DISABLE_WEBSOCKETS 1
/* disables use of socketpair for curl_multi_poll() */
#cmakedefine CURL_DISABLE_SOCKETPAIR 1
/* disables TELNET */
#cmakedefine CURL_DISABLE_TELNET 1
/* disables TFTP */
#cmakedefine CURL_DISABLE_TFTP 1
/* disables verbose strings */
#cmakedefine CURL_DISABLE_VERBOSE_STRINGS 1
/* disables unsafe CA bundle search on Windows from the curl tool */
#cmakedefine CURL_DISABLE_CA_SEARCH 1
/* safe CA bundle search (within the curl tool directory) on Windows */
#cmakedefine CURL_CA_SEARCH_SAFE 1
/* to make a symbol visible */
#cmakedefine CURL_EXTERN_SYMBOL ${CURL_EXTERN_SYMBOL}
/* Ensure using CURL_EXTERN_SYMBOL is possible */
#ifndef CURL_EXTERN_SYMBOL
#define CURL_EXTERN_SYMBOL
#endif
/* Allow SMB to work on Windows */
#cmakedefine USE_WIN32_CRYPTO 1
/* Use Windows LDAP implementation */
#cmakedefine USE_WIN32_LDAP 1
/* Define if you want to enable IPv6 support */
#cmakedefine USE_IPV6 1
/* Define to 1 if you have the alarm function. */
#cmakedefine HAVE_ALARM 1
/* Define to 1 if you have the arc4random function. */
#cmakedefine HAVE_ARC4RANDOM 1
/* Define to 1 if you have the <arpa/inet.h> header file. */
#cmakedefine HAVE_ARPA_INET_H 1
/* Define to 1 if you have _Atomic support. */
#cmakedefine HAVE_ATOMIC 1
/* Define to 1 if you have the `accept4' function. */
#cmakedefine HAVE_ACCEPT4 1
/* Define to 1 if you have the `fchmod' function. */
#cmakedefine HAVE_FCHMOD 1
/* Define to 1 if you have the `fnmatch' function. */
#cmakedefine HAVE_FNMATCH 1
/* Define to 1 if you have the `basename' function. */
#cmakedefine HAVE_BASENAME 1
/* Define to 1 if bool is an available type. */
#cmakedefine HAVE_BOOL_T 1
/* Define to 1 if you have the __builtin_available function. */
#cmakedefine HAVE_BUILTIN_AVAILABLE 1
/* Define to 1 if you have the clock_gettime function and monotonic timer. */
#cmakedefine HAVE_CLOCK_GETTIME_MONOTONIC 1
/* Define to 1 if you have the clock_gettime function and raw monotonic timer.
*/
#cmakedefine HAVE_CLOCK_GETTIME_MONOTONIC_RAW 1
/* Define to 1 if you have the `closesocket' function. */
#cmakedefine HAVE_CLOSESOCKET 1
/* Define to 1 if you have the `CloseSocket' function. */
#cmakedefine HAVE_CLOSESOCKET_CAMEL 1
/* Define to 1 if you have the <dirent.h> header file. */
#cmakedefine HAVE_DIRENT_H 1
/* Define to 1 if you have the `opendir' function. */
#cmakedefine HAVE_OPENDIR 1
/* Define to 1 if you have the memset_explicit (C23) function. */
#cmakedefine HAVE_MEMSET_EXPLICIT 1
/* Define to 1 if you have the memset_s (C11) function. */
#cmakedefine HAVE_MEMSET_S 1
/* Define to 1 if you have the fcntl function. */
#cmakedefine HAVE_FCNTL 1
/* Define to 1 if you have the <fcntl.h> header file. */
#cmakedefine HAVE_FCNTL_H 1
/* Define to 1 if you have a working fcntl O_NONBLOCK function. */
#cmakedefine HAVE_FCNTL_O_NONBLOCK 1
/* Define to 1 if you have the freeaddrinfo function. */
#cmakedefine HAVE_FREEADDRINFO 1
/* Define to 1 if you have the fseeko function. */
#cmakedefine HAVE_FSEEKO 1
/* Define to 1 if you have the fseeko declaration. */
#cmakedefine HAVE_DECL_FSEEKO 1
/* Define to 1 if you have a working getaddrinfo function. */
#cmakedefine HAVE_GETADDRINFO 1
/* Define to 1 if the getaddrinfo function is thread-safe. */
#cmakedefine HAVE_GETADDRINFO_THREADSAFE 1
/* Define to 1 if you have the `geteuid' function. */
#cmakedefine HAVE_GETEUID 1
/* Define to 1 if you have the `getppid' function. */
#cmakedefine HAVE_GETPPID 1
/* Define to 1 if you have the gethostbyname_r function. */
#cmakedefine HAVE_GETHOSTBYNAME_R 1
/* gethostbyname_r() takes 3 args */
#cmakedefine HAVE_GETHOSTBYNAME_R_3 1
/* gethostbyname_r() takes 5 args */
#cmakedefine HAVE_GETHOSTBYNAME_R_5 1
/* gethostbyname_r() takes 6 args */
#cmakedefine HAVE_GETHOSTBYNAME_R_6 1
/* Define to 1 if you have the gethostname function. */
#cmakedefine HAVE_GETHOSTNAME 1
/* Define to 1 if you have a working getifaddrs function. */
#cmakedefine HAVE_GETIFADDRS 1
/* Define to 1 if you have the `getpass_r' function. */
#cmakedefine HAVE_GETPASS_R 1
/* Define to 1 if you have the `getpeername' function. */
#cmakedefine HAVE_GETPEERNAME 1
/* Define to 1 if you have the `getsockname' function. */
#cmakedefine HAVE_GETSOCKNAME 1
/* Define to 1 if you have the `if_nametoindex' function. */
#cmakedefine HAVE_IF_NAMETOINDEX 1
/* Define to 1 if you have the `getpwuid' function. */
#cmakedefine HAVE_GETPWUID 1
/* Define to 1 if you have the `getpwuid_r' function. */
#cmakedefine HAVE_GETPWUID_R 1
/* Define to 1 if you have the `getrlimit' function. */
#cmakedefine HAVE_GETRLIMIT 1
/* Define to 1 if you have the `gettimeofday' function. */
#cmakedefine HAVE_GETTIMEOFDAY 1
/* Define to 1 if you have a working glibc-style strerror_r function. */
#cmakedefine HAVE_GLIBC_STRERROR_R 1
/* Define to 1 if you have a working gmtime_r function. */
#cmakedefine HAVE_GMTIME_R 1
/* if you have the gssapi libraries */
#cmakedefine HAVE_GSSAPI 1
/* if you have Apple GSS */
#cmakedefine HAVE_GSSAPPLE 1
/* if you have the GNU gssapi libraries */
#cmakedefine HAVE_GSSGNU 1
/* if you have gss_set_neg_mechs */
#cmakedefine HAVE_GSS_SET_NEG_MECHS 1
/* MIT Kerberos version */
#cmakedefine CURL_KRB5_VERSION ${CURL_KRB5_VERSION}
/* BoringSSL version */
#cmakedefine CURL_BORINGSSL_VERSION ${CURL_BORINGSSL_VERSION}
/* Patch stamp */
#cmakedefine CURL_PATCHSTAMP ${CURL_PATCHSTAMP}
/* Define to 1 if you have the <ifaddrs.h> header file. */
#cmakedefine HAVE_IFADDRS_H 1
/* Define to 1 if symbol `sa_family_t' exists */
#cmakedefine HAVE_SA_FAMILY_T 1
/* Define to 1 if you have the ioctlsocket function. */
#cmakedefine HAVE_IOCTLSOCKET 1
/* Define to 1 if you have the IoctlSocket camel case function. */
#cmakedefine HAVE_IOCTLSOCKET_CAMEL 1
/* Define to 1 if you have a working IoctlSocket camel case FIONBIO function.
*/
#cmakedefine HAVE_IOCTLSOCKET_CAMEL_FIONBIO 1
/* Define to 1 if you have a working ioctlsocket FIONBIO function. */
#cmakedefine HAVE_IOCTLSOCKET_FIONBIO 1
/* Define to 1 if you have a working ioctl FIONBIO function. */
#cmakedefine HAVE_IOCTL_FIONBIO 1
/* Define to 1 if you have a working ioctl SIOCGIFADDR function. */
#cmakedefine HAVE_IOCTL_SIOCGIFADDR 1
/* Define to 1 if you have the <io.h> header file. */
#cmakedefine HAVE_IO_H 1
/* Define to 1 if you have the lber.h header file. */
#cmakedefine HAVE_LBER_H 1
/* Use LDAPS implementation */
#cmakedefine HAVE_LDAP_SSL 1
/* Define to 1 if you have the ldap_ssl.h header file. */
#cmakedefine HAVE_LDAP_SSL_H 1
/* Define to 1 if you have the `ldap_url_parse' function. */
#cmakedefine HAVE_LDAP_URL_PARSE 1
/* Define to 1 if you have the <libgen.h> header file. */
#cmakedefine HAVE_LIBGEN_H 1
/* Define to 1 if you have the `idn2' library (-lidn2). */
#cmakedefine HAVE_LIBIDN2 1
/* Define to 1 if you have the idn2.h header file. */
#cmakedefine HAVE_IDN2_H 1
/* if zlib is available */
#cmakedefine HAVE_LIBZ 1
/* if brotli is available */
#cmakedefine HAVE_BROTLI 1
/* if zstd is available */
#cmakedefine HAVE_ZSTD 1
/* Define to 1 if you have the <locale.h> header file. */
#cmakedefine HAVE_LOCALE_H 1
/* Define to 1 if you have a working localtime_r function. */
#cmakedefine HAVE_LOCALTIME_R 1
/* Define to 1 if you have the 'suseconds_t' data type. */
#cmakedefine HAVE_SUSECONDS_T 1
/* Define to 1 if you have the <netdb.h> header file. */
#cmakedefine HAVE_NETDB_H 1
/* Define to 1 if you have the <netinet/in.h> header file. */
#cmakedefine HAVE_NETINET_IN_H 1
/* Define to 1 if you have the <netinet/in6.h> header file. */
#cmakedefine HAVE_NETINET_IN6_H 1
/* Define to 1 if you have the <netinet/tcp.h> header file. */
#cmakedefine HAVE_NETINET_TCP_H 1
/* Define to 1 if you have the <netinet/udp.h> header file. */
#cmakedefine HAVE_NETINET_UDP_H 1
/* Define to 1 if you have the <netinet/ip.h> header file. */
#cmakedefine HAVE_NETINET_IP_H 1
/* Define to 1 if you have the <linux/tcp.h> header file. */
#cmakedefine HAVE_LINUX_TCP_H 1
/* Define to 1 if you have the <net/if.h> header file. */
#cmakedefine HAVE_NET_IF_H 1
/* Define to 1 if you have the `pipe' function. */
#cmakedefine HAVE_PIPE 1
/* Define to 1 if you have the `pipe2' function. */
#cmakedefine HAVE_PIPE2 1
/* Define to 1 if you have the `eventfd' function. */
#cmakedefine HAVE_EVENTFD 1
/* If you have poll */
#cmakedefine HAVE_POLL 1
/* If you have realpath */
#cmakedefine HAVE_REALPATH 1
/* Define to 1 if you have the <poll.h> header file. */
#cmakedefine HAVE_POLL_H 1
/* Define to 1 if you have a working POSIX-style strerror_r function. */
#cmakedefine HAVE_POSIX_STRERROR_R 1
/* Define to 1 if you have the <pwd.h> header file. */
#cmakedefine HAVE_PWD_H 1
/* Define to 1 if OpenSSL has the `SSL_set0_wbio` function. */
#cmakedefine HAVE_SSL_SET0_WBIO 1
/* Define to 1 if you have the recv function. */
#cmakedefine HAVE_RECV 1
/* Define to 1 if you have the sched_yield function. */
#cmakedefine HAVE_SCHED_YIELD 1
/* Define to 1 if you have the send function. */
#cmakedefine HAVE_SEND 1
/* Define to 1 if you have the sendmsg function. */
#cmakedefine HAVE_SENDMSG 1
/* Define to 1 if you have the sendmmsg function. */
#cmakedefine HAVE_SENDMMSG 1
/* Define to 1 if you have the 'fsetxattr' function. */
#cmakedefine HAVE_FSETXATTR 1
/* fsetxattr() takes 5 args */
#cmakedefine HAVE_FSETXATTR_5 1
/* fsetxattr() takes 6 args */
#cmakedefine HAVE_FSETXATTR_6 1
/* Define to 1 if you have the `setlocale' function. */
#cmakedefine HAVE_SETLOCALE 1
/* Define to 1 if you have the `setrlimit' function. */
#cmakedefine HAVE_SETRLIMIT 1
/* Define to 1 if you have a working setsockopt SO_NONBLOCK function. */
#cmakedefine HAVE_SETSOCKOPT_SO_NONBLOCK 1
/* Define to 1 if you have the sigaction function. */
#cmakedefine HAVE_SIGACTION 1
/* Define to 1 if you have the siginterrupt function. */
#cmakedefine HAVE_SIGINTERRUPT 1
/* Define to 1 if you have the signal function. */
#cmakedefine HAVE_SIGNAL 1
/* Define to 1 if you have the sigsetjmp function or macro. */
#cmakedefine HAVE_SIGSETJMP 1
/* Define to 1 if struct sockaddr_in6 has the sin6_scope_id member */
#cmakedefine HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
/* Define to 1 if you have the `socket' function. */
#cmakedefine HAVE_SOCKET 1
/* Define to 1 if you have the <proto/bsdsocket.h> header file. */
#cmakedefine HAVE_PROTO_BSDSOCKET_H 1
/* Define to 1 if you have the socketpair function. */
#cmakedefine HAVE_SOCKETPAIR 1
/* Define to 1 if you have the <stdatomic.h> header file. */
#cmakedefine HAVE_STDATOMIC_H 1
/* Define to 1 if you have the <stdbool.h> header file. */
#cmakedefine HAVE_STDBOOL_H 1
/* Define to 1 if you have the strcasecmp function. */
#cmakedefine HAVE_STRCASECMP 1
/* Define to 1 if you have the strcmpi function. */
#cmakedefine HAVE_STRCMPI 1
/* Define to 1 if you have the strerror_r function. */
#cmakedefine HAVE_STRERROR_R 1
/* Define to 1 if you have the stricmp function. */
#cmakedefine HAVE_STRICMP 1
/* Define to 1 if you have the <strings.h> header file. */
#cmakedefine HAVE_STRINGS_H 1
/* Define to 1 if you have the <stropts.h> header file. */
#cmakedefine HAVE_STROPTS_H 1
/* Define to 1 if you have the memrchr function. */
#cmakedefine HAVE_MEMRCHR 1
/* if struct sockaddr_storage is defined */
#cmakedefine HAVE_STRUCT_SOCKADDR_STORAGE 1
/* Define to 1 if you have the timeval struct. */
#cmakedefine HAVE_STRUCT_TIMEVAL 1
/* Define to 1 if you have the <sys/eventfd.h> header file. */
#cmakedefine HAVE_SYS_EVENTFD_H 1
/* Define to 1 if you have the <sys/filio.h> header file. */
#cmakedefine HAVE_SYS_FILIO_H 1
/* Define to 1 if you have the <sys/ioctl.h> header file. */
#cmakedefine HAVE_SYS_IOCTL_H 1
/* Define to 1 if you have the <sys/param.h> header file. */
#cmakedefine HAVE_SYS_PARAM_H 1
/* Define to 1 if you have the <sys/poll.h> header file. */
#cmakedefine HAVE_SYS_POLL_H 1
/* Define to 1 if you have the <sys/resource.h> header file. */
#cmakedefine HAVE_SYS_RESOURCE_H 1
/* Define to 1 if you have the <sys/select.h> header file. */
#cmakedefine HAVE_SYS_SELECT_H 1
/* Define to 1 if you have the <sys/sockio.h> header file. */
#cmakedefine HAVE_SYS_SOCKIO_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#cmakedefine HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <sys/un.h> header file. */
#cmakedefine HAVE_SYS_UN_H 1
/* Define to 1 if you have the <sys/utime.h> header file. */
#cmakedefine HAVE_SYS_UTIME_H 1
/* Define to 1 if you have the <termios.h> header file. */
#cmakedefine HAVE_TERMIOS_H 1
/* Define to 1 if you have the <termio.h> header file. */
#cmakedefine HAVE_TERMIO_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#cmakedefine HAVE_UNISTD_H 1
/* Define to 1 if you have the `utime' function. */
#cmakedefine HAVE_UTIME 1
/* Define to 1 if you have the `utimes' function. */
#cmakedefine HAVE_UTIMES 1
/* Define to 1 if you have the <utime.h> header file. */
#cmakedefine HAVE_UTIME_H 1
/* Define this symbol if your OS supports changing the contents of argv */
#cmakedefine HAVE_WRITABLE_ARGV 1
/* Define this if time_t is unsigned */
#cmakedefine HAVE_TIME_T_UNSIGNED 1
/* Define to 1 if _REENTRANT preprocessor symbol must be defined. */
#cmakedefine NEED_REENTRANT 1
/* cpu-machine-OS */
#cmakedefine CURL_OS ${CURL_OS}
/* Note: SIZEOF_* variables are fetched with CMake through check_type_size().
As per CMake documentation on CheckTypeSize, C preprocessor code is
generated by CMake into SIZEOF_*_CODE. This is what we use in the
following statements.
Ref: https://cmake.org/cmake/help/latest/module/CheckTypeSize.html
*/
/* The size of `int', as computed by sizeof. */
${SIZEOF_INT_CODE}
/* The size of `long', as computed by sizeof. */
${SIZEOF_LONG_CODE}
/* The size of `off_t', as computed by sizeof. */
${SIZEOF_OFF_T_CODE}
/* The size of `curl_off_t', as computed by sizeof. */
${SIZEOF_CURL_OFF_T_CODE}
/* The size of `curl_socket_t', as computed by sizeof. */
${SIZEOF_CURL_SOCKET_T_CODE}
/* The size of `size_t', as computed by sizeof. */
${SIZEOF_SIZE_T_CODE}
/* The size of `time_t', as computed by sizeof. */
${SIZEOF_TIME_T_CODE}
/* Define if you have POSIX pthreads */
#cmakedefine HAVE_THREADS_POSIX 1
/* Define if you want to enable c-ares support */
#cmakedefine USE_ARES 1
/* Define if you want to enable c-ares DNS lookup */
#cmakedefine USE_RESOLV_ARES 1
/* Define if you want to enable threaded DNS lookup */
#cmakedefine USE_RESOLV_THREADED 1
/* if GnuTLS is enabled */
#cmakedefine USE_GNUTLS 1
/* if SSL session export support is available */
#cmakedefine USE_SSLS_EXPORT 1
/* if mbedTLS is enabled */
#cmakedefine USE_MBEDTLS 1
/* if mbedTLS <4 has the mbedtls_des_crypt_ecb function. */
#cmakedefine HAVE_MBEDTLS_DES_CRYPT_ECB 1
/* if Rustls is enabled */
#cmakedefine USE_RUSTLS 1
/* if wolfSSL is enabled */
#cmakedefine USE_WOLFSSL 1
/* if wolfSSL has the wolfSSL_get_peer_certificate function. */
#cmakedefine HAVE_WOLFSSL_GET_PEER_CERTIFICATE 1
/* if wolfSSL has the wolfSSL_UseALPN function. */
#cmakedefine HAVE_WOLFSSL_USEALPN 1
/* if wolfSSL has the wolfSSL_BIO_new function. */
#cmakedefine HAVE_WOLFSSL_BIO_NEW 1
/* if wolfSSL has the wolfSSL_BIO_set_shutdown function. */
#cmakedefine HAVE_WOLFSSL_BIO_SET_SHUTDOWN 1
/* if wolfSSL has the wc_Des_EcbEncrypt function. */
#cmakedefine HAVE_WC_DES_ECBENCRYPT 1
/* if libssh is in use */
#cmakedefine USE_LIBSSH 1
/* if libssh2 is in use */
#cmakedefine USE_LIBSSH2 1
/* if libpsl is in use */
#cmakedefine USE_LIBPSL 1
/* if you want to use OpenLDAP code instead of legacy LDAP implementation */
#cmakedefine USE_OPENLDAP 1
/* if OpenSSL is in use */
#cmakedefine USE_OPENSSL 1
/* if AmiSSL is in use */
#cmakedefine USE_AMISSL 1
/* if GSASL is in use */
#cmakedefine USE_GSASL 1
/* if libuv is in use */
#cmakedefine USE_LIBUV 1
/* if HTTP/3 proxy support is available */
#cmakedefine USE_PROXY_HTTP3 1
/* Define to 1 if you have the <uv.h> header file. */
#cmakedefine HAVE_UV_H 1
/* if libbacktrace is in use */
#cmakedefine USE_BACKTRACE 1
/* Define to 1 if you do not want the OpenSSL configuration to be loaded
automatically */
#cmakedefine CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG 1
/* to enable NGHTTP2 */
#cmakedefine USE_NGHTTP2 1
/* to enable NGTCP2 */
#cmakedefine USE_NGTCP2 1
/* to enable NGHTTP3 */
#cmakedefine USE_NGHTTP3 1
/* to enable quiche */
#cmakedefine USE_QUICHE 1
/* to enable openssl + ngtcp2 + nghttp3 */
#cmakedefine OPENSSL_QUIC_API2 1
/* Define to 1 if you have the quiche_conn_set_qlog_fd function. */
#cmakedefine HAVE_QUICHE_CONN_SET_QLOG_FD 1
/* if Unix domain sockets are enabled */
#cmakedefine USE_UNIX_SOCKETS 1
/* to enable SSPI support */
#cmakedefine USE_WINDOWS_SSPI 1
/* to enable Windows SSL */
#cmakedefine USE_SCHANNEL 1
/* if Watt-32 is in use */
#cmakedefine USE_WATT32 1
/* enable multiple SSL backends */
#cmakedefine CURL_WITH_MULTI_SSL 1
/* Number of bits in a file offset, on hosts where this is settable. */
#cmakedefine _FILE_OFFSET_BITS ${_FILE_OFFSET_BITS}
/* the signed version of size_t */
#cmakedefine ssize_t ${ssize_t}
/* Define to 1 if you have the mach_absolute_time function. */
#cmakedefine HAVE_MACH_ABSOLUTE_TIME 1
/* to enable Windows IDN */
#cmakedefine USE_WIN32_IDN 1
/* to enable Apple IDN */
#cmakedefine USE_APPLE_IDN 1
/* to enable Apple OS-native certificate verification */
#cmakedefine USE_APPLE_SECTRUST 1
/* to use Apple fast UDP (SYS_recvmsg_x, SYS_sendmsg_x) */
#cmakedefine USE_APPLE_FAST_UDP
/* Define to 1 to query for HTTPSRR when using DoH */
#cmakedefine USE_HTTPSRR 1
/* if ECH support is available */
#cmakedefine USE_ECH 1
/* Define to 1 if you have the wolfSSL_CTX_GenerateEchConfig function. */
#cmakedefine HAVE_WOLFSSL_CTX_GENERATEECHCONFIG 1
/* Define to 1 if you have the SSL_set1_ech_config_list function. */
#cmakedefine HAVE_SSL_SET1_ECH_CONFIG_LIST 1
/* Define to 1 if OpenSSL has the DES_ecb_encrypt function. */
#cmakedefine HAVE_DES_ECB_ENCRYPT 1
+50
View File
@@ -0,0 +1,50 @@
#ifndef HEADER_CURL_CTYPE_H
#define HEADER_CURL_CTYPE_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#define ISLOWHEXALPHA(x) (((x) >= 'a') && ((x) <= 'f'))
#define ISUPHEXALPHA(x) (((x) >= 'A') && ((x) <= 'F'))
#define ISLOWCNTRL(x) ((unsigned char)(x) <= 0x1f)
#define IS7F(x) ((x) == 0x7f)
#define ISPRINT(x) (((x) >= ' ') && ((x) <= 0x7e))
#define ISGRAPH(x) (((x) > ' ') && ((x) <= 0x7e))
#define ISCNTRL(x) (ISLOWCNTRL(x) || IS7F(x))
#define ISALPHA(x) (ISLOWER(x) || ISUPPER(x))
#define ISXDIGIT(x) (ISDIGIT(x) || ISLOWHEXALPHA(x) || ISUPHEXALPHA(x))
#define ISODIGIT(x) (((x) >= '0') && ((x) <= '7'))
#define ISALNUM(x) (ISDIGIT(x) || ISLOWER(x) || ISUPPER(x))
#define ISUPPER(x) (((x) >= 'A') && ((x) <= 'Z'))
#define ISLOWER(x) (((x) >= 'a') && ((x) <= 'z'))
#define ISDIGIT(x) (((x) >= '0') && ((x) <= '9'))
#define ISBLANK(x) (((x) == ' ') || ((x) == '\t'))
#define ISSPACE(x) (ISBLANK(x) || (((x) >= 0xa) && ((x) <= 0x0d)))
#define ISURLPUNTCS(x) \
(((x) == '-') || ((x) == '.') || ((x) == '_') || ((x) == '~'))
#define ISUNRESERVED(x) (ISALNUM(x) || ISURLPUNTCS(x))
#define ISNEWLINE(x) (((x) == '\n') || (x) == '\r')
#endif /* HEADER_CURL_CTYPE_H */
+175
View File
@@ -0,0 +1,175 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HTTPSIG)
/* Please keep the SSL backend-specific #if branches in this order:
*
* 1. USE_OPENSSL
* 2. USE_WOLFSSL
* 3. USE_GNUTLS
* 4. USE_MBEDTLS
*/
#include "curl_ed25519.h"
#ifdef USE_WOLFSSL
#include <wolfssl/options.h>
#include <wolfssl/wolfcrypt/settings.h>
#endif
#ifdef USE_OPENSSL
#include <openssl/evp.h>
CURLcode Curl_ed25519_sign(const unsigned char *key, size_t keylen,
const unsigned char *msg, size_t msglen,
unsigned char *sig, size_t *siglen)
{
EVP_PKEY *pkey;
EVP_MD_CTX *mdctx;
size_t slen;
int rc;
if(keylen != CURL_ED25519_KEYLEN)
return CURLE_BAD_FUNCTION_ARGUMENT;
pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, NULL, key, keylen);
if(!pkey)
return CURLE_AUTH_ERROR;
mdctx = EVP_MD_CTX_new();
if(!mdctx) {
EVP_PKEY_free(pkey);
return CURLE_OUT_OF_MEMORY;
}
rc = EVP_DigestSignInit(mdctx, NULL, NULL, NULL, pkey);
if(rc != 1) {
EVP_MD_CTX_free(mdctx);
EVP_PKEY_free(pkey);
return CURLE_AUTH_ERROR;
}
slen = CURL_ED25519_SIGLEN;
rc = EVP_DigestSign(mdctx, sig, &slen, msg, msglen);
EVP_MD_CTX_free(mdctx);
EVP_PKEY_free(pkey);
if(rc != 1)
return CURLE_AUTH_ERROR;
*siglen = slen;
return CURLE_OK;
}
#elif defined(USE_WOLFSSL) && \
(defined(HAVE_ED25519) || defined(WOLFSSL_CURVE25519_USE_ED25519)) && \
defined(HAVE_ED25519_KEY_IMPORT) && defined(HAVE_ED25519_SIGN)
#include <wolfssl/wolfcrypt/ed25519.h>
#include <wolfssl/wolfcrypt/error-crypt.h>
#include <wolfssl/wolfcrypt/random.h>
CURLcode Curl_ed25519_sign(const unsigned char *key, size_t keylen,
const unsigned char *msg, size_t msglen,
unsigned char *sig, size_t *siglen)
{
int ret;
ed25519_key edkey;
word32 outlen;
unsigned char pubkey[ED25519_PUB_KEY_SIZE];
if(keylen != ED25519_KEY_SIZE)
return CURLE_BAD_FUNCTION_ARGUMENT;
ret = wc_ed25519_init(&edkey);
if(ret)
return CURLE_AUTH_ERROR;
ret = wc_ed25519_import_private_only(key, ED25519_KEY_SIZE, &edkey);
if(ret)
goto fail;
ret = wc_ed25519_make_public(&edkey, pubkey, ED25519_PUB_KEY_SIZE);
if(ret)
goto fail;
ret = wc_ed25519_import_private_key(key, ED25519_KEY_SIZE,
pubkey, ED25519_PUB_KEY_SIZE, &edkey);
if(ret)
goto fail;
outlen = ED25519_SIG_SIZE;
ret = wc_ed25519_sign_msg(msg, (word32)msglen, sig, &outlen, &edkey);
if(ret)
goto fail;
*siglen = (size_t)outlen;
wc_ed25519_free(&edkey);
return CURLE_OK;
fail:
wc_ed25519_free(&edkey);
return CURLE_AUTH_ERROR;
}
#elif defined(USE_GNUTLS)
#include <nettle/eddsa.h>
CURLcode Curl_ed25519_sign(const unsigned char *key, size_t keylen,
const unsigned char *msg, size_t msglen,
unsigned char *sig, size_t *siglen)
{
uint8_t pubkey[ED25519_KEY_SIZE];
if(keylen != ED25519_KEY_SIZE)
return CURLE_BAD_FUNCTION_ARGUMENT;
nettle_ed25519_sha512_public_key(pubkey, key);
nettle_ed25519_sha512_sign(pubkey, key, msglen, msg, sig);
*siglen = CURL_ED25519_SIGLEN;
return CURLE_OK;
}
#else /* no Ed25519-capable backend */
CURLcode Curl_ed25519_sign(const unsigned char *key, size_t keylen,
const unsigned char *msg, size_t msglen,
unsigned char *sig, size_t *siglen)
{
(void)key;
(void)keylen;
(void)msg;
(void)msglen;
(void)sig;
(void)siglen;
return CURLE_NOT_BUILT_IN;
}
#endif /* Ed25519 backends */
#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_HTTPSIG */
+44
View File
@@ -0,0 +1,44 @@
#ifndef HEADER_CURL_ED25519_H
#define HEADER_CURL_ED25519_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HTTPSIG)
#define CURL_ED25519_SIGLEN 64
#define CURL_ED25519_KEYLEN 32
/* Sign with Ed25519 (RFC 8032).
* key/keylen: raw 32-byte private seed
* msg/msglen: data to sign
* sig: output buffer (at least CURL_ED25519_SIGLEN bytes)
* siglen: out - actual signature length on success
* Returns CURLE_OK or CURLE_NOT_BUILT_IN if no backend supports Ed25519. */
CURLcode Curl_ed25519_sign(const unsigned char *key, size_t keylen,
const unsigned char *msg, size_t msglen,
unsigned char *sig, size_t *siglen);
#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_HTTPSIG */
#endif /* HEADER_CURL_ED25519_H */
+83
View File
@@ -0,0 +1,83 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include "curl_endian.h"
/*
* Curl_read16_le()
*
* This function converts a 16-bit integer from the little endian format, as
* used in the incoming package to whatever endian format we are using
* natively.
*
* Parameters:
*
* buf [in] - A pointer to a 2-byte buffer.
*
* Returns the integer.
*/
unsigned short Curl_read16_le(const unsigned char *buf)
{
return (unsigned short)(((unsigned short)buf[0]) |
((unsigned short)buf[1] << 8));
}
/*
* Curl_read32_le()
*
* This function converts a 32-bit integer from the little endian format, as
* used in the incoming package to whatever endian format we are using
* natively.
*
* Parameters:
*
* buf [in] - A pointer to a 4-byte buffer.
*
* Returns the integer.
*/
unsigned int Curl_read32_le(const unsigned char *buf)
{
return ((unsigned int)buf[0]) | ((unsigned int)buf[1] << 8) |
((unsigned int)buf[2] << 16) | ((unsigned int)buf[3] << 24);
}
/*
* Curl_read16_be()
*
* This function converts a 16-bit integer from the big endian format, as
* used in the incoming package to whatever endian format we are using
* natively.
*
* Parameters:
*
* buf [in] - A pointer to a 2-byte buffer.
*
* Returns the integer.
*/
unsigned short Curl_read16_be(const unsigned char *buf)
{
return (unsigned short)(((unsigned short)buf[0] << 8) |
((unsigned short)buf[1]));
}
+36
View File
@@ -0,0 +1,36 @@
#ifndef HEADER_CURL_ENDIAN_H
#define HEADER_CURL_ENDIAN_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
/* Converts a 16-bit integer from little endian */
unsigned short Curl_read16_le(const unsigned char *buf);
/* Converts a 32-bit integer from little endian */
unsigned int Curl_read32_le(const unsigned char *buf);
/* Converts a 16-bit integer from big endian */
unsigned short Curl_read16_be(const unsigned char *buf);
#endif /* HEADER_CURL_ENDIAN_H */
+418
View File
@@ -0,0 +1,418 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_FTP
#include "curl_fnmatch.h"
#ifndef HAVE_FNMATCH
#define CURLFNM_CHARSET_LEN (sizeof(char) * 256)
#define CURLFNM_CHSET_SIZE (CURLFNM_CHARSET_LEN + 15)
#define CURLFNM_NEGATE CURLFNM_CHARSET_LEN
#define CURLFNM_ALNUM (CURLFNM_CHARSET_LEN + 1)
#define CURLFNM_DIGIT (CURLFNM_CHARSET_LEN + 2)
#define CURLFNM_XDIGIT (CURLFNM_CHARSET_LEN + 3)
#define CURLFNM_ALPHA (CURLFNM_CHARSET_LEN + 4)
#define CURLFNM_PRINT (CURLFNM_CHARSET_LEN + 5)
#define CURLFNM_BLANK (CURLFNM_CHARSET_LEN + 6)
#define CURLFNM_LOWER (CURLFNM_CHARSET_LEN + 7)
#define CURLFNM_GRAPH (CURLFNM_CHARSET_LEN + 8)
#define CURLFNM_SPACE (CURLFNM_CHARSET_LEN + 9)
#define CURLFNM_UPPER (CURLFNM_CHARSET_LEN + 10)
typedef enum {
CURLFNM_SCHS_DEFAULT = 0,
CURLFNM_SCHS_RIGHTBR,
CURLFNM_SCHS_RIGHTBRLEFTBR
} setcharset_state;
typedef enum {
CURLFNM_PKW_INIT = 0,
CURLFNM_PKW_DDOT
} parsekey_state;
typedef enum {
CCLASS_OTHER = 0,
CCLASS_DIGIT,
CCLASS_UPPER,
CCLASS_LOWER
} char_class;
#define SETCHARSET_OK 1
#define SETCHARSET_FAIL 0
static int parsekeyword(const unsigned char **pattern, unsigned char *charset)
{
parsekey_state state = CURLFNM_PKW_INIT;
char keyword[10] = { 0 };
size_t i;
const unsigned char *p = *pattern;
bool found = FALSE;
for(i = 0; !found; i++) {
char c = (char)*p++;
if(i >= sizeof(keyword))
return SETCHARSET_FAIL;
switch(state) {
case CURLFNM_PKW_INIT:
if(ISLOWER(c))
keyword[i] = c;
else if(c == ':')
state = CURLFNM_PKW_DDOT;
else
return SETCHARSET_FAIL;
break;
case CURLFNM_PKW_DDOT:
if(c == ']')
found = TRUE;
else
return SETCHARSET_FAIL;
}
}
#undef KEYLEN
*pattern = p; /* move caller's pattern pointer */
if(!strcmp(keyword, "digit"))
charset[CURLFNM_DIGIT] = 1;
else if(!strcmp(keyword, "alnum"))
charset[CURLFNM_ALNUM] = 1;
else if(!strcmp(keyword, "alpha"))
charset[CURLFNM_ALPHA] = 1;
else if(!strcmp(keyword, "xdigit"))
charset[CURLFNM_XDIGIT] = 1;
else if(!strcmp(keyword, "print"))
charset[CURLFNM_PRINT] = 1;
else if(!strcmp(keyword, "graph"))
charset[CURLFNM_GRAPH] = 1;
else if(!strcmp(keyword, "space"))
charset[CURLFNM_SPACE] = 1;
else if(!strcmp(keyword, "blank"))
charset[CURLFNM_BLANK] = 1;
else if(!strcmp(keyword, "upper"))
charset[CURLFNM_UPPER] = 1;
else if(!strcmp(keyword, "lower"))
charset[CURLFNM_LOWER] = 1;
else
return SETCHARSET_FAIL;
return SETCHARSET_OK;
}
/* Return the character class. */
static char_class charclass(unsigned char c)
{
if(ISUPPER(c))
return CCLASS_UPPER;
if(ISLOWER(c))
return CCLASS_LOWER;
if(ISDIGIT(c))
return CCLASS_DIGIT;
return CCLASS_OTHER;
}
/* Include a character or a range in set. */
static void setcharorrange(const unsigned char **pp, unsigned char *charset)
{
const unsigned char *p = (*pp)++;
unsigned char c = *p++;
charset[c] = 1;
if(ISALNUM(c) && *p++ == '-') {
char_class cc = charclass(c);
unsigned char endrange = *p++;
if(endrange == '\\')
endrange = *p++;
if(endrange >= c && charclass(endrange) == cc) {
while(c++ != endrange)
if(charclass(c) == cc) /* Chars in class may be not consecutive. */
charset[c] = 1;
*pp = p;
}
}
}
/* returns 1 (TRUE) if pattern is OK, 0 if is bad ("p" is pattern pointer) */
static int setcharset(const unsigned char **p, unsigned char *charset)
{
setcharset_state state = CURLFNM_SCHS_DEFAULT;
bool something_found = FALSE;
unsigned char c;
memset(charset, 0, CURLFNM_CHSET_SIZE);
for(;;) {
c = **p;
if(!c)
return SETCHARSET_FAIL;
switch(state) {
case CURLFNM_SCHS_DEFAULT:
if(c == ']') {
if(something_found)
return SETCHARSET_OK;
something_found = TRUE;
state = CURLFNM_SCHS_RIGHTBR;
charset[c] = 1;
(*p)++;
}
else if(c == '[') {
const unsigned char *pp = *p + 1;
if(*pp++ == ':' && parsekeyword(&pp, charset))
*p = pp;
else {
charset[c] = 1;
(*p)++;
}
something_found = TRUE;
}
else if(c == '^' || c == '!') {
if(!something_found) {
if(charset[CURLFNM_NEGATE]) {
charset[c] = 1;
something_found = TRUE;
}
else
charset[CURLFNM_NEGATE] = 1; /* negate charset */
}
else
charset[c] = 1;
(*p)++;
}
else if(c == '\\') {
c = *(++(*p));
if(c)
setcharorrange(p, charset);
else
charset['\\'] = 1;
something_found = TRUE;
}
else {
setcharorrange(p, charset);
something_found = TRUE;
}
break;
case CURLFNM_SCHS_RIGHTBR:
if(c == '[') {
state = CURLFNM_SCHS_RIGHTBRLEFTBR;
charset[c] = 1;
(*p)++;
}
else if(c == ']') {
return SETCHARSET_OK;
}
else if(ISPRINT(c)) {
charset[c] = 1;
(*p)++;
state = CURLFNM_SCHS_DEFAULT;
}
else
/* used 'goto fail' instead of 'return SETCHARSET_FAIL' to avoid a
* nonsense warning 'statement not reached' at end of the fnc when
* compiling on Solaris */
goto fail;
break;
case CURLFNM_SCHS_RIGHTBRLEFTBR:
if(c == ']')
return SETCHARSET_OK;
state = CURLFNM_SCHS_DEFAULT;
charset[c] = 1;
(*p)++;
break;
}
}
fail:
return SETCHARSET_FAIL;
}
/* match one pattern token against one string character, advancing both */
static int matchtoken(const unsigned char **pp, const unsigned char **sp)
{
const unsigned char *p = *pp;
const unsigned char *s = *sp;
switch(*p) {
case '?':
break;
case '\\':
if(p[1])
p++;
if(*s != *p)
return 0;
break;
case '[': {
unsigned char charset[CURLFNM_CHSET_SIZE];
const unsigned char *pp2 = p + 1; /* Copy in case of syntax error. */
bool found = FALSE;
if(!setcharset(&pp2, charset))
return -1; /* Syntax error in set; mismatch! */
if(charset[(unsigned int)*s])
found = TRUE;
else if(charset[CURLFNM_ALNUM])
found = ISALNUM(*s);
else if(charset[CURLFNM_ALPHA])
found = ISALPHA(*s);
else if(charset[CURLFNM_DIGIT])
found = ISDIGIT(*s);
else if(charset[CURLFNM_XDIGIT])
found = ISXDIGIT(*s);
else if(charset[CURLFNM_PRINT])
found = ISPRINT(*s);
else if(charset[CURLFNM_SPACE])
found = ISBLANK(*s);
else if(charset[CURLFNM_UPPER])
found = ISUPPER(*s);
else if(charset[CURLFNM_LOWER])
found = ISLOWER(*s);
else if(charset[CURLFNM_BLANK])
found = ISBLANK(*s);
else if(charset[CURLFNM_GRAPH])
found = ISGRAPH(*s);
if(charset[CURLFNM_NEGATE])
found = !found;
if(!found)
return 0;
*pp = pp2 + 1;
*sp = s + 1;
return 1;
}
default:
if(*p != *s)
return 0;
break;
}
*pp = p + 1;
*sp = s + 1;
return 1;
}
/* greedy match with backtracking to the most recent '*' */
static int loop(const unsigned char *pattern, const unsigned char *string)
{
const unsigned char *p = pattern;
const unsigned char *s = string;
const unsigned char *star_p = NULL;
const unsigned char *star_s = NULL;
int maxstars = 2;
while(*s) {
if(*p == '*') {
if(!maxstars)
return CURL_FNMATCH_NOMATCH;
maxstars--;
for(;;) {
p++;
if(!*p)
return CURL_FNMATCH_MATCH;
if(*p == '?') {
if(!*s)
return CURL_FNMATCH_NOMATCH;
s++;
}
else if(*p != '*')
break;
}
star_p = p;
star_s = s;
}
else if(*p) {
const unsigned char *np = p;
const unsigned char *ns = s;
int r = matchtoken(&np, &ns);
if(r < 0)
return CURL_FNMATCH_NOMATCH;
if(r) {
p = np;
s = ns;
continue;
}
if(!star_p)
return CURL_FNMATCH_NOMATCH;
p = star_p;
s = ++star_s;
}
else if(star_p) {
p = star_p;
s = ++star_s;
}
else
return CURL_FNMATCH_NOMATCH;
}
while(*p == '*') {
if(!maxstars)
return CURL_FNMATCH_NOMATCH;
maxstars--;
do {
p++;
if(*p == '?')
return CURL_FNMATCH_NOMATCH;
} while(*p == '*');
}
return *p ? CURL_FNMATCH_NOMATCH : CURL_FNMATCH_MATCH;
}
/*
* @unittest: 1307
*/
int Curl_fnmatch(void *ptr, const char *pattern, const char *string)
{
(void)ptr; /* the argument is specified by the curl_fnmatch_callback
prototype, but not used by Curl_fnmatch() */
if(!pattern || !string) {
return CURL_FNMATCH_FAIL;
}
return loop((const unsigned char *)pattern,
(const unsigned char *)string);
}
#else /* HAVE_FNMATCH */
#include <fnmatch.h>
/*
* @unittest: 1307
*/
int Curl_fnmatch(void *ptr, const char *pattern, const char *string)
{
(void)ptr; /* the argument is specified by the curl_fnmatch_callback
prototype, but not used by Curl_fnmatch() */
if(!pattern || !string) {
return CURL_FNMATCH_FAIL;
}
switch(fnmatch(pattern, string, 0)) {
case 0:
return CURL_FNMATCH_MATCH;
case FNM_NOMATCH:
return CURL_FNMATCH_NOMATCH;
default:
return CURL_FNMATCH_FAIL;
}
/* not reached */
}
#endif /* !HAVE_FNMATCH */
#endif /* !CURL_DISABLE_FTP */
+45
View File
@@ -0,0 +1,45 @@
#ifndef HEADER_CURL_FNMATCH_H
#define HEADER_CURL_FNMATCH_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#define CURL_FNMATCH_MATCH 0
#define CURL_FNMATCH_NOMATCH 1
#define CURL_FNMATCH_FAIL 2
/* default pattern matching function
* =================================
* Implemented with recursive backtracking, if you want to use Curl_fnmatch,
* please note that there is not implemented UTF/Unicode support.
*
* Implemented features:
* '?' notation, does not match UTF characters
* '*' can also work with UTF string
* [a-zA-Z0-9] enumeration support
*
* keywords: alnum, digit, xdigit, alpha, print, blank, lower, graph, space
* and upper (use as "[[:alnum:]]")
*/
int Curl_fnmatch(void *ptr, const char *pattern, const char *string);
#endif /* HEADER_CURL_FNMATCH_H */
+165
View File
@@ -0,0 +1,165 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_COOKIES) || !defined(CURL_DISABLE_ALTSVC) || \
!defined(CURL_DISABLE_HSTS)
#include "urldata.h"
#include "rand.h"
#include "curl_fopen.h"
/* The dirslash() function breaks a null-terminated pathname string into
directory and filename components then returns the directory component up
to, *AND INCLUDING*, a final '/'. If there is no directory in the path,
this instead returns a "" string.
This function returns a pointer to malloc'ed memory.
The input path to this function is expected to have a filename part.
*/
#ifdef _WIN32
#define PATHSEP "\\"
#define IS_SEP(x) (((x) == '/') || ((x) == '\\'))
#elif defined(MSDOS) || defined(OS2)
#define PATHSEP "\\"
#define IS_SEP(x) ((x) == '\\')
#else
#define PATHSEP "/"
#define IS_SEP(x) ((x) == '/')
#endif
static char *dirslash(const char *path)
{
size_t n;
struct dynbuf out;
DEBUGASSERT(path);
curlx_dyn_init(&out, CURL_MAX_INPUT_LENGTH);
n = strlen(path);
if(n) {
/* find the rightmost path separator, if any */
while(n && !IS_SEP(path[n - 1]))
--n;
/* skip over all the path separators, if any */
while(n && IS_SEP(path[n - 1]))
--n;
}
if(curlx_dyn_addn(&out, path, n))
return NULL;
/* if there was a directory, append a single trailing slash */
if(n && curlx_dyn_addn(&out, PATHSEP, 1))
return NULL;
return curlx_dyn_ptr(&out);
}
/*
* Curl_fopen() opens a file for writing with a temp name, to be renamed
* to the final name when completed. If there is an existing file using this
* name at the time of the open, this function will clone the mode from that
* file. if 'tempname' is non-NULL, it needs a rename after the file is
* written.
*/
CURLcode Curl_fopen(struct Curl_easy *data, const char *filename,
FILE **fh, char **tempname)
{
CURLcode result = CURLE_WRITE_ERROR;
unsigned char randbuf[41];
char *tempstore = NULL;
#ifndef _WIN32
curlx_struct_stat sb;
#endif
int fd = -1;
char *dir = NULL;
*tempname = NULL;
#ifndef _WIN32
*fh = curlx_fopen(filename, FOPEN_WRITETEXT);
if(!*fh)
goto fail;
if(curlx_fstat(fileno(*fh), &sb) == -1 || !S_ISREG(sb.st_mode)) {
return CURLE_OK;
}
curlx_fclose(*fh);
#endif /* !_WIN32 */
*fh = NULL;
result = Curl_rand_alnum(data, randbuf, sizeof(randbuf));
if(result)
goto fail;
dir = dirslash(filename);
if(dir) {
/* The temp filename should not end up too long for the target file
system */
tempstore = curl_maprintf("%s%s.tmp", dir, randbuf);
curlx_free(dir);
}
if(!tempstore) {
result = CURLE_OUT_OF_MEMORY;
goto fail;
}
result = CURLE_WRITE_ERROR;
#ifdef _WIN32
fd = curlx_open(tempstore, _O_WRONLY | _O_CREAT | _O_EXCL,
_S_IREAD | _S_IWRITE);
#else
fd = curlx_open(tempstore, O_WRONLY | O_CREAT | O_EXCL,
(mode_t)(S_IRUSR | S_IWUSR | 0600));
#endif
if(fd == -1)
goto fail;
#ifdef HAVE_FCHMOD
{
curlx_struct_stat nsb;
if((curlx_fstat(fd, &nsb) != -1) &&
(nsb.st_uid == sb.st_uid) && (nsb.st_gid == sb.st_gid)) {
/* if the user and group are the same, clone the original mode */
if(fchmod(fd, (mode_t)sb.st_mode) == -1)
goto fail;
}
}
#endif
*fh = curlx_fdopen(fd, FOPEN_WRITETEXT);
if(!*fh)
goto fail;
*tempname = tempstore;
return CURLE_OK;
fail:
if(fd != -1) {
curlx_close(fd);
unlink(tempstore);
}
curlx_free(tempstore);
return result;
}
#endif /* !disabled */
+31
View File
@@ -0,0 +1,31 @@
#ifndef HEADER_CURL_FOPEN_H
#define HEADER_CURL_FOPEN_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curlx/win32-fopen.h"
CURLcode Curl_fopen(struct Curl_easy *data, const char *filename,
FILE **fh, char **tempname);
#endif
+69
View File
@@ -0,0 +1,69 @@
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_COOKIES) || !defined(CURL_DISABLE_ALTSVC) || \
!defined(CURL_DISABLE_HSTS) || !defined(CURL_DISABLE_NETRC)
#include "curl_get_line.h"
/*
* Curl_get_line() returns only complete whole lines that end with newline.
* When 'eof' is set TRUE, the last line has been read.
*/
CURLcode Curl_get_line(struct dynbuf *buf, FILE *input, bool *eof)
{
CURLcode result;
char buffer[128];
curlx_dyn_reset(buf);
while(1) {
size_t rlen;
const char *b = fgets(buffer, sizeof(buffer), input);
if(!b && ferror(input))
return CURLE_READ_ERROR;
*eof = feof(input);
rlen = b ? strlen(b) : 0;
if(rlen) {
result = curlx_dyn_addn(buf, b, rlen);
if(result)
/* too long line or out of memory */
return result;
}
/* now check the full line */
rlen = curlx_dyn_len(buf);
b = curlx_dyn_ptr(buf);
if(rlen && (b[rlen - 1] == '\n'))
/* LF at end of the line */
return CURLE_OK; /* all good */
if(*eof)
/* append a newline */
return curlx_dyn_addn(buf, "\n", 1);
/* otherwise get next line to append */
}
/* UNREACHABLE */
}
#endif /* if not disabled */

Some files were not shown because too many files have changed in this diff Show More