1 /* $OpenBSD: tls13_error.c,v 1.1 2020/01/20 13:10:37 jsing Exp $ */
2 /*
3 * Copyright (c) 2014,2019 Joel Sing <jsing@openbsd.org>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18 #include <errno.h>
19
20 #include "tls13_internal.h"
21
22 void
tls13_error_clear(struct tls13_error * error)23 tls13_error_clear(struct tls13_error *error)
24 {
25 error->code = 0;
26 error->subcode = 0;
27 error->errnum = 0;
28 error->file = NULL;
29 error->line = 0;
30 free(error->msg);
31 error->msg = NULL;
32 }
33
34 static int
tls13_error_vset(struct tls13_error * error,int code,int subcode,int errnum,const char * file,int line,const char * fmt,va_list ap)35 tls13_error_vset(struct tls13_error *error, int code, int subcode, int errnum,
36 const char *file, int line, const char *fmt, va_list ap)
37 {
38 char *errmsg = NULL;
39 int rv = -1;
40
41 tls13_error_clear(error);
42
43 error->code = code;
44 error->subcode = subcode;
45 error->errnum = errnum;
46 error->file = file;
47 error->line = line;
48
49 if (vasprintf(&errmsg, fmt, ap) == -1) {
50 errmsg = NULL;
51 goto err;
52 }
53
54 if (errnum == -1) {
55 error->msg = errmsg;
56 return 0;
57 }
58
59 if (asprintf(&error->msg, "%s: %s", errmsg, strerror(errnum)) == -1) {
60 error->msg = NULL;
61 goto err;
62 }
63 rv = 0;
64
65 err:
66 free(errmsg);
67
68 return rv;
69 }
70
71 int
tls13_error_set(struct tls13_error * error,int code,int subcode,const char * file,int line,const char * fmt,...)72 tls13_error_set(struct tls13_error *error, int code, int subcode,
73 const char *file, int line, const char *fmt, ...)
74 {
75 va_list ap;
76 int errnum, rv;
77
78 errnum = errno;
79
80 va_start(ap, fmt);
81 rv = tls13_error_vset(error, code, subcode, errnum, file, line, fmt, ap);
82 va_end(ap);
83
84 return (rv);
85 }
86
87 int
tls13_error_setx(struct tls13_error * error,int code,int subcode,const char * file,int line,const char * fmt,...)88 tls13_error_setx(struct tls13_error *error, int code, int subcode,
89 const char *file, int line, const char *fmt, ...)
90 {
91 va_list ap;
92 int rv;
93
94 va_start(ap, fmt);
95 rv = tls13_error_vset(error, code, subcode, -1, file, line, fmt, ap);
96 va_end(ap);
97
98 return (rv);
99 }
100