xref: /freebsd/contrib/libder/libder/libder_error.c (revision 35c0a8c449fd2b7f75029ebed5e10852240f0865)
1 /*-
2  * Copyright (c) 2024 Kyle Evans <kevans@FreeBSD.org>
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  */
6 
7 #include <stdio.h>
8 
9 #include "libder_private.h"
10 
11 #undef libder_set_error
12 
13 static const char libder_error_nodesc[] = "[Description not available]";
14 
15 #define	DESCRIBE(err, msg)	{ LDE_ ## err, msg }
16 static const struct libder_error_desc {
17 	enum libder_error	 desc_error;
18 	const char		*desc_str;
19 } libder_error_descr[] = {
20 	DESCRIBE(NONE,		"No error"),
21 	DESCRIBE(NOMEM,		"Out of memory"),
22 	DESCRIBE(INVAL,		"Invalid parameter"),
23 	DESCRIBE(SHORTHDR,	"Header too short"),
24 	DESCRIBE(BADVARLEN,	"Bad variable length encoding"),
25 	DESCRIBE(LONGLEN,	"Encoded length too large (8 byte max)"),
26 	DESCRIBE(SHORTDATA,	"Payload not available (too short)"),
27 	DESCRIBE(GARBAGE,	"Garbage after encoded data"),
28 	DESCRIBE(STREAMERR,	"Stream error"),
29 	DESCRIBE(TRUNCVARLEN,	"Variable length object truncated"),
30 	DESCRIBE(COALESCE_BADCHILD,	"Bad child encountered when coalescing"),
31 	DESCRIBE(BADOBJECT,	"Payload not valid for object type"),
32 	DESCRIBE(STRICT_EOC,		"Strict: end-of-content violation"),
33 	DESCRIBE(STRICT_TAG,		"Strict: tag violation"),
34 	DESCRIBE(STRICT_PVARLEN,	"Strict: primitive using indefinite length"),
35 	DESCRIBE(STRICT_BOOLEAN,	"Strict: boolean encoded incorrectly"),
36 	DESCRIBE(STRICT_NULL,		"Strict: null encoded incorrectly"),
37 	DESCRIBE(STRICT_PRIMITIVE,	"Strict: type must be primitive"),
38 	DESCRIBE(STRICT_CONSTRUCTED,	"Strict: type must be constructed"),
39 	DESCRIBE(STRICT_BITSTRING,	"Strict: malformed constructed bitstring"),
40 };
41 
42 const char *
libder_get_error(struct libder_ctx * ctx)43 libder_get_error(struct libder_ctx *ctx)
44 {
45 	const struct libder_error_desc *desc;
46 
47 	for (size_t i = 0; i < nitems(libder_error_descr); i++) {
48 		desc = &libder_error_descr[i];
49 
50 		if (desc->desc_error == ctx->error)
51 			return (desc->desc_str);
52 	}
53 
54 	return (libder_error_nodesc);
55 }
56 
57 bool
libder_has_error(struct libder_ctx * ctx)58 libder_has_error(struct libder_ctx *ctx)
59 {
60 
61 	return (ctx->error != 0);
62 }
63 
64 LIBDER_PRIVATE void
libder_set_error(struct libder_ctx * ctx,int error,const char * file,int line)65 libder_set_error(struct libder_ctx *ctx, int error, const char *file, int line)
66 {
67 	ctx->error = error;
68 
69 	if (ctx->verbose >= 2) {
70 		fprintf(stderr, "%s: [%s:%d]: %s (error %d)\n",
71 		    __func__, file, line, libder_get_error(ctx), error);
72 	} else if (ctx->verbose >= 1) {
73 		fprintf(stderr, "%s: %s (error %d)\n", __func__,
74 		    libder_get_error(ctx), error);
75 	}
76 }
77