Debian Codegraph @

third_party/rust/nss-gk-api/src/err.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 #![allow(dead_code)]
8 #![allow(clippy::upper_case_acronyms)]
9
10 use std::os::raw::c_char;
11 use std::str::Utf8Error;
12
13 use crate::nss_prelude::*;
14 use crate::prtypes::*;
15
16 include!(concat!(env!("OUT_DIR"), "/nspr_error.rs"));
17 mod codes {
18 #![allow(non_snake_case)]
19 include!(concat!(env!("OUT_DIR"), "/nss_secerr.rs"));
20 include!(concat!(env!("OUT_DIR"), "/nss_sslerr.rs"));
21 include!(concat!(env!("OUT_DIR"), "/mozpkix.rs"));
22 }
23 pub use codes::mozilla_pkix_ErrorCode as mozpkix;
24 pub use codes::SECErrorCodes as sec;
25 pub use codes::SSLErrorCodes as ssl;
26 pub mod nspr {
27 include!(concat!(env!("OUT_DIR"), "/nspr_err.rs"));
28 }
29
30 pub type Res<T> = Result<T, Error>;
31
32 #[derive(Clone, Debug, PartialEq, PartialOrd, Ord, Eq)]
33 pub enum Error {
34 AeadError,
35 AeadTruncated,
36 CertificateLoading,
37 CipherInitFailure,
38 CreateSslSocket,
39 EchRetry(Vec<u8>),
40 HkdfError,
41 InternalError,
42 IntegerOverflow,
43 InvalidEpoch,
44 InvalidInput,
45 MixedHandshakeMethod,
46 NoDataAvailable,
47 NssError {
48 name: String,
49 code: PRErrorCode,
50 desc: String,
51 },
52 OverrunError,
53 SelfEncryptFailure,
54 StringError,
55 TimeTravelError,
56 UnsupportedCipher,
57 UnsupportedCurve,
58 UnsupportedHash,
59 UnsupportedVersion,
60 }
61
62 impl Error {
63 pub(crate) fn last_nss_error() -> Self {
64 Self::from(unsafe { PR_GetError() })
65 }
66 }
67
68 impl std::error::Error for Error {
69 #[must_use]
70 fn cause(&self) -> Option<&dyn std::error::Error> {
71 None
72 }
73 #[must_use]
74 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
75 None
76 }
77 }
78
79 impl std::fmt::Display for Error {
80 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
81 write!(f, "Error: {:?}", self)
82 }
83 }
84
85 impl From<std::num::TryFromIntError> for Error {
86 #[must_use]
87 fn from(_: std::num::TryFromIntError) -> Self {
88 Self::IntegerOverflow
89 }
90 }
91 impl From<std::ffi::NulError> for Error {
92 #[must_use]
93 fn from(_: std::ffi::NulError) -> Self {
94 Self::InternalError
95 }
96 }
97 impl From<Utf8Error> for Error {
98 fn from(_: Utf8Error) -> Self {
99 Self::StringError
100 }
101 }
102 impl From<PRErrorCode> for Error {
103 fn from(code: PRErrorCode) -> Self {
104 let name = wrap_str_fn(|| unsafe { PR_ErrorToName(code) }, "UNKNOWN_ERROR");
105 let desc = wrap_str_fn(
106 || unsafe { PR_ErrorToString(code, PR_LANGUAGE_I_DEFAULT) },
107 "...",
108 );
109 Self::NssError { name, code, desc }
110 }
111 }
112
113 use std::ffi::CStr;
114
115 fn wrap_str_fn<F>(f: F, dflt: &str) -> String
116 where
117 F: FnOnce() -> *const c_char,
118 {
119 unsafe {
120 let p = f();
121 if p.is_null() {
122 return dflt.to_string();
123 }
124 CStr::from_ptr(p).to_string_lossy().into_owned()
125 }
126 }
127
128 pub fn is_blocked(result: &Res<()>) -> bool {
129 match result {
130 Err(Error::NssError { code, .. }) => *code == nspr::PR_WOULD_BLOCK_ERROR,
131 _ => false,
132 }
133 }
134
135 pub trait IntoResult {
136 /// The `Ok` type for the result.
137 type Ok;
138
139 /// Unsafe in our implementors because they take a pointer and have no way
140 /// to ensure that the pointer is valid. An invalid pointer could cause UB
141 /// in `impl Drop for Scoped`.
142 unsafe fn into_result(self) -> Result<Self::Ok, Error>;
143 }
144
145 pub unsafe fn into_result<P>(ptr: *mut P) -> Result<*mut P, Error> {
146 if ptr.is_null() {
147 Err(Error::last_nss_error())
148 } else {
149 Ok(ptr)
150 }
151 }
152
153 // This can be used to implement `IntoResult` for pointer types that do not make
154 // sense as smart pointers. For smart pointers use `scoped_ptr!`.
155 macro_rules! impl_into_result {
156 ($pointer:ty) => {
157 impl $crate::err::IntoResult for *mut $pointer {
158 type Ok = *mut $pointer;
159
160 unsafe fn into_result(self) -> Result<Self::Ok, $crate::err::Error> {
161 $crate::err::into_result(self)
162 }
163 }
164 };
165 }
166
167 impl IntoResult for SECStatus {
168 type Ok = ();
169
170 unsafe fn into_result(self) -> Result<(), Error> {
171 if self == SECSuccess {
172 Ok(())
173 } else {
174 Err(Error::last_nss_error())
175 }
176 }
177 }
178
179 pub fn secstatus_to_res(code: SECStatus) -> Res<()> {
180 // Unsafe in the trait, but this impl should be safe.
181 unsafe { SECStatus::into_result(code) }
182 }
183
184 #[cfg(test)]
185 mod tests {
186 use crate::err::{self, is_blocked, secstatus_to_res, Error, PRErrorCode, PR_SetError};
187 use crate::ssl::{SECFailure, SECSuccess};
188 use test_fixture::fixture_init;
189
190 fn set_error_code(code: PRErrorCode) {
191 // This code doesn't work without initializing NSS first.
192 fixture_init();
193 unsafe {
194 PR_SetError(code, 0);
195 }
196 }
197
198 #[test]
199 fn error_code() {
200 fixture_init();
201 assert_eq!(15 - 0x3000, err::ssl::SSL_ERROR_BAD_MAC_READ);
202 assert_eq!(166 - 0x2000, err::sec::SEC_ERROR_LIBPKIX_INTERNAL);
203 assert_eq!(-5998, err::nspr::PR_WOULD_BLOCK_ERROR);
204 }
205
206 #[test]
207 fn is_ok() {
208 assert!(secstatus_to_res(SECSuccess).is_ok());
209 }
210
211 #[test]
212 fn is_err() {
213 set_error_code(err::ssl::SSL_ERROR_BAD_MAC_READ);
214 let r = secstatus_to_res(SECFailure);
215 assert!(r.is_err());
216 match r.unwrap_err() {
217 Error::NssError { name, code, desc } => {
218 assert_eq!(name, "SSL_ERROR_BAD_MAC_READ");
219 assert_eq!(code, -12273);
220 assert_eq!(
221 desc,
222 "SSL received a record with an incorrect Message Authentication Code."
223 );
224 }
225 _ => unreachable!(),
226 }
227 }
228
229 #[test]
230 fn is_err_zero_code() {
231 set_error_code(0);
232 let r = secstatus_to_res(SECFailure);
233 assert!(r.is_err());
234 match r.unwrap_err() {
235 Error::NssError { name, code, .. } => {
236 assert_eq!(name, "UNKNOWN_ERROR");
237 assert_eq!(code, 0);
238 // Note that we don't test |desc| here because that comes from
239 // strerror(0), which is platform-dependent.
240 }
241 _ => unreachable!(),
242 }
243 }
244
245 #[test]
246 fn blocked() {
247 set_error_code(err::nspr::PR_WOULD_BLOCK_ERROR);
248 let r = secstatus_to_res(SECFailure);
249 assert!(r.is_err());
250 assert!(is_blocked(&r));
251 match r.unwrap_err() {
252 Error::NssError { name, code, desc } => {
253 assert_eq!(name, "PR_WOULD_BLOCK_ERROR");
254 assert_eq!(code, -5998);
255 assert_eq!(desc, "The operation would have blocked");
256 }
257 _ => panic!("bad error type"),
258 }
259 }
260 }