This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new 699d5d0ad4 fix(bindings/c): fix self-aliasing UAF, preserve
reader/writer error kinds, guard NULL/non-ASCII FFI, and validate timestamps
(#8949)
699d5d0ad4 is described below
commit 699d5d0ad48743c05c76455d9e0f4aab14b11737
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 06:58:15 2026 +0800
fix(bindings/c): fix self-aliasing UAF, preserve reader/writer error kinds,
guard NULL/non-ASCII FFI, and validate timestamps (#8949)
---
bindings/c/Cargo.toml | 3 +
bindings/c/include/opendal.h | 6 +-
bindings/c/src/layer.rs | 64 ++++++-
bindings/c/src/operator.rs | 15 +-
bindings/c/src/presign.rs | 355 +++++++++++++++++++++++++++++++++---
bindings/c/src/reader.rs | 306 ++++++++++++++++++++++++++++++-
bindings/c/src/types.rs | 425 +++++++++++++++++++++++++++++++++++++------
bindings/c/src/writer.rs | 209 ++++++++++++++++++++-
bindings/c/tests/bdd.cpp | 100 ++++++++++
bindings/c/tests/reader.cpp | 25 +++
10 files changed, 1395 insertions(+), 113 deletions(-)
diff --git a/bindings/c/Cargo.toml b/bindings/c/Cargo.toml
index 80c5fd9bc4..15f0ef4bfa 100644
--- a/bindings/c/Cargo.toml
+++ b/bindings/c/Cargo.toml
@@ -46,5 +46,8 @@ tokio = { version = "1.27", features = [
"sync",
] }
+[dev-dependencies]
+http = "1.4"
+
[features]
default = []
diff --git a/bindings/c/include/opendal.h b/bindings/c/include/opendal.h
index 9c1cf22867..9b2856aa38 100644
--- a/bindings/c/include/opendal.h
+++ b/bindings/c/include/opendal.h
@@ -1188,7 +1188,7 @@ struct opendal_operator_layers
*opendal_operator_layers_new(void);
/**
* \brief Add a retry layer.
*/
-void opendal_operator_layers_add_retry(struct opendal_operator_layers *self,
+void opendal_operator_layers_add_retry(struct opendal_operator_layers *layers,
bool jitter,
float factor,
uint64_t min_delay_ns,
@@ -1198,7 +1198,7 @@ void opendal_operator_layers_add_retry(struct
opendal_operator_layers *self,
/**
* \brief Add a timeout layer.
*/
-void opendal_operator_layers_add_timeout(struct opendal_operator_layers *self,
+void opendal_operator_layers_add_timeout(struct opendal_operator_layers
*layers,
uint64_t timeout_ns,
uint64_t io_timeout_ns);
@@ -3159,7 +3159,7 @@ struct opendal_operator_options
*opendal_operator_options_new(void);
* opendal_operator_options_free(options);
* ```
*/
-void opendal_operator_options_set(struct opendal_operator_options *self,
+void opendal_operator_options_set(struct opendal_operator_options *opts,
const char *key,
const char *value);
diff --git a/bindings/c/src/layer.rs b/bindings/c/src/layer.rs
index ab05ce3a7c..9c2ea635e9 100644
--- a/bindings/c/src/layer.rs
+++ b/bindings/c/src/layer.rs
@@ -125,14 +125,17 @@ impl opendal_operator_layers {
/// \brief Add a retry layer.
#[no_mangle]
pub unsafe extern "C" fn opendal_operator_layers_add_retry(
- &mut self,
+ layers: *mut opendal_operator_layers,
jitter: bool,
factor: f32,
min_delay_ns: u64,
max_delay_ns: u64,
max_times: u64,
) {
- self.add_retry(jitter, factor, min_delay_ns, max_delay_ns, max_times);
+ if layers.is_null() || (*layers).inner.is_null() {
+ return;
+ }
+ (*layers).add_retry(jitter, factor, min_delay_ns, max_delay_ns,
max_times);
}
/// \brief Add a timeout layer.
@@ -146,11 +149,14 @@ impl opendal_operator_layers {
/// \brief Add a timeout layer.
#[no_mangle]
pub unsafe extern "C" fn opendal_operator_layers_add_timeout(
- &mut self,
+ layers: *mut opendal_operator_layers,
timeout_ns: u64,
io_timeout_ns: u64,
) {
- self.add_timeout(timeout_ns, io_timeout_ns);
+ if layers.is_null() || (*layers).inner.is_null() {
+ return;
+ }
+ (*layers).add_timeout(timeout_ns, io_timeout_ns);
}
/// \brief Free the allocated memory used by opendal_operator_layers.
@@ -164,3 +170,53 @@ impl opendal_operator_layers {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_operator_layers_add_null_guards() {
+ unsafe {
+ // NULL layers pointers must be no-ops without UB.
+ opendal_operator_layers::opendal_operator_layers_add_retry(
+ std::ptr::null_mut(),
+ true,
+ 2.0,
+ 1_000,
+ 10_000,
+ 3,
+ );
+ opendal_operator_layers::opendal_operator_layers_add_timeout(
+ std::ptr::null_mut(),
+ 1_000,
+ 2_000,
+ );
+
+ let mut empty_inner = opendal_operator_layers {
+ inner: std::ptr::null_mut(),
+ };
+ opendal_operator_layers::opendal_operator_layers_add_retry(
+ &mut empty_inner,
+ false,
+ 2.0,
+ 1_000,
+ 10_000,
+ 3,
+ );
+ opendal_operator_layers::opendal_operator_layers_add_timeout(
+ &mut empty_inner,
+ 1_000,
+ 2_000,
+ );
+
+ let layers =
opendal_operator_layers::opendal_operator_layers_new();
+ opendal_operator_layers::opendal_operator_layers_add_retry(
+ layers, true, 2.0, 1_000, 10_000, 3,
+ );
+
opendal_operator_layers::opendal_operator_layers_add_timeout(layers, 1_000,
2_000);
+ assert_eq!((*layers).deref().len(), 2);
+ opendal_operator_layers::opendal_operator_layers_free(layers);
+ }
+ }
+}
diff --git a/bindings/c/src/operator.rs b/bindings/c/src/operator.rs
index 3a2039e195..b4359fc83b 100644
--- a/bindings/c/src/operator.rs
+++ b/bindings/c/src/operator.rs
@@ -563,7 +563,10 @@ pub unsafe extern "C" fn opendal_operator_read_with_cancel(
let opts = if opts.is_null() {
core::options::ReadOptions::default()
} else {
- (&*opts).into()
+ match core::options::ReadOptions::try_from(&*opts) {
+ Ok(opts) => opts,
+ Err(e) => return opendal_error::new(e),
+ }
};
let cancel_token = opendal_cancel_token::as_inner(cancel);
match block_on_cancellable(
@@ -675,7 +678,10 @@ pub unsafe extern "C" fn
opendal_operator_reader_with_cancel(
let opts = if opts.is_null() {
core::options::ReaderOptions::default()
} else {
- (&*opts).into()
+ match core::options::ReaderOptions::try_from(&*opts) {
+ Ok(opts) => opts,
+ Err(e) => return opendal_error::new(e),
+ }
};
let cancel_token = opendal_cancel_token::as_inner(cancel);
match block_on_cancellable(op.handle(), cancel_token, async {
@@ -1116,7 +1122,10 @@ pub unsafe extern "C" fn
opendal_operator_stat_with_cancel(
let opts = if opts.is_null() {
core::options::StatOptions::default()
} else {
- (&*opts).into()
+ match core::options::StatOptions::try_from(&*opts) {
+ Ok(opts) => opts,
+ Err(e) => return opendal_error::new(e),
+ }
};
let cancel_token = opendal_cancel_token::as_inner(cancel);
match block_on_cancellable(
diff --git a/bindings/c/src/presign.rs b/bindings/c/src/presign.rs
index 535544ac5a..6c13ffa472 100644
--- a/bindings/c/src/presign.rs
+++ b/bindings/c/src/presign.rs
@@ -52,20 +52,40 @@ struct opendal_presigned_request_inner {
}
impl opendal_presigned_request_inner {
- fn new(req: ocorePresignedRequest) -> Self {
- let method = CString::new(req.method().as_str()).unwrap();
- let uri = CString::new(req.uri().to_string()).unwrap();
-
- let header_keys: Vec<CString> = req
- .header()
- .iter()
- .map(|(k, _)| CString::new(k.as_str()).unwrap())
- .collect();
- let header_values: Vec<CString> = req
- .header()
- .iter()
- .map(|(_, v)| CString::new(v.to_str().unwrap()).unwrap())
- .collect();
+ fn new(req: ocorePresignedRequest) -> core::Result<Self> {
+ let method = CString::new(req.method().as_str()).map_err(|e| {
+ core::Error::new(
+ core::ErrorKind::Unexpected,
+ "presigned request method contains interior nul byte",
+ )
+ .set_source(e)
+ })?;
+ let uri = CString::new(req.uri().to_string()).map_err(|e| {
+ core::Error::new(
+ core::ErrorKind::Unexpected,
+ "presigned request uri contains interior nul byte",
+ )
+ .set_source(e)
+ })?;
+
+ let mut header_keys = Vec::with_capacity(req.header().len());
+ let mut header_values = Vec::with_capacity(req.header().len());
+ for (k, v) in req.header().iter() {
+ header_keys.push(CString::new(k.as_str()).map_err(|e| {
+ core::Error::new(
+ core::ErrorKind::Unexpected,
+ "presigned request header name contains interior nul byte",
+ )
+ .set_source(e)
+ })?);
+ header_values.push(CString::new(v.as_bytes()).map_err(|e| {
+ core::Error::new(
+ core::ErrorKind::Unexpected,
+ "presigned request header value contains interior nul
byte",
+ )
+ .set_source(e)
+ })?);
+ }
let headers: Vec<opendal_http_header_pair> = header_keys
.iter()
@@ -76,13 +96,13 @@ impl opendal_presigned_request_inner {
})
.collect();
- Self {
+ Ok(Self {
method,
uri,
headers,
header_keys,
header_values,
- }
+ })
}
}
@@ -92,14 +112,19 @@ unsafe fn make_presign_result(
) -> *mut opendal_error {
assert!(!req_out.is_null());
match result {
- Ok(req) => {
- let inner = Box::new(opendal_presigned_request_inner::new(req));
- let presigned_req = Box::new(opendal_presigned_request {
- inner: Box::into_raw(inner),
- });
- std::ptr::write(req_out, Box::into_raw(presigned_req));
- std::ptr::null_mut()
- }
+ Ok(req) => match opendal_presigned_request_inner::new(req) {
+ Ok(inner) => {
+ let presigned_req = Box::new(opendal_presigned_request {
+ inner: Box::into_raw(Box::new(inner)),
+ });
+ std::ptr::write(req_out, Box::into_raw(presigned_req));
+ std::ptr::null_mut()
+ }
+ Err(e) => {
+ std::ptr::write(req_out, std::ptr::null_mut());
+ opendal_error::new(e)
+ }
+ },
Err(e) => {
std::ptr::write(req_out, std::ptr::null_mut());
opendal_error::from_cancellable(e)
@@ -170,13 +195,17 @@ pub unsafe extern "C" fn
opendal_operator_presign_read_with_cancel(
) -> *mut opendal_error {
assert!(!path.is_null());
assert!(!req.is_null());
+ std::ptr::write(req, std::ptr::null_mut());
let path = CStr::from_ptr(path).to_str().expect("malformed path");
let duration = Duration::from_secs(expire_secs);
let opts = if opts.is_null() {
core::options::ReadOptions::default()
} else {
- (&*opts).into()
+ match core::options::ReadOptions::try_from(&*opts) {
+ Ok(opts) => opts,
+ Err(e) => return opendal_error::new(e),
+ }
};
let cancel_token = opendal_cancel_token::as_inner(cancel);
@@ -392,13 +421,17 @@ pub unsafe extern "C" fn
opendal_operator_presign_stat_with_cancel(
) -> *mut opendal_error {
assert!(!path.is_null());
assert!(!req.is_null());
+ std::ptr::write(req, std::ptr::null_mut());
let path = CStr::from_ptr(path).to_str().expect("malformed path");
let duration = Duration::from_secs(expire_secs);
let opts = if opts.is_null() {
core::options::StatOptions::default()
} else {
- (&*opts).into()
+ match core::options::StatOptions::try_from(&*opts) {
+ Ok(opts) => opts,
+ Err(e) => return opendal_error::new(e),
+ }
};
let cancel_token = opendal_cancel_token::as_inner(cancel);
@@ -415,6 +448,9 @@ pub unsafe extern "C" fn
opendal_operator_presign_stat_with_cancel(
pub unsafe extern "C" fn opendal_presigned_request_method(
req: *const opendal_presigned_request,
) -> *const c_char {
+ if req.is_null() || (*req).inner.is_null() {
+ return std::ptr::null();
+ }
(*(*req).inner).method.as_ptr()
}
@@ -423,6 +459,9 @@ pub unsafe extern "C" fn opendal_presigned_request_method(
pub unsafe extern "C" fn opendal_presigned_request_uri(
req: *const opendal_presigned_request,
) -> *const c_char {
+ if req.is_null() || (*req).inner.is_null() {
+ return std::ptr::null();
+ }
(*(*req).inner).uri.as_ptr()
}
@@ -431,6 +470,9 @@ pub unsafe extern "C" fn opendal_presigned_request_uri(
pub unsafe extern "C" fn opendal_presigned_request_headers(
req: *const opendal_presigned_request,
) -> *const opendal_http_header_pair {
+ if req.is_null() || (*req).inner.is_null() {
+ return std::ptr::null();
+ }
(*(*req).inner).headers.as_ptr()
}
@@ -439,6 +481,9 @@ pub unsafe extern "C" fn opendal_presigned_request_headers(
pub unsafe extern "C" fn opendal_presigned_request_headers_len(
req: *const opendal_presigned_request,
) -> usize {
+ if req.is_null() || (*req).inner.is_null() {
+ return 0;
+ }
(*(*req).inner).headers.len()
}
@@ -446,7 +491,263 @@ pub unsafe extern "C" fn
opendal_presigned_request_headers_len(
#[no_mangle]
pub unsafe extern "C" fn opendal_presigned_request_free(req: *mut
opendal_presigned_request) {
if !req.is_null() {
- drop(Box::from_raw((*req).inner));
+ if !(*req).inner.is_null() {
+ drop(Box::from_raw((*req).inner));
+ }
drop(Box::from_raw(req));
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::error::opendal_code;
+ use ::opendal::raw::{self, oio};
+ use std::sync::Arc;
+
+ #[derive(Debug)]
+ struct NonAsciiPresignService {
+ inner: raw::Servicer,
+ }
+
+ #[derive(Debug)]
+ struct NonAsciiPresignLayer;
+
+ impl raw::Layer for NonAsciiPresignLayer {
+ fn apply_service(&self, inner: raw::Servicer) -> raw::Servicer {
+ Arc::new(NonAsciiPresignService { inner })
+ }
+ }
+
+ impl raw::Service for NonAsciiPresignService {
+ type Reader = oio::Reader;
+ type Writer = oio::Writer;
+ type Lister = oio::Lister;
+ type Deleter = oio::Deleter;
+ type Copier = oio::Copier;
+ type Composer = oio::Composer;
+
+ fn info(&self) -> raw::ServiceInfo {
+ self.inner.info()
+ }
+
+ fn capability(&self) -> core::Capability {
+ let mut cap = self.inner.capability();
+ cap.presign = true;
+ cap.presign_write = true;
+ cap.presign_read = true;
+ cap.presign_stat = true;
+ cap
+ }
+
+ async fn create_dir(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpCreateDir,
+ ) -> core::Result<raw::RpCreateDir> {
+ self.inner.create_dir(ctx, path, args).await
+ }
+
+ async fn stat(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpStat,
+ ) -> core::Result<raw::RpStat> {
+ self.inner.stat(ctx, path, args).await
+ }
+
+ fn read(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpRead,
+ ) -> core::Result<Self::Reader> {
+ self.inner.read(ctx, path, args)
+ }
+
+ fn write(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpWrite,
+ ) -> core::Result<Self::Writer> {
+ self.inner.write(ctx, path, args)
+ }
+
+ fn delete(&self, ctx: &core::OperationContext) ->
core::Result<Self::Deleter> {
+ self.inner.delete(ctx)
+ }
+
+ fn list(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpList,
+ ) -> core::Result<Self::Lister> {
+ self.inner.list(ctx, path, args)
+ }
+
+ fn copy(
+ &self,
+ ctx: &core::OperationContext,
+ from: &str,
+ to: &str,
+ args: raw::OpCopy,
+ ) -> core::Result<Self::Copier> {
+ self.inner.copy(ctx, from, to, args)
+ }
+
+ async fn rename(
+ &self,
+ ctx: &core::OperationContext,
+ from: &str,
+ to: &str,
+ args: raw::OpRename,
+ ) -> core::Result<raw::RpRename> {
+ self.inner.rename(ctx, from, to, args).await
+ }
+
+ fn compose(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpCompose,
+ ) -> core::Result<Self::Composer> {
+ self.inner.compose(ctx, path, args)
+ }
+
+ async fn presign(
+ &self,
+ _ctx: &core::OperationContext,
+ _path: &str,
+ _args: raw::OpPresign,
+ ) -> core::Result<raw::RpPresign> {
+ let mut headers = http::HeaderMap::new();
+ headers.insert(
+ http::header::CONTENT_DISPOSITION,
+ http::HeaderValue::from_bytes("attachment;
filename=\"测试.txt\"".as_bytes())
+ .unwrap(),
+ );
+ let req = ocorePresignedRequest::new(
+ http::Method::PUT,
+ "https://example.com/object".parse().unwrap(),
+ headers,
+ );
+ Ok(raw::RpPresign::new(req))
+ }
+ }
+
+ #[test]
+ fn test_presign_non_ascii_header_value_does_not_panic() {
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ let op = core::Operator::new(core::services::Memory::default())
+ .unwrap()
+ .layer(NonAsciiPresignLayer);
+ let c_op = opendal_operator::from_operator(runtime.handle().clone(),
op);
+ let path = CString::new("test.txt").unwrap();
+
+ unsafe {
+ let mut req: *mut opendal_presigned_request = std::ptr::null_mut();
+ let err = opendal_operator_presign_write(&*c_op, path.as_ptr(),
60, &mut req);
+ assert!(err.is_null());
+ assert!(!req.is_null());
+
+ assert_eq!(
+ CStr::from_ptr(opendal_presigned_request_method(req))
+ .to_str()
+ .unwrap(),
+ "PUT"
+ );
+ assert_eq!(
+ CStr::from_ptr(opendal_presigned_request_uri(req))
+ .to_str()
+ .unwrap(),
+ "https://example.com/object"
+ );
+ assert_eq!(opendal_presigned_request_headers_len(req), 1);
+
+ let headers = opendal_presigned_request_headers(req);
+ assert!(!headers.is_null());
+ let pair = &*headers;
+ assert_eq!(
+ CStr::from_ptr(pair.key).to_str().unwrap(),
+ "content-disposition"
+ );
+ assert_eq!(
+ CStr::from_ptr(pair.value).to_bytes(),
+ "attachment; filename=\"测试.txt\"".as_bytes()
+ );
+
+ opendal_presigned_request_free(req);
+ opendal_operator::opendal_operator_free(c_op);
+ }
+ }
+
+ #[test]
+ fn test_presigned_request_null_guards() {
+ unsafe {
+
assert!(opendal_presigned_request_method(std::ptr::null()).is_null());
+ assert!(opendal_presigned_request_uri(std::ptr::null()).is_null());
+
assert!(opendal_presigned_request_headers(std::ptr::null()).is_null());
+
assert_eq!(opendal_presigned_request_headers_len(std::ptr::null()), 0);
+ opendal_presigned_request_free(std::ptr::null_mut());
+
+ let req = Box::into_raw(Box::new(opendal_presigned_request {
+ inner: std::ptr::null_mut(),
+ }));
+ assert!(opendal_presigned_request_method(req).is_null());
+ assert!(opendal_presigned_request_uri(req).is_null());
+ assert!(opendal_presigned_request_headers(req).is_null());
+ assert_eq!(opendal_presigned_request_headers_len(req), 0);
+ opendal_presigned_request_free(req);
+ }
+ }
+
+ #[test]
+ fn test_presign_out_of_range_timestamp_returns_config_invalid() {
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ let op = core::Operator::new(core::services::Memory::default())
+ .unwrap()
+ .layer(NonAsciiPresignLayer);
+ let c_op = opendal_operator::from_operator(runtime.handle().clone(),
op);
+ let path = CString::new("test.txt").unwrap();
+
+ unsafe {
+ let bad_read = opendal_read_options {
+ has_if_modified_since: true,
+ if_modified_since: i64::MAX,
+ ..Default::default()
+ };
+ let mut req: *mut opendal_presigned_request =
std::ptr::dangling_mut();
+ let err =
+ opendal_operator_presign_read_with(&*c_op, path.as_ptr(), 60,
&bad_read, &mut req);
+ assert!(!err.is_null());
+ assert_eq!((*err).code(), opendal_code::OPENDAL_CONFIG_INVALID);
+ assert!(req.is_null());
+ opendal_error::opendal_error_free(err);
+
+ let bad_stat = opendal_stat_options {
+ has_if_unmodified_since: true,
+ if_unmodified_since: i64::MIN,
+ ..Default::default()
+ };
+ let mut req: *mut opendal_presigned_request =
std::ptr::dangling_mut();
+ let err =
+ opendal_operator_presign_stat_with(&*c_op, path.as_ptr(), 60,
&bad_stat, &mut req);
+ assert!(!err.is_null());
+ assert_eq!((*err).code(), opendal_code::OPENDAL_CONFIG_INVALID);
+ assert!(req.is_null());
+ opendal_error::opendal_error_free(err);
+
+ opendal_operator::opendal_operator_free(c_op);
+ }
+ }
+}
diff --git a/bindings/c/src/reader.rs b/bindings/c/src/reader.rs
index 78129e23eb..78bedbc68f 100644
--- a/bindings/c/src/reader.rs
+++ b/bindings/c/src/reader.rs
@@ -55,6 +55,24 @@ pub struct opendal_reader {
inner: *mut c_void,
}
+fn reader_io_error(e: std::io::Error, context: &str) -> *mut opendal_error {
+ if e.get_ref().is_some_and(|s| s.is::<core::Error>()) {
+ let err = e
+ .into_inner()
+ .expect("io error inner was checked to be present")
+ .downcast::<core::Error>()
+ .expect("io error inner was checked to be opendal::Error");
+ return opendal_error::new(*err);
+ }
+
+ let kind = match e.kind() {
+ std::io::ErrorKind::NotFound => core::ErrorKind::NotFound,
+ std::io::ErrorKind::PermissionDenied =>
core::ErrorKind::PermissionDenied,
+ _ => core::ErrorKind::Unexpected,
+ };
+ opendal_error::new(core::Error::new(kind, context).set_source(e))
+}
+
impl opendal_reader {
fn deref_mut(&mut self) -> &mut ReaderInner {
// Safety: the inner should never be null once constructed
@@ -113,10 +131,7 @@ impl opendal_reader {
std::ptr::null_mut()
}
Err(CancellableError::Cancelled) => opendal_error::cancelled(),
- Err(CancellableError::Inner(e)) => opendal_error::new(
- core::Error::new(core::ErrorKind::Unexpected, "read failed
from reader")
- .set_source(e),
- ),
+ Err(CancellableError::Inner(e)) => reader_io_error(e, "read failed
from reader"),
}
}
@@ -177,10 +192,7 @@ impl opendal_reader {
std::ptr::null_mut()
}
Err(CancellableError::Cancelled) => opendal_error::cancelled(),
- Err(CancellableError::Inner(e)) => opendal_error::new(
- core::Error::new(core::ErrorKind::Unexpected, "seek failed
from reader")
- .set_source(e),
- ),
+ Err(CancellableError::Inner(e)) => reader_io_error(e, "seek failed
from reader"),
}
}
@@ -232,4 +244,282 @@ mod tests {
opendal_reader::opendal_reader_free(reader);
}
}
+
+ #[test]
+ fn test_reader_preserves_not_found_on_read_and_seek() {
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ let op =
core::Operator::new(core::services::Memory::default()).unwrap();
+ let reader = runtime.block_on(async {
+ op.reader("does_not_exist")
+ .await
+ .unwrap()
+ .into_futures_async_read(core::BytesRange::default())
+ .await
+ .unwrap()
+ });
+ let reader = Box::into_raw(Box::new(opendal_reader::new(
+ runtime.handle().clone(),
+ reader,
+ )));
+
+ let mut buf = [0u8; 16];
+ let mut size = 99;
+ let err = unsafe {
+ opendal_reader::opendal_reader_read(
+ &mut *reader,
+ buf.as_mut_ptr(),
+ buf.len(),
+ &mut size,
+ )
+ };
+ assert!(!err.is_null());
+ assert_eq!(unsafe { (*err).code() }, opendal_code::OPENDAL_NOT_FOUND);
+ assert_eq!(size, 0);
+ unsafe { opendal_error::opendal_error_free(err) };
+
+ let mut pos = 99;
+ let err = unsafe {
+ opendal_reader::opendal_reader_seek(&mut *reader, 0,
OPENDAL_SEEK_END, &mut pos)
+ };
+ assert!(!err.is_null());
+ assert_eq!(unsafe { (*err).code() }, opendal_code::OPENDAL_NOT_FOUND);
+ assert_eq!(pos, 0);
+ unsafe {
+ opendal_error::opendal_error_free(err);
+ opendal_reader::opendal_reader_free(reader);
+ }
+ }
+
+ #[test]
+ fn test_reader_preserves_backend_error_kind() {
+ use ::opendal::raw::{self, oio};
+ use std::sync::Arc;
+
+ #[derive(Debug)]
+ struct FailingReadService {
+ inner: raw::Servicer,
+ }
+
+ #[derive(Debug)]
+ struct FailingReadLayer;
+
+ impl raw::Layer for FailingReadLayer {
+ fn apply_service(&self, inner: raw::Servicer) -> raw::Servicer {
+ Arc::new(FailingReadService { inner })
+ }
+ }
+
+ struct FailingReader;
+
+ impl oio::Read for FailingReader {
+ async fn open(
+ &self,
+ _range: core::BytesRange,
+ ) -> core::Result<(raw::RpRead, Box<dyn oio::ReadStreamDyn>)> {
+ Err(core::Error::new(
+ core::ErrorKind::ConditionNotMatch,
+ "etag mismatch on read",
+ ))
+ }
+
+ async fn read(
+ &self,
+ _range: core::BytesRange,
+ ) -> core::Result<(raw::RpRead, core::Buffer)> {
+ Err(core::Error::new(
+ core::ErrorKind::ConditionNotMatch,
+ "etag mismatch on read",
+ ))
+ }
+ }
+
+ impl raw::Service for FailingReadService {
+ type Reader = FailingReader;
+ type Writer = oio::Writer;
+ type Lister = oio::Lister;
+ type Deleter = oio::Deleter;
+ type Copier = oio::Copier;
+ type Composer = oio::Composer;
+
+ fn info(&self) -> raw::ServiceInfo {
+ self.inner.info()
+ }
+
+ fn capability(&self) -> core::Capability {
+ self.inner.capability()
+ }
+
+ async fn create_dir(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpCreateDir,
+ ) -> core::Result<raw::RpCreateDir> {
+ self.inner.create_dir(ctx, path, args).await
+ }
+
+ async fn stat(
+ &self,
+ _ctx: &core::OperationContext,
+ _path: &str,
+ _args: raw::OpStat,
+ ) -> core::Result<raw::RpStat> {
+ Err(core::Error::new(
+ core::ErrorKind::PermissionDenied,
+ "permission denied on stat",
+ ))
+ }
+
+ fn read(
+ &self,
+ _ctx: &core::OperationContext,
+ _path: &str,
+ _args: raw::OpRead,
+ ) -> core::Result<Self::Reader> {
+ Ok(FailingReader)
+ }
+
+ fn write(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpWrite,
+ ) -> core::Result<Self::Writer> {
+ self.inner.write(ctx, path, args)
+ }
+
+ fn delete(&self, ctx: &core::OperationContext) ->
core::Result<Self::Deleter> {
+ self.inner.delete(ctx)
+ }
+
+ fn list(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpList,
+ ) -> core::Result<Self::Lister> {
+ self.inner.list(ctx, path, args)
+ }
+
+ fn copy(
+ &self,
+ ctx: &core::OperationContext,
+ from: &str,
+ to: &str,
+ args: raw::OpCopy,
+ ) -> core::Result<Self::Copier> {
+ self.inner.copy(ctx, from, to, args)
+ }
+
+ async fn rename(
+ &self,
+ ctx: &core::OperationContext,
+ from: &str,
+ to: &str,
+ args: raw::OpRename,
+ ) -> core::Result<raw::RpRename> {
+ self.inner.rename(ctx, from, to, args).await
+ }
+
+ fn compose(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpCompose,
+ ) -> core::Result<Self::Composer> {
+ self.inner.compose(ctx, path, args)
+ }
+
+ async fn presign(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpPresign,
+ ) -> core::Result<raw::RpPresign> {
+ self.inner.presign(ctx, path, args).await
+ }
+ }
+
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ let op = core::Operator::new(core::services::Memory::default())
+ .unwrap()
+ .layer(FailingReadLayer);
+ let reader = runtime.block_on(async {
+ op.reader("test")
+ .await
+ .unwrap()
+ .into_futures_async_read(core::BytesRange::default())
+ .await
+ .unwrap()
+ });
+ let reader = Box::into_raw(Box::new(opendal_reader::new(
+ runtime.handle().clone(),
+ reader,
+ )));
+
+ let mut buf = [0u8; 8];
+ let mut size = 99;
+ let err = unsafe {
+ opendal_reader::opendal_reader_read(
+ &mut *reader,
+ buf.as_mut_ptr(),
+ buf.len(),
+ &mut size,
+ )
+ };
+ assert!(!err.is_null());
+ assert_eq!(
+ unsafe { (*err).code() },
+ opendal_code::OPENDAL_CONDITION_NOT_MATCH
+ );
+ assert_eq!(size, 0);
+ unsafe { opendal_error::opendal_error_free(err) };
+
+ let mut pos = 99;
+ let err = unsafe {
+ opendal_reader::opendal_reader_seek(&mut *reader, 0,
OPENDAL_SEEK_END, &mut pos)
+ };
+ assert!(!err.is_null());
+ assert_eq!(
+ unsafe { (*err).code() },
+ opendal_code::OPENDAL_PERMISSION_DENIED
+ );
+ assert_eq!(pos, 0);
+ unsafe {
+ opendal_error::opendal_error_free(err);
+ opendal_reader::opendal_reader_free(reader);
+ }
+ }
+
+ #[test]
+ fn test_reader_io_error_fallback() {
+ unsafe {
+ let err = reader_io_error(
+ std::io::Error::new(std::io::ErrorKind::InvalidInput, "bad
seek"),
+ "seek failed",
+ );
+ assert_eq!((*err).code(), opendal_code::OPENDAL_UNEXPECTED);
+ opendal_error::opendal_error_free(err);
+
+ let err = reader_io_error(
+ std::io::Error::new(std::io::ErrorKind::NotFound, "missing"),
+ "read failed",
+ );
+ assert_eq!((*err).code(), opendal_code::OPENDAL_NOT_FOUND);
+ opendal_error::opendal_error_free(err);
+
+ let err = reader_io_error(
+ std::io::Error::new(std::io::ErrorKind::PermissionDenied,
"denied"),
+ "read failed",
+ );
+ assert_eq!((*err).code(), opendal_code::OPENDAL_PERMISSION_DENIED);
+ opendal_error::opendal_error_free(err);
+ }
+ }
}
diff --git a/bindings/c/src/types.rs b/bindings/c/src/types.rs
index f3ce2bd92a..62851524ad 100644
--- a/bindings/c/src/types.rs
+++ b/bindings/c/src/types.rs
@@ -206,18 +206,20 @@ impl opendal_list_options {
return;
}
- let o = &mut *opts;
- // Free any previous value.
- if !o.start_after.is_null() {
- drop(CString::from_raw(o.start_after));
- o.start_after = std::ptr::null_mut();
- }
- if !start_after.is_null() {
+ // Allocate before freeing the old value so self-aliasing or substring
+ // pointers into `opts->start_after` remain valid while reading.
+ let new_ptr = if start_after.is_null() {
+ std::ptr::null_mut()
+ } else {
let s = CStr::from_ptr(start_after)
.to_str()
- .expect("malformed start_after")
- .to_owned();
- o.start_after = CString::new(s).unwrap().into_raw();
+ .expect("malformed start_after");
+ CString::new(s).unwrap().into_raw()
+ };
+ let o = &mut *opts;
+ let old_ptr = std::mem::replace(&mut o.start_after, new_ptr);
+ if !old_ptr.is_null() {
+ drop(CString::from_raw(old_ptr));
}
}
@@ -310,17 +312,18 @@ impl opendal_delete_options {
if opts.is_null() {
return;
}
+ // Allocate before freeing the old value so self-aliasing or substring
+ // pointers into `opts->version` remain valid while reading.
+ let new_ptr = if version.is_null() {
+ std::ptr::null_mut()
+ } else {
+ let s = CStr::from_ptr(version).to_str().expect("malformed
version");
+ CString::new(s).unwrap().into_raw()
+ };
let o = &mut *opts;
- if !o.version.is_null() {
- drop(CString::from_raw(o.version));
- o.version = std::ptr::null_mut();
- }
- if !version.is_null() {
- let s = CStr::from_ptr(version)
- .to_str()
- .expect("malformed version")
- .to_owned();
- o.version = CString::new(s).unwrap().into_raw();
+ let old_ptr = std::mem::replace(&mut o.version, new_ptr);
+ if !old_ptr.is_null() {
+ drop(CString::from_raw(old_ptr));
}
}
@@ -775,27 +778,46 @@ impl Default for opendal_stat_options {
}
}
-impl From<&opendal_stat_options> for options::StatOptions {
- fn from(value: &opendal_stat_options) -> Self {
- Self {
+fn optional_timestamp(has: bool, millis: i64, field: &str) ->
opendal::Result<Option<Timestamp>> {
+ if !has {
+ return Ok(None);
+ }
+ Timestamp::from_millisecond(millis)
+ .map(Some)
+ .map_err(|err| {
+ Error::new(
+ ErrorKind::ConfigInvalid,
+ format!("invalid {field} timestamp '{millis}' ms"),
+ )
+ .set_source(err)
+ })
+}
+
+impl TryFrom<&opendal_stat_options> for options::StatOptions {
+ type Error = Error;
+
+ fn try_from(value: &opendal_stat_options) -> Result<Self, Self::Error> {
+ Ok(Self {
version: unsafe { optional_cstr(value.version) },
if_match: unsafe { optional_cstr(value.if_match) },
if_none_match: unsafe { optional_cstr(value.if_none_match) },
- if_modified_since: value
- .has_if_modified_since
- .then(||
Timestamp::from_millisecond(value.if_modified_since).ok())
- .flatten(),
- if_unmodified_since: value
- .has_if_unmodified_since
- .then(||
Timestamp::from_millisecond(value.if_unmodified_since).ok())
- .flatten(),
+ if_modified_since: optional_timestamp(
+ value.has_if_modified_since,
+ value.if_modified_since,
+ "if_modified_since",
+ )?,
+ if_unmodified_since: optional_timestamp(
+ value.has_if_unmodified_since,
+ value.if_unmodified_since,
+ "if_unmodified_since",
+ )?,
override_content_type: unsafe {
optional_cstr(value.override_content_type) },
override_cache_control: unsafe {
optional_cstr(value.override_cache_control) },
override_content_disposition: unsafe {
optional_cstr(value.override_content_disposition)
},
..Default::default()
- }
+ })
}
}
@@ -1059,8 +1081,10 @@ impl opendal_read_options {
}
}
-impl From<&opendal_read_options> for options::ReadOptions {
- fn from(value: &opendal_read_options) -> Self {
+impl TryFrom<&opendal_read_options> for options::ReadOptions {
+ type Error = Error;
+
+ fn try_from(value: &opendal_read_options) -> Result<Self, Self::Error> {
let range = if value.offset > 0 || value.has_length {
let size = if value.has_length {
Some(value.length)
@@ -1072,19 +1096,21 @@ impl From<&opendal_read_options> for
options::ReadOptions {
BytesRange::default()
};
- Self {
+ Ok(Self {
range,
version: unsafe { optional_cstr(value.version) },
if_match: unsafe { optional_cstr(value.if_match) },
if_none_match: unsafe { optional_cstr(value.if_none_match) },
- if_modified_since: value
- .has_if_modified_since
- .then(||
Timestamp::from_millisecond(value.if_modified_since).ok())
- .flatten(),
- if_unmodified_since: value
- .has_if_unmodified_since
- .then(||
Timestamp::from_millisecond(value.if_unmodified_since).ok())
- .flatten(),
+ if_modified_since: optional_timestamp(
+ value.has_if_modified_since,
+ value.if_modified_since,
+ "if_modified_since",
+ )?,
+ if_unmodified_since: optional_timestamp(
+ value.has_if_unmodified_since,
+ value.if_unmodified_since,
+ "if_unmodified_since",
+ )?,
content_length_hint: value
.has_content_length_hint
.then_some(value.content_length_hint),
@@ -1097,7 +1123,7 @@ impl From<&opendal_read_options> for options::ReadOptions
{
optional_cstr(value.override_content_disposition)
},
..Default::default()
- }
+ })
}
}
@@ -1297,20 +1323,24 @@ impl opendal_reader_options {
}
}
-impl From<&opendal_reader_options> for options::ReaderOptions {
- fn from(value: &opendal_reader_options) -> Self {
- Self {
+impl TryFrom<&opendal_reader_options> for options::ReaderOptions {
+ type Error = Error;
+
+ fn try_from(value: &opendal_reader_options) -> Result<Self, Self::Error> {
+ Ok(Self {
version: unsafe { optional_cstr(value.version) },
if_match: unsafe { optional_cstr(value.if_match) },
if_none_match: unsafe { optional_cstr(value.if_none_match) },
- if_modified_since: value
- .has_if_modified_since
- .then(||
Timestamp::from_millisecond(value.if_modified_since).ok())
- .flatten(),
- if_unmodified_since: value
- .has_if_unmodified_since
- .then(||
Timestamp::from_millisecond(value.if_unmodified_since).ok())
- .flatten(),
+ if_modified_since: optional_timestamp(
+ value.has_if_modified_since,
+ value.if_modified_since,
+ "if_modified_since",
+ )?,
+ if_unmodified_since: optional_timestamp(
+ value.has_if_unmodified_since,
+ value.if_unmodified_since,
+ "if_unmodified_since",
+ )?,
content_length_hint: value
.has_content_length_hint
.then_some(value.content_length_hint),
@@ -1319,7 +1349,7 @@ impl From<&opendal_reader_options> for
options::ReaderOptions {
gap: value.has_gap.then_some(value.gap),
prefetch: value.prefetch,
..Default::default()
- }
+ })
}
}
@@ -1535,10 +1565,13 @@ impl opendal_operator_options {
/// ```
#[no_mangle]
pub unsafe extern "C" fn opendal_operator_options_set(
- &mut self,
+ opts: *mut opendal_operator_options,
key: *const c_char,
value: *const c_char,
) {
+ if opts.is_null() || (*opts).inner.is_null() || key.is_null() ||
value.is_null() {
+ return;
+ }
let k = unsafe { std::ffi::CStr::from_ptr(key) }
.to_str()
.unwrap()
@@ -1547,7 +1580,7 @@ impl opendal_operator_options {
.to_str()
.unwrap()
.to_string();
- self.deref_mut().insert(k, v);
+ (*opts).deref_mut().insert(k, v);
}
/// \brief Free the allocated memory used by [`opendal_operator_options`]
@@ -1601,3 +1634,279 @@ mod bytes_tests {
assert_eq!(bytes.capacity, 0);
}
}
+
+#[cfg(test)]
+mod option_tests {
+ use super::*;
+ use crate::error::{opendal_code, opendal_error};
+ use crate::operator::{
+ opendal_operator, opendal_operator_read_with,
opendal_operator_reader_with,
+ opendal_operator_stat_with,
+ };
+
+ #[test]
+ fn test_list_options_set_start_after_self_alias_and_substring() {
+ unsafe {
+ // NULL opts is a safe no-op.
+ let initial = CString::new("dir/file_a").unwrap();
+ opendal_list_options::opendal_list_options_set_start_after(
+ std::ptr::null_mut(),
+ initial.as_ptr(),
+ );
+
+ let opts = opendal_list_options::opendal_list_options_new();
+ opendal_list_options::opendal_list_options_set_start_after(opts,
initial.as_ptr());
+ assert_eq!(
+ CStr::from_ptr((*opts).start_after).to_str().unwrap(),
+ "dir/file_a"
+ );
+
+ // Self-alias: pass opts->start_after back into setter.
+ let self_ptr = (*opts).start_after;
+ opendal_list_options::opendal_list_options_set_start_after(opts,
self_ptr);
+ assert_eq!(
+ CStr::from_ptr((*opts).start_after).to_str().unwrap(),
+ "dir/file_a"
+ );
+
+ // Substring alias: pass a pointer inside opts->start_after back
into setter.
+ let sub_ptr = (*opts).start_after.add(4);
+ opendal_list_options::opendal_list_options_set_start_after(opts,
sub_ptr);
+ assert_eq!(
+ CStr::from_ptr((*opts).start_after).to_str().unwrap(),
+ "file_a"
+ );
+
+ // NULL unsets the value.
+ opendal_list_options::opendal_list_options_set_start_after(opts,
std::ptr::null());
+ assert!((*opts).start_after.is_null());
+
+ opendal_list_options::opendal_list_options_free(opts);
+ }
+ }
+
+ #[test]
+ fn test_delete_options_set_version_self_alias_and_substring() {
+ unsafe {
+ let initial = CString::new("v1/rev42").unwrap();
+ opendal_delete_options::opendal_delete_options_set_version(
+ std::ptr::null_mut(),
+ initial.as_ptr(),
+ );
+
+ let opts = opendal_delete_options::opendal_delete_options_new();
+ opendal_delete_options::opendal_delete_options_set_version(opts,
initial.as_ptr());
+ assert_eq!(
+ CStr::from_ptr((*opts).version).to_str().unwrap(),
+ "v1/rev42"
+ );
+
+ // Self-alias: pass opts->version back into setter.
+ let self_ptr = (*opts).version;
+ opendal_delete_options::opendal_delete_options_set_version(opts,
self_ptr);
+ assert_eq!(
+ CStr::from_ptr((*opts).version).to_str().unwrap(),
+ "v1/rev42"
+ );
+
+ // Substring alias: pass a pointer inside opts->version back into
setter.
+ let sub_ptr = (*opts).version.add(3);
+ opendal_delete_options::opendal_delete_options_set_version(opts,
sub_ptr);
+ assert_eq!(CStr::from_ptr((*opts).version).to_str().unwrap(),
"rev42");
+
+ // NULL unsets the value.
+ opendal_delete_options::opendal_delete_options_set_version(opts,
std::ptr::null());
+ assert!((*opts).version.is_null());
+
+ opendal_delete_options::opendal_delete_options_free(opts);
+ }
+ }
+
+ #[test]
+ fn test_operator_options_set_null_guards() {
+ unsafe {
+ let key = CString::new("root").unwrap();
+ let val = CString::new("/myroot").unwrap();
+
+ // NULL opts must be a no-op without UB.
+ opendal_operator_options::opendal_operator_options_set(
+ std::ptr::null_mut(),
+ key.as_ptr(),
+ val.as_ptr(),
+ );
+
+ // NULL inner must also be a no-op without UB.
+ let mut empty_inner = opendal_operator_options {
+ inner: std::ptr::null_mut(),
+ };
+ opendal_operator_options::opendal_operator_options_set(
+ &mut empty_inner,
+ key.as_ptr(),
+ val.as_ptr(),
+ );
+
+ let opts =
opendal_operator_options::opendal_operator_options_new();
+ opendal_operator_options::opendal_operator_options_set(
+ opts,
+ std::ptr::null(),
+ val.as_ptr(),
+ );
+ opendal_operator_options::opendal_operator_options_set(
+ opts,
+ key.as_ptr(),
+ std::ptr::null(),
+ );
+ assert!((*opts).deref().is_empty());
+
+ opendal_operator_options::opendal_operator_options_set(
+ opts,
+ key.as_ptr(),
+ val.as_ptr(),
+ );
+ assert_eq!(
+ (*opts).deref().get("root").map(String::as_str),
+ Some("/myroot")
+ );
+
+ opendal_operator_options::opendal_operator_options_free(opts);
+ }
+ }
+
+ #[test]
+ fn test_out_of_range_conditional_timestamps_rejected() {
+ let valid_ms = 1_700_000_000_000;
+
+ // StatOptions
+ let mut stat = opendal_stat_options {
+ has_if_modified_since: false,
+ if_modified_since: i64::MAX,
+ ..Default::default()
+ };
+ assert!(options::StatOptions::try_from(&stat)
+ .unwrap()
+ .if_modified_since
+ .is_none());
+
+ stat.has_if_modified_since = true;
+ assert_eq!(
+ options::StatOptions::try_from(&stat).unwrap_err().kind(),
+ ErrorKind::ConfigInvalid
+ );
+
+ stat.if_modified_since = valid_ms;
+ stat.has_if_unmodified_since = true;
+ stat.if_unmodified_since = i64::MIN;
+ assert_eq!(
+ options::StatOptions::try_from(&stat).unwrap_err().kind(),
+ ErrorKind::ConfigInvalid
+ );
+
+ stat.if_unmodified_since = valid_ms;
+ let parsed = options::StatOptions::try_from(&stat).unwrap();
+ assert_eq!(
+ parsed.if_modified_since,
+ Some(Timestamp::from_millisecond(valid_ms).unwrap())
+ );
+ assert_eq!(
+ parsed.if_unmodified_since,
+ Some(Timestamp::from_millisecond(valid_ms).unwrap())
+ );
+
+ // ReadOptions
+ let mut read = opendal_read_options {
+ has_if_modified_since: true,
+ if_modified_since: i64::MAX,
+ ..Default::default()
+ };
+ assert_eq!(
+ options::ReadOptions::try_from(&read).unwrap_err().kind(),
+ ErrorKind::ConfigInvalid
+ );
+ read.has_if_modified_since = false;
+ read.has_if_unmodified_since = true;
+ read.if_unmodified_since = i64::MIN;
+ assert_eq!(
+ options::ReadOptions::try_from(&read).unwrap_err().kind(),
+ ErrorKind::ConfigInvalid
+ );
+
+ // ReaderOptions
+ let mut reader = opendal_reader_options {
+ has_if_modified_since: true,
+ if_modified_since: i64::MAX,
+ ..Default::default()
+ };
+ assert_eq!(
+ options::ReaderOptions::try_from(&reader)
+ .unwrap_err()
+ .kind(),
+ ErrorKind::ConfigInvalid
+ );
+ reader.has_if_modified_since = false;
+ reader.has_if_unmodified_since = true;
+ reader.if_unmodified_since = i64::MIN;
+ assert_eq!(
+ options::ReaderOptions::try_from(&reader)
+ .unwrap_err()
+ .kind(),
+ ErrorKind::ConfigInvalid
+ );
+
+ // End-to-end FFI calls return OPENDAL_CONFIG_INVALID and initialize
out params.
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ let op =
opendal::Operator::new(opendal::services::Memory::default()).unwrap();
+ runtime
+ .block_on(op.write("test", "hello"))
+ .expect("seed test object");
+ let c_op = opendal_operator::from_operator(runtime.handle().clone(),
op);
+ let path = CString::new("test").unwrap();
+
+ unsafe {
+ // Default options succeed on memory backend.
+ let default_stat = opendal_stat_options::default();
+ let mut meta = std::ptr::dangling_mut();
+ let err = opendal_operator_stat_with(&*c_op, path.as_ptr(),
&default_stat, &mut meta);
+ assert!(err.is_null());
+ assert!(!meta.is_null());
+ crate::metadata::opendal_metadata::opendal_metadata_free(meta);
+
+ // Out-of-range timestamps must be rejected as ConfigInvalid
instead of
+ // being silently dropped and letting the request succeed
unconditionally.
+ let bad_stat = opendal_stat_options {
+ has_if_modified_since: true,
+ if_modified_since: i64::MAX,
+ ..Default::default()
+ };
+ let mut meta = std::ptr::dangling_mut();
+ let err = opendal_operator_stat_with(&*c_op, path.as_ptr(),
&bad_stat, &mut meta);
+ assert!(!err.is_null());
+ assert_eq!((*err).code(), opendal_code::OPENDAL_CONFIG_INVALID);
+ assert!(meta.is_null());
+ opendal_error::opendal_error_free(err);
+
+ let mut bytes = opendal_bytes {
+ data: std::ptr::dangling_mut(),
+ len: 99,
+ capacity: 99,
+ };
+ let err = opendal_operator_read_with(&*c_op, path.as_ptr(), &read,
&mut bytes);
+ assert!(!err.is_null());
+ assert_eq!((*err).code(), opendal_code::OPENDAL_CONFIG_INVALID);
+ assert!(bytes.data.is_null());
+ assert_eq!(bytes.len, 0);
+ opendal_error::opendal_error_free(err);
+
+ let mut reader_ptr = std::ptr::dangling_mut();
+ let err = opendal_operator_reader_with(&*c_op, path.as_ptr(),
&reader, &mut reader_ptr);
+ assert!(!err.is_null());
+ assert_eq!((*err).code(), opendal_code::OPENDAL_CONFIG_INVALID);
+ assert!(reader_ptr.is_null());
+ opendal_error::opendal_error_free(err);
+
+ opendal_operator::opendal_operator_free(c_op);
+ }
+ }
+}
diff --git a/bindings/c/src/writer.rs b/bindings/c/src/writer.rs
index 3b771381c0..07e0398b50 100644
--- a/bindings/c/src/writer.rs
+++ b/bindings/c/src/writer.rs
@@ -20,7 +20,7 @@ use std::ffi::c_void;
use ::opendal as core;
use super::*;
-use crate::cancel::{block_on_cancellable, CancellableError};
+use crate::cancel::block_on_cancellable;
struct WriterInner {
handle: tokio::runtime::Handle,
@@ -102,11 +102,7 @@ impl opendal_writer {
std::ptr::write(size, len);
std::ptr::null_mut()
}
- Err(CancellableError::Cancelled) => opendal_error::cancelled(),
- Err(CancellableError::Inner(e)) => opendal_error::new(
- core::Error::new(core::ErrorKind::Unexpected, "write failed
from writer")
- .set_source(e),
- ),
+ Err(e) => opendal_error::from_cancellable(e),
}
}
@@ -167,10 +163,7 @@ impl opendal_writer {
}
std::ptr::null_mut()
}
- Err(CancellableError::Cancelled) => opendal_error::cancelled(),
- Err(CancellableError::Inner(e)) => opendal_error::new(
- core::Error::new(core::ErrorKind::Unexpected, "close writer
failed").set_source(e),
- ),
+ Err(e) => opendal_error::from_cancellable(e),
}
}
@@ -185,3 +178,199 @@ impl opendal_writer {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ::opendal::raw::{self, oio};
+ use std::sync::Arc;
+
+ #[derive(Debug)]
+ struct FailingWriteService {
+ inner: raw::Servicer,
+ }
+
+ #[derive(Debug)]
+ struct FailingWriteLayer;
+
+ impl raw::Layer for FailingWriteLayer {
+ fn apply_service(&self, inner: raw::Servicer) -> raw::Servicer {
+ Arc::new(FailingWriteService { inner })
+ }
+ }
+
+ struct FailingWriter;
+
+ impl oio::Write for FailingWriter {
+ async fn write(&mut self, _bs: core::Buffer) -> core::Result<()> {
+ Err(core::Error::new(
+ core::ErrorKind::ConditionNotMatch,
+ "precondition failed on write",
+ ))
+ }
+
+ async fn close(&mut self) -> core::Result<core::Metadata> {
+ Err(core::Error::new(
+ core::ErrorKind::PermissionDenied,
+ "permission denied on close",
+ ))
+ }
+
+ async fn abort(&mut self) -> core::Result<()> {
+ Ok(())
+ }
+ }
+
+ impl raw::Service for FailingWriteService {
+ type Reader = oio::Reader;
+ type Writer = FailingWriter;
+ type Lister = oio::Lister;
+ type Deleter = oio::Deleter;
+ type Copier = oio::Copier;
+ type Composer = oio::Composer;
+
+ fn info(&self) -> raw::ServiceInfo {
+ self.inner.info()
+ }
+
+ fn capability(&self) -> core::Capability {
+ let mut cap = self.inner.capability();
+ cap.write = true;
+ cap.write_can_multi = true;
+ cap
+ }
+
+ async fn create_dir(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpCreateDir,
+ ) -> core::Result<raw::RpCreateDir> {
+ self.inner.create_dir(ctx, path, args).await
+ }
+
+ async fn stat(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpStat,
+ ) -> core::Result<raw::RpStat> {
+ self.inner.stat(ctx, path, args).await
+ }
+
+ fn read(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpRead,
+ ) -> core::Result<Self::Reader> {
+ self.inner.read(ctx, path, args)
+ }
+
+ fn write(
+ &self,
+ _ctx: &core::OperationContext,
+ _path: &str,
+ _args: raw::OpWrite,
+ ) -> core::Result<Self::Writer> {
+ Ok(FailingWriter)
+ }
+
+ fn delete(&self, ctx: &core::OperationContext) ->
core::Result<Self::Deleter> {
+ self.inner.delete(ctx)
+ }
+
+ fn list(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpList,
+ ) -> core::Result<Self::Lister> {
+ self.inner.list(ctx, path, args)
+ }
+
+ fn copy(
+ &self,
+ ctx: &core::OperationContext,
+ from: &str,
+ to: &str,
+ args: raw::OpCopy,
+ ) -> core::Result<Self::Copier> {
+ self.inner.copy(ctx, from, to, args)
+ }
+
+ async fn rename(
+ &self,
+ ctx: &core::OperationContext,
+ from: &str,
+ to: &str,
+ args: raw::OpRename,
+ ) -> core::Result<raw::RpRename> {
+ self.inner.rename(ctx, from, to, args).await
+ }
+
+ fn compose(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpCompose,
+ ) -> core::Result<Self::Composer> {
+ self.inner.compose(ctx, path, args)
+ }
+
+ async fn presign(
+ &self,
+ ctx: &core::OperationContext,
+ path: &str,
+ args: raw::OpPresign,
+ ) -> core::Result<raw::RpPresign> {
+ self.inner.presign(ctx, path, args).await
+ }
+ }
+
+ #[test]
+ fn test_writer_preserves_backend_error_kinds() {
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ let op = core::Operator::new(core::services::Memory::default())
+ .unwrap()
+ .layer(FailingWriteLayer);
+ let writer = runtime.block_on(op.writer("test")).unwrap();
+ let writer = Box::into_raw(Box::new(opendal_writer::new(
+ runtime.handle().clone(),
+ writer,
+ )));
+
+ let payload = b"hello";
+ let bytes = std::mem::ManuallyDrop::new(opendal_bytes {
+ data: payload.as_ptr() as *mut u8,
+ len: payload.len(),
+ capacity: payload.len(),
+ });
+ let mut written = 99;
+ let err =
+ unsafe { opendal_writer::opendal_writer_write(&mut *writer,
&bytes, &mut written) };
+ assert!(!err.is_null());
+ assert_eq!(
+ unsafe { (*err).code() },
+ opendal_code::OPENDAL_CONDITION_NOT_MATCH
+ );
+ assert_eq!(written, 0);
+ unsafe { opendal_error::opendal_error_free(err) };
+
+ let mut meta = std::ptr::dangling_mut();
+ let err = unsafe {
opendal_writer::opendal_writer_close_with_metadata(writer, &mut meta) };
+ assert!(!err.is_null());
+ assert_eq!(
+ unsafe { (*err).code() },
+ opendal_code::OPENDAL_PERMISSION_DENIED
+ );
+ assert!(meta.is_null());
+ unsafe {
+ opendal_error::opendal_error_free(err);
+ opendal_writer::opendal_writer_free(writer);
+ }
+ }
+}
diff --git a/bindings/c/tests/bdd.cpp b/bindings/c/tests/bdd.cpp
index 73630ef2c6..0572a1a37b 100644
--- a/bindings/c/tests/bdd.cpp
+++ b/bindings/c/tests/bdd.cpp
@@ -17,6 +17,7 @@
* under the License.
*/
+#include <limits>
#include "gtest/gtest.h"
extern "C" {
@@ -418,3 +419,102 @@ TEST_F(OpendalBddTest, OutputParametersAndFailureInitTest)
EXPECT_EQ(opendal_operator_delete(this->p, "meta-write"), nullptr);
EXPECT_EQ(opendal_operator_delete(this->p, "writer-meta"), nullptr);
}
+
+TEST_F(OpendalBddTest, OptionStringSelfAliasingSafe)
+{
+ opendal_list_options* list_opts = opendal_list_options_new();
+ ASSERT_NE(list_opts, nullptr);
+ opendal_list_options_set_start_after(list_opts, "dir/file_a");
+ ASSERT_NE(list_opts->start_after, nullptr);
+ opendal_list_options_set_start_after(list_opts, list_opts->start_after);
+ EXPECT_STREQ(list_opts->start_after, "dir/file_a");
+ opendal_list_options_set_start_after(list_opts, list_opts->start_after +
4);
+ EXPECT_STREQ(list_opts->start_after, "file_a");
+ opendal_list_options_set_start_after(list_opts, nullptr);
+ EXPECT_EQ(list_opts->start_after, nullptr);
+ opendal_list_options_free(list_opts);
+
+ opendal_delete_options* del_opts = opendal_delete_options_new();
+ ASSERT_NE(del_opts, nullptr);
+ opendal_delete_options_set_version(del_opts, "v1/rev42");
+ ASSERT_NE(del_opts->version, nullptr);
+ opendal_delete_options_set_version(del_opts, del_opts->version);
+ EXPECT_STREQ(del_opts->version, "v1/rev42");
+ opendal_delete_options_set_version(del_opts, del_opts->version + 3);
+ EXPECT_STREQ(del_opts->version, "rev42");
+ opendal_delete_options_set_version(del_opts, nullptr);
+ EXPECT_EQ(del_opts->version, nullptr);
+ opendal_delete_options_free(del_opts);
+}
+
+TEST_F(OpendalBddTest, NullPointerGuards)
+{
+ EXPECT_EQ(opendal_presigned_request_method(nullptr), nullptr);
+ EXPECT_EQ(opendal_presigned_request_uri(nullptr), nullptr);
+ EXPECT_EQ(opendal_presigned_request_headers(nullptr), nullptr);
+ EXPECT_EQ(opendal_presigned_request_headers_len(nullptr), 0);
+
+ opendal_operator_options_set(nullptr, "root", "/myroot");
+ opendal_operator_options* opts = opendal_operator_options_new();
+ opendal_operator_options_set(opts, nullptr, "/myroot");
+ opendal_operator_options_set(opts, "root", nullptr);
+ opendal_operator_options_free(opts);
+
+ opendal_operator_layers_add_retry(nullptr, true, 2.0f, 1000, 10000, 3);
+ opendal_operator_layers_add_timeout(nullptr, 1000, 2000);
+}
+
+TEST_F(OpendalBddTest, RejectOutOfRangeConditionalTimestamps)
+{
+ const int64_t max_ts = std::numeric_limits<int64_t>::max();
+ const int64_t min_ts = std::numeric_limits<int64_t>::min();
+
+ opendal_stat_options* stat_opts = opendal_stat_options_new();
+ opendal_stat_options_set_if_modified_since(stat_opts, max_ts);
+ opendal_metadata* meta = reinterpret_cast<opendal_metadata*>(0x1);
+ opendal_error* err = opendal_operator_stat_with(this->p, "any", stat_opts,
&meta);
+ ASSERT_NE(err, nullptr);
+ EXPECT_EQ(err->code, OPENDAL_CONFIG_INVALID);
+ EXPECT_EQ(meta, nullptr);
+ opendal_error_free(err);
+
+ opendal_presigned_request* req =
reinterpret_cast<opendal_presigned_request*>(0x1);
+ err = opendal_operator_presign_stat_with(this->p, "any", 60, stat_opts,
&req);
+ ASSERT_NE(err, nullptr);
+ EXPECT_EQ(err->code, OPENDAL_CONFIG_INVALID);
+ EXPECT_EQ(req, nullptr);
+ opendal_error_free(err);
+ opendal_stat_options_free(stat_opts);
+
+ opendal_read_options* read_opts = opendal_read_options_new();
+ opendal_read_options_set_if_unmodified_since(read_opts, min_ts);
+ opendal_bytes bytes = {
+ .data = reinterpret_cast<uint8_t*>(0x1),
+ .len = 99,
+ .capacity = 99,
+ };
+ err = opendal_operator_read_with(this->p, "any", read_opts, &bytes);
+ ASSERT_NE(err, nullptr);
+ EXPECT_EQ(err->code, OPENDAL_CONFIG_INVALID);
+ EXPECT_EQ(bytes.data, nullptr);
+ EXPECT_EQ(bytes.len, 0);
+ opendal_error_free(err);
+
+ req = reinterpret_cast<opendal_presigned_request*>(0x1);
+ err = opendal_operator_presign_read_with(this->p, "any", 60, read_opts,
&req);
+ ASSERT_NE(err, nullptr);
+ EXPECT_EQ(err->code, OPENDAL_CONFIG_INVALID);
+ EXPECT_EQ(req, nullptr);
+ opendal_error_free(err);
+ opendal_read_options_free(read_opts);
+
+ opendal_reader_options* reader_opts = opendal_reader_options_new();
+ opendal_reader_options_set_if_modified_since(reader_opts, max_ts);
+ opendal_reader* reader = reinterpret_cast<opendal_reader*>(0x1);
+ err = opendal_operator_reader_with(this->p, "any", reader_opts, &reader);
+ ASSERT_NE(err, nullptr);
+ EXPECT_EQ(err->code, OPENDAL_CONFIG_INVALID);
+ EXPECT_EQ(reader, nullptr);
+ opendal_error_free(err);
+ opendal_reader_options_free(reader_opts);
+}
diff --git a/bindings/c/tests/reader.cpp b/bindings/c/tests/reader.cpp
index 2e7d1e7699..7567d9dd1e 100644
--- a/bindings/c/tests/reader.cpp
+++ b/bindings/c/tests/reader.cpp
@@ -115,3 +115,28 @@ TEST_F(OpendalReaderTest, SeekTest)
opendal_reader_free(reader);
}
+
+TEST_F(OpendalReaderTest, PreservesNotFoundErrorCode)
+{
+ opendal_reader* reader = nullptr;
+ opendal_error* err = opendal_operator_reader(this->p, "/does_not_exist",
&reader);
+ ASSERT_EQ(err, nullptr);
+ ASSERT_NE(reader, nullptr);
+
+ uint8_t buf[16] = { 0 };
+ uintptr_t read_size = 99;
+ err = opendal_reader_read(reader, buf, sizeof(buf), &read_size);
+ ASSERT_NE(err, nullptr);
+ EXPECT_EQ(err->code, OPENDAL_NOT_FOUND);
+ EXPECT_EQ(read_size, 0);
+ opendal_error_free(err);
+
+ uint64_t pos = 99;
+ err = opendal_reader_seek(reader, 0, OPENDAL_SEEK_END, &pos);
+ ASSERT_NE(err, nullptr);
+ EXPECT_EQ(err->code, OPENDAL_NOT_FOUND);
+ EXPECT_EQ(pos, 0);
+ opendal_error_free(err);
+
+ opendal_reader_free(reader);
+}