Debian Codegraph @

src/error.rs

raw symbols SCIP
1 // SPDX-License-Identifier: Apache-2.0 or MIT
2 //
3 // Copyright 2021 Sony Group Corporation
4 //
5
6 use std::borrow::Cow;
7 use std::error::Error;
8 use std::fmt;
9 use std::ops::Deref;
10
11 pub(crate) type Result<T> = std::result::Result<T, SeccompError>;
12
13 /// Errnos returned by the libseccomp API.
14 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15 #[non_exhaustive]
16 // https://github.com/seccomp/libseccomp/blob/3c0dedd45713d7928c459b6523b78f4cfd435269/src/api.c#L60
17 pub enum SeccompErrno {
18 /// The library doesn't permit the particular operation.
19 EACCES,
20 /// There was a system failure beyond the control of libseccomp.
21 ECANCELED,
22 /// Architecture/ABI specific failure.
23 EDOM,
24 /// Failure regarding the existence of argument.
25 EEXIST,
26 /// Internal libseccomp failure.
27 EFAULT,
28 /// Invalid input to the libseccomp API.
29 EINVAL,
30 /// No matching entry found.
31 ENOENT,
32 /// Unable to allocate enough memory to perform the requested operation.
33 ENOMEM,
34 /// The library doesn't support the particular operation.
35 EOPNOTSUPP,
36 /// Provided buffer is too small.
37 ERANGE,
38 /// Unable to load the filter due to thread issues.
39 ESRCH,
40 }
41
42 impl SeccompErrno {
43 fn strerror(&self) -> &'static str {
44 use SeccompErrno::*;
45
46 match self {
47 EACCES => "The library doesn't permit the particular operation",
48 ECANCELED => "There was a system failure beyond the control of libseccomp",
49 EDOM => "Architecture/ABI specific failure",
50 EEXIST => "Failure regarding the existence of argument",
51 EFAULT => "Internal libseccomp failure",
52 EINVAL => "Invalid input to the libseccomp API",
53 ENOENT => "No matching entry found",
54 ENOMEM => "Unable to allocate enough memory to perform the requested operation",
55 EOPNOTSUPP => "The library doesn't support the particular operation",
56 ERANGE => "Provided buffer is too small",
57 ESRCH => "Unable to load the filter due to thread issues",
58 }
59 }
60
61 fn to_sysrawrc(self) -> i32 {
62 use SeccompErrno::*;
63
64 match self {
65 EACCES => libc::EACCES,
66 ECANCELED => libc::ECANCELED,
67 EDOM => libc::EDOM,
68 EEXIST => libc::EEXIST,
69 EFAULT => libc::EFAULT,
70 EINVAL => libc::EINVAL,
71 ENOENT => libc::ENOENT,
72 ENOMEM => libc::ENOMEM,
73 EOPNOTSUPP => libc::EOPNOTSUPP,
74 ERANGE => libc::ERANGE,
75 ESRCH => libc::ESRCH,
76 }
77 }
78 }
79
80 impl fmt::Display for SeccompErrno {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 f.write_str(self.strerror())
83 }
84 }
85
86 /// A list specifying different categories of error.
87 #[derive(Debug, PartialEq, Eq, Hash)]
88 #[non_exhaustive]
89 pub(crate) enum ErrorKind {
90 /// An error that represents error code on failure of the libseccomp API.
91 Errno(SeccompErrno),
92 /// A system's raw error code.
93 SysRawRc(i32),
94 /// An invalid Architecture.
95 InvalidArch(u32),
96 /// An invalid Action.
97 InvalidAction(u32),
98 /// An invalid string in from_str.
99 FromStr(String),
100 /// A lower-level error that is caused by an error from a lower-level module.
101 Source,
102 /// A custom error that does not fall under any other error kind.
103 Common(Cow<'static, str>),
104 }
105
106 /// The error type for libseccomp operations.
107 pub struct SeccompError {
108 kind: ErrorKind,
109 source: Option<Box<dyn Error + Send + Sync>>,
110 }
111
112 impl SeccompError {
113 pub(crate) fn new(kind: ErrorKind) -> Self {
114 Self { kind, source: None }
115 }
116
117 pub(crate) fn with_source<E>(kind: ErrorKind, source: E) -> Self
118 where
119 E: Error + Send + Sync + 'static,
120 {
121 Self {
122 kind,
123 source: Some(Box::new(source)),
124 }
125 }
126
127 pub(crate) fn with_msg<M>(msg: M) -> Self
128 where
129 M: Into<Cow<'static, str>>,
130 {
131 Self {
132 kind: ErrorKind::Common(msg.into()),
133 source: None,
134 }
135 }
136
137 #[allow(dead_code)]
138 pub(crate) fn with_msg_and_source<M, E>(msg: M, source: E) -> Self
139 where
140 M: Into<Cow<'static, str>>,
141 E: Error + Send + Sync + 'static,
142 {
143 Self {
144 kind: ErrorKind::Common(msg.into()),
145 source: Some(Box::new(source)),
146 }
147 }
148
149 pub(crate) fn from_errno(raw_errno: i32) -> Self {
150 let seccomp_errno = match -raw_errno {
151 libc::EACCES => SeccompErrno::EACCES,
152 libc::ECANCELED => SeccompErrno::ECANCELED,
153 libc::EDOM => SeccompErrno::EDOM,
154 libc::EEXIST => SeccompErrno::EEXIST,
155 libc::EFAULT => SeccompErrno::EFAULT,
156 libc::EINVAL => SeccompErrno::EINVAL,
157 libc::ENOENT => SeccompErrno::ENOENT,
158 libc::ENOMEM => SeccompErrno::ENOMEM,
159 libc::EOPNOTSUPP => SeccompErrno::EOPNOTSUPP,
160 libc::ERANGE => SeccompErrno::ERANGE,
161 libc::ESRCH => SeccompErrno::ESRCH,
162 _ => return Self::new(ErrorKind::SysRawRc(raw_errno)),
163 };
164 Self::new(ErrorKind::Errno(seccomp_errno))
165 }
166
167 /// Query the errno returned by the libseccomp API.
168 pub fn errno(&self) -> Option<SeccompErrno> {
169 if let ErrorKind::Errno(errno) = self.kind {
170 Some(errno)
171 } else {
172 None
173 }
174 }
175
176 /// Query the system's raw error code returned when something goes wrong
177 /// in the libc and the kernel.
178 ///
179 /// This function will be useful for users who want to extract the system's
180 /// error code directly returned by [`ScmpFilterAttr::ApiSysRawRc`](`crate::ScmpFilterAttr::ApiSysRawRc`)
181 /// , or get the errno returned by the libseccomp API as a negative integer rather than [`SeccompErrno`].
182 ///
183 /// # Examples
184 ///
185 /// ```
186 /// # use libseccomp::*;
187 /// match set_api(1000) {
188 /// Err(e) => {
189 /// eprintln!("Error: {e}");
190 /// if let Some(sys) = e.sysrawrc() {
191 /// eprintln!("The system's raw error code: {sys}");
192 /// assert_eq!(sys, -libc::EINVAL);
193 /// }
194 /// }
195 /// _ => println!("No error"),
196 /// }
197 /// # Ok::<(), Box<dyn std::error::Error>>(())
198 /// ```
199 pub fn sysrawrc(&self) -> Option<i32> {
200 match self.kind {
201 ErrorKind::SysRawRc(rc) => Some(rc),
202 ErrorKind::Errno(errno) => Some(-errno.to_sysrawrc()),
203 _ => None,
204 }
205 }
206
207 /// Returns the raw ffi value of an unsupported Action/Arch.
208 ///
209 /// # Examples
210 ///
211 /// ```
212 /// # use libseccomp::*;
213 /// let mut ctx = ScmpFilterContext::new(ScmpAction::Allow)?;
214 /// if let Err(err) = ctx.get_act_default() {
215 /// println!("{:#?}", err.raw_ffi_value())
216 /// }
217 /// # Ok::<(), Box<dyn std::error::Error>>(())
218 /// ```
219 pub fn raw_ffi_value(&self) -> Option<u32> {
220 match self.kind {
221 ErrorKind::InvalidArch(v) | ErrorKind::InvalidAction(v) => Some(v),
222 _ => None,
223 }
224 }
225
226 fn msg(&self) -> Cow<'_, str> {
227 match &self.kind {
228 ErrorKind::Errno(e) => e.strerror().into(),
229 ErrorKind::SysRawRc(e) => {
230 format!("The system's raw error code({}) was returned", e).into()
231 }
232 ErrorKind::InvalidArch(_) => "Parse error by invalid architecture".into(),
233 ErrorKind::InvalidAction(_) => "Parse error by invalid action".into(),
234 ErrorKind::FromStr(s) => format!("Error while parsing '{s}'").into(),
235 ErrorKind::Source => self.source.as_ref().unwrap().to_string().into(),
236 ErrorKind::Common(s) => s.deref().into(),
237 }
238 }
239 }
240
241 impl fmt::Display for SeccompError {
242 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243 let msg = self.msg();
244
245 match &self.source {
246 Some(source) if self.kind != ErrorKind::Source => {
247 write!(f, "{} caused by: {}", msg, source)
248 }
249 Some(_) | None => {
250 write!(f, "{}", msg)
251 }
252 }
253 }
254 }
255
256 impl fmt::Debug for SeccompError {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 f.debug_struct("Error")
259 .field("kind", &self.kind)
260 .field("source", &self.source)
261 .field("message", &self.msg())
262 .finish()
263 }
264 }
265
266 impl Error for SeccompError {
267 fn source(&self) -> Option<&(dyn Error + 'static)> {
268 match &self.source {
269 Some(error) => Some(error.as_ref()),
270 None => None,
271 }
272 }
273 }
274
275 /* Does not work without specialization (RFC 1210) or negative trait bounds
276 impl<T: Error> From<T> for SeccompError {
277 fn from(err: T) -> Self {
278 Self::with_source(ErrorKind::Source, err)
279 }
280 }
281 */
282
283 macro_rules! impl_seccomperror_from {
284 ($errty:ty) => {
285 impl From<$errty> for SeccompError {
286 fn from(err: $errty) -> Self {
287 Self::with_source(ErrorKind::Source, err)
288 }
289 }
290 };
291 }
292 impl_seccomperror_from!(std::ffi::NulError);
293 impl_seccomperror_from!(std::num::TryFromIntError);
294 impl_seccomperror_from!(std::str::Utf8Error);
295
296 #[cfg(test)]
297 mod tests {
298 use super::ErrorKind::*;
299 use super::*;
300 use std::ffi::CString;
301
302 const TEST_ERR_MSG: &str = "test error";
303 const TEST_NULL_STR: &str = "f\0oo";
304 const NULL_ERR_MSG: &str = "nul byte found in provided data at position: 1";
305
306 #[test]
307 fn test_msg() {
308 let null_err = CString::new(TEST_NULL_STR).unwrap_err();
309
310 // Errno
311 assert_eq!(
312 SeccompError::from_errno(-libc::EACCES).msg(),
313 SeccompErrno::EACCES.strerror()
314 );
315 assert_eq!(
316 SeccompError::from_errno(-libc::ECANCELED).msg(),
317 SeccompErrno::ECANCELED.strerror()
318 );
319 assert_eq!(
320 SeccompError::from_errno(-libc::EDOM).msg(),
321 SeccompErrno::EDOM.strerror()
322 );
323 assert_eq!(
324 SeccompError::from_errno(-libc::EEXIST).msg(),
325 SeccompErrno::EEXIST.strerror()
326 );
327 assert_eq!(
328 SeccompError::from_errno(-libc::EFAULT).msg(),
329 SeccompErrno::EFAULT.strerror()
330 );
331 assert_eq!(
332 SeccompError::from_errno(-libc::EINVAL).msg(),
333 SeccompErrno::EINVAL.strerror()
334 );
335 assert_eq!(
336 SeccompError::from_errno(-libc::ENOENT).msg(),
337 SeccompErrno::ENOENT.strerror()
338 );
339 assert_eq!(
340 SeccompError::from_errno(-libc::ENOMEM).msg(),
341 SeccompErrno::ENOMEM.strerror()
342 );
343 assert_eq!(
344 SeccompError::new(Errno(SeccompErrno::EOPNOTSUPP)).msg(),
345 SeccompErrno::EOPNOTSUPP.strerror(),
346 );
347 assert_eq!(
348 SeccompError::from_errno(-libc::ERANGE).msg(),
349 SeccompErrno::ERANGE.strerror()
350 );
351 assert_eq!(
352 SeccompError::from_errno(-libc::ESRCH).msg(),
353 SeccompErrno::ESRCH.strerror()
354 );
355
356 // Common
357 assert_eq!(
358 SeccompError::new(Common(TEST_ERR_MSG.into())).msg(),
359 TEST_ERR_MSG
360 );
361
362 // Source
363 assert_eq!(
364 SeccompError::with_source(Source, null_err).msg(),
365 NULL_ERR_MSG
366 );
367
368 // SysRawRc
369 assert_eq!(
370 SeccompError::from_errno(-libc::EPIPE).msg(),
371 format!("The system's raw error code({}) was returned", -libc::EPIPE)
372 );
373
374 // InvalidArch
375 assert_eq!(
376 SeccompError::new(InvalidArch(123)).msg(),
377 "Parse error by invalid architecture",
378 );
379
380 // InvalidAction
381 assert_eq!(
382 SeccompError::new(InvalidAction(123)).msg(),
383 "Parse error by invalid action",
384 );
385
386 // FromStr
387 assert_eq!(
388 SeccompError::new(FromStr("SCMP".to_string())).msg(),
389 "Error while parsing 'SCMP'",
390 );
391 }
392
393 #[test]
394 fn test_source() {
395 let null_err = CString::new(TEST_NULL_STR).unwrap_err();
396
397 assert!(SeccompError::new(Errno(SeccompErrno::EACCES))
398 .source()
399 .is_none());
400 assert!(
401 SeccompError::with_source(Errno(SeccompErrno::EACCES), null_err)
402 .source()
403 .is_some()
404 );
405 }
406
407 #[test]
408 fn test_with_msg() {
409 assert_eq!(SeccompError::with_msg(TEST_ERR_MSG).msg(), TEST_ERR_MSG);
410 assert!(SeccompError::with_msg(TEST_ERR_MSG).source().is_none());
411 }
412
413 #[test]
414 fn test_with_msg_and_source() {
415 let null_err = CString::new(TEST_NULL_STR).unwrap_err();
416
417 assert_eq!(
418 SeccompError::with_msg_and_source(TEST_ERR_MSG, null_err.clone()).msg(),
419 TEST_ERR_MSG
420 );
421 assert!(SeccompError::with_msg_and_source(TEST_ERR_MSG, null_err)
422 .source()
423 .is_some());
424 }
425
426 #[test]
427 fn test_errno() {
428 assert_eq!(
429 SeccompError::from_errno(-libc::EACCES).errno().unwrap(),
430 SeccompErrno::EACCES
431 );
432 assert!(SeccompError::from_errno(libc::EBADFD).errno().is_none());
433 }
434
435 #[test]
436 fn test_sysrawrc() {
437 let tests = &[
438 // The EBADFD is not handled by SeccompErrno
439 libc::EBADFD,
440 // The following errnos are handled by SeccompErrno
441 libc::EACCES,
442 libc::ECANCELED,
443 libc::EDOM,
444 libc::EEXIST,
445 libc::EFAULT,
446 libc::EINVAL,
447 libc::ENOENT,
448 libc::ENOMEM,
449 libc::EOPNOTSUPP,
450 libc::ERANGE,
451 libc::ESRCH,
452 ];
453
454 for errno in tests {
455 assert_eq!(SeccompError::from_errno(-errno).sysrawrc().unwrap(), -errno);
456 }
457 assert!(SeccompError::with_msg("no errno").sysrawrc().is_none());
458 }
459
460 #[test]
461 fn test_raw_ffi_value() {
462 assert_eq!(
463 SeccompError::new(InvalidArch(123)).raw_ffi_value().unwrap(),
464 123
465 );
466 assert_eq!(
467 SeccompError::new(InvalidAction(123))
468 .raw_ffi_value()
469 .unwrap(),
470 123
471 );
472 assert!(SeccompError::new(Common("".into()))
473 .raw_ffi_value()
474 .is_none());
475 }
476
477 #[test]
478 fn test_from() {
479 let null_err = CString::new(TEST_NULL_STR).unwrap_err();
480 let scmp_err = SeccompError::from(null_err.clone());
481
482 assert_eq!(scmp_err.kind, ErrorKind::Source);
483 assert_eq!(scmp_err.source().unwrap().to_string(), null_err.to_string());
484 }
485
486 #[test]
487 fn test_display() {
488 let null_err = CString::new(TEST_NULL_STR).unwrap_err();
489
490 // fmt::Display for SeccompErrno
491 assert_eq!(
492 format!("{}", SeccompErrno::EACCES),
493 SeccompErrno::EACCES.strerror()
494 );
495
496 // Errno without source
497 assert_eq!(
498 format!("{}", SeccompError::new(Errno(SeccompErrno::EACCES))),
499 SeccompErrno::EACCES.strerror()
500 );
501 // Errno with source
502 assert_eq!(
503 format!(
504 "{}",
505 SeccompError::with_source(Errno(SeccompErrno::EACCES), null_err.clone())
506 ),
507 format!(
508 "{} caused by: {}",
509 SeccompErrno::EACCES.strerror(),
510 NULL_ERR_MSG
511 )
512 );
513
514 // Common without source
515 assert_eq!(
516 format!("{}", SeccompError::new(Common(TEST_ERR_MSG.into()))),
517 TEST_ERR_MSG
518 );
519 // Common with source
520 assert_eq!(
521 format!(
522 "{}",
523 SeccompError::with_source(Common(TEST_ERR_MSG.into()), null_err.clone())
524 ),
525 format!("{} caused by: {}", TEST_ERR_MSG, NULL_ERR_MSG)
526 );
527
528 // Source
529 assert_eq!(
530 format!("{}", SeccompError::with_source(ErrorKind::Source, null_err)),
531 NULL_ERR_MSG
532 );
533 }
534
535 #[test]
536 fn test_debug() {
537 let null_err = CString::new(TEST_NULL_STR).unwrap_err();
538
539 // Errno without source
540 assert_eq!(
541 format!("{:?}", SeccompError::new(Errno(SeccompErrno::EACCES))),
542 format!(
543 "Error {{ kind: Errno({}), source: {}, message: \"{}\" }}",
544 "EACCES",
545 "None",
546 SeccompErrno::EACCES.strerror()
547 )
548 );
549 // Errno with source
550 assert_eq!(
551 format!(
552 "{:?}",
553 SeccompError::with_source(Errno(SeccompErrno::EACCES), null_err),
554 ),
555 format!(
556 "Error {{ kind: Errno({}), source: {}, message: \"{}\" }}",
557 "EACCES",
558 "Some(NulError(1, [102, 0, 111, 111]))",
559 SeccompErrno::EACCES.strerror()
560 )
561 );
562 }
563 }