1#![deny(missing_docs)]
2
3use crate::ffi;
28use crate::libc_types::{c_int, c_long, time_t};
29use foreign_types::{ForeignType, ForeignTypeRef};
30use std::cmp::Ordering;
31use std::ffi::CString;
32use std::fmt;
33use std::ptr;
34use std::slice;
35use std::str;
36
37use crate::bio::MemBio;
38use crate::bn::{BigNum, BigNumRef};
39use crate::error::ErrorStack;
40use crate::nid::Nid;
41use crate::stack::Stackable;
42use crate::string::OpensslString;
43use crate::{cvt, cvt_p};
44use openssl_macros::corresponds;
45
46foreign_type_and_impl_send_sync! {
47 type CType = ffi::ASN1_GENERALIZEDTIME;
48 fn drop = ffi::ASN1_GENERALIZEDTIME_free;
49
50 pub struct Asn1GeneralizedTime;
62}
63
64impl fmt::Display for Asn1GeneralizedTimeRef {
65 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66 let bio = MemBio::new().ok();
67 let msg = bio
68 .as_ref()
69 .and_then(|mem_bio| unsafe {
70 cvt(ffi::ASN1_GENERALIZEDTIME_print(
71 mem_bio.as_ptr(),
72 self.as_ptr(),
73 ))
74 .ok()?;
75 str::from_utf8(mem_bio.get_buf()).ok()
76 })
77 .unwrap_or("error");
78 f.write_str(msg)
79 }
80}
81
82#[derive(Debug, Copy, Clone, PartialEq, Eq)]
84pub struct Asn1Type(c_int);
85
86#[allow(missing_docs)] impl Asn1Type {
88 pub const EOC: Asn1Type = Asn1Type(ffi::V_ASN1_EOC);
89
90 pub const BOOLEAN: Asn1Type = Asn1Type(ffi::V_ASN1_BOOLEAN);
91
92 pub const INTEGER: Asn1Type = Asn1Type(ffi::V_ASN1_INTEGER);
93
94 pub const BIT_STRING: Asn1Type = Asn1Type(ffi::V_ASN1_BIT_STRING);
95
96 pub const OCTET_STRING: Asn1Type = Asn1Type(ffi::V_ASN1_OCTET_STRING);
97
98 pub const NULL: Asn1Type = Asn1Type(ffi::V_ASN1_NULL);
99
100 pub const OBJECT: Asn1Type = Asn1Type(ffi::V_ASN1_OBJECT);
101
102 pub const OBJECT_DESCRIPTOR: Asn1Type = Asn1Type(ffi::V_ASN1_OBJECT_DESCRIPTOR);
103
104 pub const EXTERNAL: Asn1Type = Asn1Type(ffi::V_ASN1_EXTERNAL);
105
106 pub const REAL: Asn1Type = Asn1Type(ffi::V_ASN1_REAL);
107
108 pub const ENUMERATED: Asn1Type = Asn1Type(ffi::V_ASN1_ENUMERATED);
109
110 pub const UTF8STRING: Asn1Type = Asn1Type(ffi::V_ASN1_UTF8STRING);
111
112 pub const SEQUENCE: Asn1Type = Asn1Type(ffi::V_ASN1_SEQUENCE);
113
114 pub const SET: Asn1Type = Asn1Type(ffi::V_ASN1_SET);
115
116 pub const NUMERICSTRING: Asn1Type = Asn1Type(ffi::V_ASN1_NUMERICSTRING);
117
118 pub const PRINTABLESTRING: Asn1Type = Asn1Type(ffi::V_ASN1_PRINTABLESTRING);
119
120 pub const T61STRING: Asn1Type = Asn1Type(ffi::V_ASN1_T61STRING);
121
122 pub const TELETEXSTRING: Asn1Type = Asn1Type(ffi::V_ASN1_TELETEXSTRING);
123
124 pub const VIDEOTEXSTRING: Asn1Type = Asn1Type(ffi::V_ASN1_VIDEOTEXSTRING);
125
126 pub const IA5STRING: Asn1Type = Asn1Type(ffi::V_ASN1_IA5STRING);
127
128 pub const UTCTIME: Asn1Type = Asn1Type(ffi::V_ASN1_UTCTIME);
129
130 pub const GENERALIZEDTIME: Asn1Type = Asn1Type(ffi::V_ASN1_GENERALIZEDTIME);
131
132 pub const GRAPHICSTRING: Asn1Type = Asn1Type(ffi::V_ASN1_GRAPHICSTRING);
133
134 pub const ISO64STRING: Asn1Type = Asn1Type(ffi::V_ASN1_ISO64STRING);
135
136 pub const VISIBLESTRING: Asn1Type = Asn1Type(ffi::V_ASN1_VISIBLESTRING);
137
138 pub const GENERALSTRING: Asn1Type = Asn1Type(ffi::V_ASN1_GENERALSTRING);
139
140 pub const UNIVERSALSTRING: Asn1Type = Asn1Type(ffi::V_ASN1_UNIVERSALSTRING);
141
142 pub const BMPSTRING: Asn1Type = Asn1Type(ffi::V_ASN1_BMPSTRING);
143
144 #[must_use]
146 pub fn from_raw(value: c_int) -> Self {
147 Asn1Type(value)
148 }
149
150 #[must_use]
152 pub fn as_raw(&self) -> c_int {
153 self.0
154 }
155}
156
157#[derive(Debug, Clone, PartialEq, Eq, Hash)]
165pub struct TimeDiff {
166 pub days: c_int,
168 pub secs: c_int,
172}
173
174foreign_type_and_impl_send_sync! {
175 type CType = ffi::ASN1_TIME;
176 fn drop = ffi::ASN1_TIME_free;
177 pub struct Asn1Time;
188}
189
190impl Asn1TimeRef {
191 #[corresponds(ASN1_TIME_diff)]
193 pub fn diff(&self, compare: &Self) -> Result<TimeDiff, ErrorStack> {
194 let mut days = 0;
195 let mut secs = 0;
196 let other = compare.as_ptr();
197
198 let err = unsafe { ffi::ASN1_TIME_diff(&mut days, &mut secs, self.as_ptr(), other) };
199
200 match err {
201 0 => Err(ErrorStack::get()),
202 _ => Ok(TimeDiff { days, secs }),
203 }
204 }
205
206 #[corresponds(ASN1_TIME_compare)]
208 pub fn compare(&self, other: &Self) -> Result<Ordering, ErrorStack> {
209 let d = self.diff(other)?;
210 if d.days > 0 || d.secs > 0 {
211 return Ok(Ordering::Less);
212 }
213 if d.days < 0 || d.secs < 0 {
214 return Ok(Ordering::Greater);
215 }
216
217 Ok(Ordering::Equal)
218 }
219}
220
221impl PartialEq for Asn1TimeRef {
222 fn eq(&self, other: &Asn1TimeRef) -> bool {
223 self.diff(other)
224 .map(|t| t.days == 0 && t.secs == 0)
225 .unwrap_or(false)
226 }
227}
228
229impl PartialEq<Asn1Time> for Asn1TimeRef {
230 fn eq(&self, other: &Asn1Time) -> bool {
231 self.diff(other)
232 .map(|t| t.days == 0 && t.secs == 0)
233 .unwrap_or(false)
234 }
235}
236
237impl PartialEq<Asn1Time> for &Asn1TimeRef {
238 fn eq(&self, other: &Asn1Time) -> bool {
239 self.diff(other)
240 .map(|t| t.days == 0 && t.secs == 0)
241 .unwrap_or(false)
242 }
243}
244
245impl PartialOrd for Asn1TimeRef {
246 fn partial_cmp(&self, other: &Asn1TimeRef) -> Option<Ordering> {
247 self.compare(other).ok()
248 }
249}
250
251impl PartialOrd<Asn1Time> for Asn1TimeRef {
252 fn partial_cmp(&self, other: &Asn1Time) -> Option<Ordering> {
253 self.compare(other).ok()
254 }
255}
256
257impl PartialOrd<Asn1Time> for &Asn1TimeRef {
258 fn partial_cmp(&self, other: &Asn1Time) -> Option<Ordering> {
259 self.compare(other).ok()
260 }
261}
262
263impl fmt::Display for Asn1TimeRef {
264 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
265 unsafe {
266 let mem_bio = match MemBio::new() {
267 Err(_) => return f.write_str("error"),
268 Ok(m) => m,
269 };
270 let print_result = cvt(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.as_ptr()));
271 match print_result {
272 Err(_) => f.write_str("error"),
273 Ok(_) => f.write_str(str::from_utf8_unchecked(mem_bio.get_buf())),
274 }
275 }
276 }
277}
278
279impl fmt::Debug for Asn1TimeRef {
280 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
281 f.write_str(&self.to_string())
282 }
283}
284
285impl Asn1Time {
286 #[corresponds(ASN1_TIME_new)]
287 fn new() -> Result<Asn1Time, ErrorStack> {
288 ffi::init();
289
290 unsafe {
291 let handle = cvt_p(ffi::ASN1_TIME_new())?;
292 Ok(Asn1Time::from_ptr(handle))
293 }
294 }
295
296 #[corresponds(X509_gmtime_adj)]
297 fn from_period(period: c_long) -> Result<Asn1Time, ErrorStack> {
298 ffi::init();
299
300 unsafe {
301 let handle = cvt_p(ffi::X509_gmtime_adj(ptr::null_mut(), period))?;
302 Ok(Asn1Time::from_ptr(handle))
303 }
304 }
305
306 pub fn days_from_now(days: u32) -> Result<Asn1Time, ErrorStack> {
308 Self::from_period((days * 60 * 60 * 24) as _)
310 }
311
312 #[corresponds(ASN1_TIME_set)]
314 pub fn from_unix(time: time_t) -> Result<Asn1Time, ErrorStack> {
315 ffi::init();
316
317 unsafe {
318 let handle = cvt_p(ffi::ASN1_TIME_set(ptr::null_mut(), time))?;
319 Ok(Asn1Time::from_ptr(handle))
320 }
321 }
322
323 #[corresponds(ASN1_TIME_set_string)]
325 #[allow(clippy::should_implement_trait)]
326 pub fn from_str(s: &str) -> Result<Asn1Time, ErrorStack> {
327 unsafe {
328 let s = CString::new(s).map_err(ErrorStack::internal_error)?;
329
330 let time = Asn1Time::new()?;
331 cvt(ffi::ASN1_TIME_set_string(time.as_ptr(), s.as_ptr()))?;
332
333 Ok(time)
334 }
335 }
336}
337
338impl PartialEq for Asn1Time {
339 fn eq(&self, other: &Asn1Time) -> bool {
340 self.diff(other)
341 .map(|t| t.days == 0 && t.secs == 0)
342 .unwrap_or(false)
343 }
344}
345
346impl PartialEq<Asn1TimeRef> for Asn1Time {
347 fn eq(&self, other: &Asn1TimeRef) -> bool {
348 self.diff(other)
349 .map(|t| t.days == 0 && t.secs == 0)
350 .unwrap_or(false)
351 }
352}
353
354impl<'a> PartialEq<&'a Asn1TimeRef> for Asn1Time {
355 fn eq(&self, other: &&'a Asn1TimeRef) -> bool {
356 self.diff(other)
357 .map(|t| t.days == 0 && t.secs == 0)
358 .unwrap_or(false)
359 }
360}
361
362impl PartialOrd for Asn1Time {
363 fn partial_cmp(&self, other: &Asn1Time) -> Option<Ordering> {
364 self.compare(other).ok()
365 }
366}
367
368impl PartialOrd<Asn1TimeRef> for Asn1Time {
369 fn partial_cmp(&self, other: &Asn1TimeRef) -> Option<Ordering> {
370 self.compare(other).ok()
371 }
372}
373
374impl<'a> PartialOrd<&'a Asn1TimeRef> for Asn1Time {
375 fn partial_cmp(&self, other: &&'a Asn1TimeRef) -> Option<Ordering> {
376 self.compare(other).ok()
377 }
378}
379
380foreign_type_and_impl_send_sync! {
381 type CType = ffi::ASN1_STRING;
382 fn drop = ffi::ASN1_STRING_free;
383 pub struct Asn1String;
391}
392
393impl Asn1StringRef {
394 #[corresponds(ASN1_STRING_to_UTF8)]
400 pub fn as_utf8(&self) -> Result<OpensslString, ErrorStack> {
401 unsafe {
402 let mut ptr = ptr::null_mut();
403 let len = ffi::ASN1_STRING_to_UTF8(&mut ptr, self.as_ptr());
404 if len < 0 {
405 return Err(ErrorStack::get());
406 }
407
408 Ok(OpensslString::from_ptr(ptr.cast()))
409 }
410 }
411
412 #[corresponds(ASN1_STRING_get0_data)]
419 pub fn as_slice(&self) -> &[u8] {
420 unsafe { slice::from_raw_parts(ASN1_STRING_get0_data(self.as_ptr()), self.len()) }
421 }
422
423 #[corresponds(ASN1_STRING_length)]
425 pub fn len(&self) -> usize {
426 unsafe { ffi::ASN1_STRING_length(self.as_ptr()) as usize }
427 }
428
429 pub fn is_empty(&self) -> bool {
431 self.len() == 0
432 }
433}
434
435impl fmt::Debug for Asn1StringRef {
436 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
437 match self.as_utf8() {
438 Ok(openssl_string) => openssl_string.fmt(fmt),
439 Err(_) => fmt.write_str("error"),
440 }
441 }
442}
443
444foreign_type_and_impl_send_sync! {
445 type CType = ffi::ASN1_INTEGER;
446 fn drop = ffi::ASN1_INTEGER_free;
447
448 pub struct Asn1Integer;
458}
459
460impl Asn1Integer {
461 pub fn from_bn(bn: &BigNumRef) -> Result<Self, ErrorStack> {
469 bn.to_asn1_integer()
470 }
471}
472
473impl Asn1IntegerRef {
474 #[allow(clippy::unnecessary_cast)]
475 #[allow(missing_docs)]
476 #[deprecated(since = "0.10.6", note = "use to_bn instead")]
477 #[must_use]
478 pub fn get(&self) -> i64 {
479 unsafe { crate::ffi::ASN1_INTEGER_get(self.as_ptr()) as i64 }
480 }
481
482 #[corresponds(ASN1_INTEGER_to_BN)]
484 pub fn to_bn(&self) -> Result<BigNum, ErrorStack> {
485 unsafe {
486 cvt_p(crate::ffi::ASN1_INTEGER_to_BN(
487 self.as_ptr(),
488 ptr::null_mut(),
489 ))
490 .map(|p| BigNum::from_ptr(p))
491 }
492 }
493
494 #[corresponds(ASN1_INTEGER_set)]
499 pub fn set(&mut self, value: i32) -> Result<(), ErrorStack> {
500 unsafe {
501 cvt(crate::ffi::ASN1_INTEGER_set(
502 self.as_ptr(),
503 c_long::from(value),
504 ))
505 .map(|_| ())
506 }
507 }
508}
509
510foreign_type_and_impl_send_sync! {
511 type CType = ffi::ASN1_BIT_STRING;
512 fn drop = ffi::ASN1_BIT_STRING_free;
513 pub struct Asn1BitString;
520}
521
522impl Asn1BitStringRef {
523 #[corresponds(ASN1_STRING_get0_data)]
525 #[must_use]
526 pub fn as_slice(&self) -> &[u8] {
527 unsafe {
528 let ptr = ASN1_STRING_get0_data(self.as_ptr().cast());
529 if ptr.is_null() {
530 return &[];
531 }
532 slice::from_raw_parts(ptr, self.len())
533 }
534 }
535
536 #[corresponds(ASN1_STRING_get0_data)]
538 #[must_use]
539 pub fn to_str(&self) -> Option<&str> {
540 str::from_utf8(self.as_slice()).ok()
541 }
542
543 #[corresponds(ASN1_STRING_length)]
545 #[must_use]
546 pub fn len(&self) -> usize {
547 unsafe { ffi::ASN1_STRING_length(self.as_ptr().cast_const()) as usize }
548 }
549
550 #[must_use]
552 pub fn is_empty(&self) -> bool {
553 self.len() == 0
554 }
555}
556
557foreign_type_and_impl_send_sync! {
558 type CType = ffi::ASN1_OBJECT;
559 fn drop = ffi::ASN1_OBJECT_free;
560
561 pub struct Asn1Object;
575}
576
577impl Stackable for Asn1Object {
578 type StackType = ffi::stack_st_ASN1_OBJECT;
579}
580
581impl Asn1Object {
582 #[corresponds(OBJ_txt2obj)]
584 #[allow(clippy::should_implement_trait)]
585 pub fn from_str(txt: &str) -> Result<Asn1Object, ErrorStack> {
586 unsafe {
587 ffi::init();
588 let txt = CString::new(txt).map_err(ErrorStack::internal_error)?;
589 let obj: *mut ffi::ASN1_OBJECT = cvt_p(ffi::OBJ_txt2obj(txt.as_ptr(), 0))?;
590 Ok(Asn1Object::from_ptr(obj))
591 }
592 }
593}
594
595impl Asn1ObjectRef {
596 #[must_use]
598 pub fn nid(&self) -> Nid {
599 unsafe { Nid::from_raw(ffi::OBJ_obj2nid(self.as_ptr())) }
600 }
601}
602
603impl fmt::Display for Asn1ObjectRef {
604 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
605 unsafe {
606 let mut buf = [0u8; 80];
607 let len = ffi::OBJ_obj2txt(
608 buf.as_mut_ptr().cast(),
609 buf.len() as c_int,
610 self.as_ptr(),
611 0,
612 );
613 fmt.write_str(
614 buf.get(..len as usize)
615 .and_then(|s| str::from_utf8(s).ok())
616 .unwrap_or("error"),
617 )
618 }
619 }
620}
621
622impl fmt::Debug for Asn1ObjectRef {
623 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
624 fmt.write_str(self.to_string().as_str())
625 }
626}
627
628use crate::ffi::ASN1_STRING_get0_data;
629
630#[cfg(test)]
631mod tests {
632 use super::*;
633
634 use crate::bn::BigNum;
635 use crate::nid::Nid;
636
637 #[test]
639 fn bn_cvt() {
640 fn roundtrip(bn: BigNum) {
641 let large = Asn1Integer::from_bn(&bn).unwrap();
642 assert_eq!(large.to_bn().unwrap(), bn);
643 }
644
645 roundtrip(BigNum::from_dec_str("1000000000000000000000000000000000").unwrap());
646 roundtrip(-BigNum::from_dec_str("1000000000000000000000000000000000").unwrap());
647 roundtrip(BigNum::from_u32(1234).unwrap());
648 roundtrip(-BigNum::from_u32(1234).unwrap());
649 }
650
651 #[test]
652 fn time_from_str() {
653 Asn1Time::from_str("99991231235959Z").unwrap();
654 }
655
656 #[test]
657 fn time_from_unix() {
658 let t = Asn1Time::from_unix(0).unwrap();
659 assert_eq!("Jan 1 00:00:00 1970 GMT", t.to_string());
660 }
661
662 #[test]
663 fn time_eq() {
664 let a = Asn1Time::from_str("99991231235959Z").unwrap();
665 let b = Asn1Time::from_str("99991231235959Z").unwrap();
666 let c = Asn1Time::from_str("99991231235958Z").unwrap();
667 let a_ref = a.as_ref();
668 let b_ref = b.as_ref();
669 let c_ref = c.as_ref();
670 assert!(a == b);
671 assert!(a != c);
672 assert!(a == b_ref);
673 assert!(a != c_ref);
674 assert!(b_ref == a);
675 assert!(c_ref != a);
676 assert!(a_ref == b_ref);
677 assert!(a_ref != c_ref);
678 }
679
680 #[test]
681 fn time_ord() {
682 let a = Asn1Time::from_str("99991231235959Z").unwrap();
683 let b = Asn1Time::from_str("99991231235959Z").unwrap();
684 let c = Asn1Time::from_str("99991231235958Z").unwrap();
685 let a_ref = a.as_ref();
686 let b_ref = b.as_ref();
687 let c_ref = c.as_ref();
688 assert!(a >= b);
689 assert!(a > c);
690 assert!(b <= a);
691 assert!(c < a);
692
693 assert!(a_ref >= b);
694 assert!(a_ref > c);
695 assert!(b_ref <= a);
696 assert!(c_ref < a);
697
698 assert!(a >= b_ref);
699 assert!(a > c_ref);
700 assert!(b <= a_ref);
701 assert!(c < a_ref);
702
703 assert!(a_ref >= b_ref);
704 assert!(a_ref > c_ref);
705 assert!(b_ref <= a_ref);
706 assert!(c_ref < a_ref);
707 }
708
709 #[test]
710 fn object_from_str() {
711 let object = Asn1Object::from_str("2.16.840.1.101.3.4.2.1").unwrap();
712 assert_eq!(object.nid(), Nid::SHA256);
713 }
714
715 #[test]
716 fn object_from_str_with_invalid_input() {
717 Asn1Object::from_str("NOT AN OID")
718 .map(|object| object.to_string())
719 .expect_err("parsing invalid OID should fail");
720 }
721}