coap_message_utils/error.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
//! Common error types
#[cfg(feature = "defmt_0_3")]
use defmt_0_3::Format;
// This makes the feature not additive, to a hypothetical defmt_0_4, but then again, those would
// probably conflict anyway. (If there is ever a need for multiple impls at the same time, all the
// fallout would be that we'd have to implement Format manually, as we can only have a single defmt
// module in scope when we derive Format)
#[cfg(feature = "defmt_0_3")]
use defmt_0_3 as defmt;
/// A build-time-flexible renderable error type
///
/// This is used wherever this crate produces errors, and also recommended for outside handlers --
/// the idea being that the more code parts share a type, the more compact code can be emitted.
///
/// Depending on what gets configured, it may just be a single u8 error code, or it may contain
/// more details such as the number of the option that could not be processed, or any other
/// Standard Problem Details (RFC9290).
///
/// The most typical use for this is to be used as a
/// [`coap_handler::Handler::ExtractRequestError`](https://docs.rs/coap-handler/latest/coap_handler/trait.Handler.html#associatedtype.ExtractRequestError).
/// It can also be used as a
/// [`coap_handler::Handler::BuildResponseError`](https://docs.rs/coap-handler/latest/coap_handler/trait.Handler.html#associatedtype.BuildResponseError),
/// to express late errors, but then it needs to coexist with the errors raised from writing to the
/// response message. For that coexistence, the [`Self::from_unionerror`] conversion is provided.
#[derive(Debug)]
#[cfg_attr(feature = "defmt_0_3", derive(Format))]
pub struct Error {
code: u8,
#[cfg(feature = "error_unprocessed_coap_option")]
unprocessed_option: Option<core::num::NonZeroU16>,
#[cfg(feature = "error_request_body_error_position")]
request_body_error_position: Option<u32>,
#[cfg(feature = "error_max_age")]
max_age: Option<u32>,
// reason: When not feature=error_title but debug_assertions, this field's presence in Debug is
// sufficient reason to have it.
#[allow(dead_code)]
#[cfg(any(feature = "error_title", debug_assertions))]
title: Option<&'static str>,
}
impl Error {
const MAX_ENCODED_LEN: usize = {
let mut count = 0;
count += 1; // up to 24 items
if cfg!(feature = "error_unprocessed_coap_option") {
// 1 item, 1+0 key, value up to 16bit
count += 1 + 3;
}
if cfg!(feature = "error_request_body_error_position") {
// 1 item, 1+1 key, value up to 64bit in theory
count += 2 + 5;
}
count
};
/// Create an error response for an unprocessed option
///
/// The response is rendered with a single unprocessed-coap-option problem detail if that
/// feature is enabled.
///
/// If the unprocessed option has a special error code (e.g. Accept => 4.06 Not Acceptable or
/// Content Format => 4.15 Unsupported Content-Format), that code is emitted instead of the
/// default 4.02 Bad Option, and the unprocessed-coap-option problem details is not emitted. In
/// particular, Uri-Path is turned into a 4.04 Not Found, because it indicates that some
/// resource did not expect any URI components after the last expected component.
///
/// Note that the CoAP option number is given as a u16, as is common around the CoAP crates
/// (even though 0 is a reseved value). It is an error to pass in the value 0; the
/// implementation may treat this as a reason for a panic, or silently ignore the error and not
/// render the problem detail.
pub fn bad_option(unprocessed_option: u16) -> Self {
let special_code = match unprocessed_option {
coap_numbers::option::ACCEPT => Some(coap_numbers::code::NOT_ACCEPTABLE),
coap_numbers::option::PROXY_URI | coap_numbers::option::PROXY_SCHEME => {
Some(coap_numbers::code::PROXYING_NOT_SUPPORTED)
}
coap_numbers::option::CONTENT_FORMAT => {
Some(coap_numbers::code::UNSUPPORTED_CONTENT_FORMAT)
}
coap_numbers::option::URI_PATH => Some(coap_numbers::code::NOT_FOUND),
_ => None,
};
#[allow(unused)]
let unprocessed_option = if special_code.is_some() {
None
} else {
core::num::NonZeroU16::try_from(unprocessed_option).ok()
};
let code = special_code.unwrap_or(coap_numbers::code::BAD_OPTION);
#[allow(clippy::needless_update)]
Self {
code,
#[cfg(feature = "error_unprocessed_coap_option")]
unprocessed_option,
..Self::otherwise_empty()
}
}
/// Create a 4.00 Bad Request error with a Request Body Error Position indicating at which
/// position in the request's body the error occurred
///
/// If the crate is compiled without the `error_request_body_error_position` feature, the
/// position information will be ignored. The value may also be ignored if it exceeds an
/// internal limit of how large values can be expressed.
pub fn bad_request_with_rbep(#[allow(unused)] byte: usize) -> Self {
#[allow(clippy::needless_update)]
Self {
code: coap_numbers::code::BAD_REQUEST,
#[cfg(feature = "error_request_body_error_position")]
request_body_error_position: byte.try_into().ok(),
..Self::otherwise_empty()
}
}
/// Is there any reason to even start rendering CBOR?
///
/// This provides a precise number of items.
///
/// Note that the presence of a `title` is *not* counted here, as the title on its own can just
/// as well be sent in a diagnostic payload.
#[inline(always)]
fn problem_details_count(&self) -> u8 {
#[allow(unused_mut)]
let mut count = 0;
#[cfg(feature = "error_unprocessed_coap_option")]
if self.unprocessed_option.is_some() {
count += 1;
}
#[cfg(feature = "error_request_body_error_position")]
if self.request_body_error_position.is_some() {
count += 1;
}
count
}
/// Convert [any writable message's
/// `UnionError`](coap_message::MinimalWritableMessage::UnionError) into an Error.
///
/// This discards the error's details and just builds an Internal Server Error.
///
/// The reason why this exists as a method is ergonomics: It allows handler implementations to
/// have a
/// [`BuildResponse`](https://docs.rs/coap-handler/latest/coap_handler/trait.Handler.html#tymethod.build_response)
/// that returns crafted [`Error`] instances, and still escalate errors from writing through
/// `.map_err(Error::from_unionerror)`.
///
/// ## Downsides
///
/// Using this might lose some debug information if the errors of the writable message turn out
/// to be more than Internal Server Error messages. Currently, such uses are not known; if they
/// come up, this method will likely be deprecated in favor of something that extracts errors
/// better. (One option for that point is to use an enum of Error and whatever the other thing
/// is; right now, this would only lead to duplication in generated machine code).
///
/// ## Constraints
///
/// Note that this signature does not constrain the type of `_err` a lot -- there is no hard
/// criterium to recognize whether a type is a conversion or write error pertaining to the
/// current response message, or just an arbitrary error. By convention, this is only applied
/// to items that can be converted into the UnionError; upholding that convention helps
/// spotting if ever there needs to be a replacement for this.
pub fn from_unionerror(
_err: impl core::fmt::Debug + coap_message::error::RenderableOnMinimal,
) -> Self {
Self::internal_server_error()
}
/// Create an otherwise empty 4.00 Bad Request error
pub fn bad_request() -> Self {
#[allow(clippy::needless_update)]
Self {
code: coap_numbers::code::BAD_REQUEST,
..Self::otherwise_empty()
}
}
/// Create an otherwise empty 4.01 Unauthorized error
pub fn unauthorized() -> Self {
#[allow(clippy::needless_update)]
Self {
code: coap_numbers::code::UNAUTHORIZED,
..Self::otherwise_empty()
}
}
/// Create an otherwise empty 4.03 Forbidden error
pub fn forbidden() -> Self {
#[allow(clippy::needless_update)]
Self {
code: coap_numbers::code::FORBIDDEN,
..Self::otherwise_empty()
}
}
/// Create an otherwise empty 4.04 Not Found error
pub fn not_found() -> Self {
#[allow(clippy::needless_update)]
Self {
code: coap_numbers::code::NOT_FOUND,
..Self::otherwise_empty()
}
}
/// Create an otherwise empty 4.05 Method Not Allowed error
pub fn method_not_allowed() -> Self {
#[allow(clippy::needless_update)]
Self {
code: coap_numbers::code::METHOD_NOT_ALLOWED,
..Self::otherwise_empty()
}
}
/// Create an otherwise empty 4.06 Not Acceptable error
///
/// Note that this error can also be created by calling [`Self::bad_option(o)`] when `o` is an
/// Accept option (so there is no need for special casing by the application, but it
/// may be convenient to use this function when it is decided late that the requested format
/// was parsed turned out to be unsuitable).
pub fn not_acceptable() -> Self {
#[allow(clippy::needless_update)]
Self {
code: coap_numbers::code::NOT_ACCEPTABLE,
..Self::otherwise_empty()
}
}
/// Create an otherwise empty 4.15 Unsupported Content Format error
///
/// Note that this error can also be created by calling [`Self::bad_option(o)`] when `o` is a
/// Content-Format option (so there is no need for special casing by the application, but it
/// may be convenient to use this function when it is decided late that a content format that
/// was parsed turned out to be unsuitable).
pub fn unsupported_content_format() -> Self {
#[allow(clippy::needless_update)]
Self {
code: coap_numbers::code::UNSUPPORTED_CONTENT_FORMAT,
..Self::otherwise_empty()
}
}
/// Create an otherwise empty 5.00 Internal Server Error error
pub fn internal_server_error() -> Self {
#[allow(clippy::needless_update)]
Self {
code: coap_numbers::code::INTERNAL_SERVER_ERROR,
..Self::otherwise_empty()
}
}
/// Create an otherwise empty 5.03 Service Unavailable error
pub fn service_unavailable() -> Self {
#[allow(clippy::needless_update)]
Self {
code: coap_numbers::code::SERVICE_UNAVAILABLE,
..Self::otherwise_empty()
}
}
/// Set a Max-Age
///
/// Unlike the constructors that set error details, this modifier is only available when the
/// data is actually stored, because not emitting it is not just elision of possibly helful
/// details, but may change the networks' behavior (for example, because a long Max-Age is not
/// sent and the client keeps retrying every minute).
#[cfg(feature = "error_max_age")]
pub fn with_max_age(self, max_age: u32) -> Self {
Self {
max_age: Some(max_age),
..self
}
}
/// Set a title on the error
///
/// The title will be used as a diagnostic payload if no other diagnostic components are on a
/// message, or it will be set as the title detail. This function is available unconditionally,
/// but the title property is only stored if the `error_title` feature is enabled, or on debug
/// builds to be shown in the [Debug] representation.
///
/// On CoAP message implementations where
/// [MinimalWritableMessage::promote_to_mutable_writable_message] returns None, the title may
/// not be shown in more complex results for lack of buffer space; where it returns Some, it
/// can use the full available message and is thus usually shown (unless the full error
/// response is too large for the message, in which case no payload is emitted).
#[allow(unused_variables)]
pub fn with_title(self, title: &'static str) -> Self {
Self {
#[cfg(any(feature = "error_title", debug_assertions))]
title: Some(title),
..self
}
}
/// A default-ish constructor that leaves the code in an invalid state -- useful for other
/// constructors so they only have to cfg() out the values they need, and not every single
/// line.
///
/// It is typically used as `#[allow(clippy::needless_update)] Self { code,
/// ..Self::otherwise_empty()}`, where the annotation quenches complaints about all members
/// already being set in builds with no extra features.
#[inline]
fn otherwise_empty() -> Self {
Self {
code: 0,
#[cfg(feature = "error_unprocessed_coap_option")]
unprocessed_option: None,
#[cfg(feature = "error_request_body_error_position")]
request_body_error_position: None,
#[cfg(feature = "error_max_age")]
max_age: None,
#[cfg(any(feature = "error_title", debug_assertions))]
title: None,
}
}
}
impl coap_message::error::RenderableOnMinimal for Error {
type Error<IE: coap_message::error::RenderableOnMinimal + core::fmt::Debug> = IE;
fn render<M: coap_message::MinimalWritableMessage>(
self,
message: &mut M,
) -> Result<(), Self::Error<M::UnionError>> {
use coap_message::{Code, OptionNumber};
message.set_code(M::Code::new(self.code)?);
// In a minimal setup, this is unconditionally 0, and the rest of the problem details stuff
// should not be emitted in optimized code. If max_age is off too, the optimized function
// just returns here already.
let mut pd_count = self.problem_details_count();
if pd_count > 0 {
// That's quite liktely to be Some, as that registry is stable
const PROBLEM_DETAILS: Option<u16> =
coap_numbers::content_format::from_str("application/concise-problem-details+cbor");
// May err on stacks that can't do Content-Format (but that's rare).
let cfopt = M::OptionNumber::new(coap_numbers::option::CONTENT_FORMAT);
if let Some((pd, cfopt)) = PROBLEM_DETAILS.zip(cfopt.ok()) {
// If this goes wrong, we rather send the empty response (lest the CBOR be
// interpreted as plain text diagnostic payload) -- better to send the unannotated
// code than send even less information by falling back to an internal server error
// message.
if message.add_option_uint(cfopt, pd).is_err() {
pd_count = 0;
}
}
};
#[cfg(feature = "error_max_age")]
if let Some(max_age) = self.max_age {
// Failure to set this is critical in the sense that we better report it as an internal
// server error. If problem details are involved, the server should remove that in its
// error path.
message.add_option_uint(
M::OptionNumber::new(coap_numbers::option::MAX_AGE)?,
max_age,
)?;
}
let encode = |mut cursor: minicbor::encode::write::Cursor<_>, try_include_title| {
let mut encoder = minicbor::Encoder::new(&mut cursor);
#[cfg(feature = "error_title")]
let extra_length_for_title = u64::from(try_include_title && self.title.is_some());
#[cfg(not(feature = "error_title"))]
let extra_length_for_title = 0;
#[cfg(not(feature = "error_title"))]
let _ = try_include_title;
#[allow(unused_mut)]
let mut encoder = encoder.map(u64::from(pd_count) + extra_length_for_title)?;
#[cfg(feature = "error_unprocessed_coap_option")]
if let Some(unprocessed_option) = self.unprocessed_option {
encoder = encoder.i8(-8)?;
encoder = encoder.u16(unprocessed_option.into())?;
}
#[cfg(feature = "error_request_body_error_position")]
if let Some(position) = self.request_body_error_position {
encoder = encoder.i8(-25)?;
encoder = encoder.u32(position)?;
}
#[cfg(feature = "error_title")]
if try_include_title {
if let Some(title) = self.title {
encoder = encoder.i8(-1)?;
encoder = encoder.str(title)?;
}
}
let _ = encoder;
let written = cursor.position();
Ok(written)
};
if pd_count > 0 {
if let Some(message) = message.promote_to_mutable_writable_message() {
use coap_message::MutableWritableMessage;
let max_len = Self::MAX_ENCODED_LEN;
#[cfg(feature = "error_title")]
let max_len = max_len
+ match self.title {
Some(t) => 1 + 5 + t.len(),
None => 0,
};
let payload = message.payload_mut_with_len(max_len)?;
let cursor = minicbor::encode::write::Cursor::new(payload);
if let Ok::<_, minicbor::encode::Error<_>>(written) = encode(cursor, true) {
message.truncate(written)?;
} else {
message.truncate(0)?;
}
} else {
// When monomorphized for a message type where promote_to_mutable_writable_message
// is inline Some, this branch should not even be emitted, let alone taken.
let mut buf = [0u8; Self::MAX_ENCODED_LEN];
let cursor = minicbor::encode::write::Cursor::new(buf.as_mut());
if let Ok::<_, minicbor::encode::Error<_>>(written) = encode(cursor, false) {
message.set_payload(&buf[..written])?;
}
}
} else {
#[cfg(feature = "error_title")]
if let Some(title) = self.title {
message.set_payload(title.as_bytes())?;
}
}
Ok(())
}
}