error.c (1900B)
1 /* 2 * Copyright (c) 2020 Paco Esteban <paco@e1e0.net> 3 * Copyright (c) 2020 Tracey Emery <tracey@traceyemery.net> 4 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 19 #include <sys/syslimits.h> 20 21 #include <errno.h> 22 #include <stdio.h> 23 #include <stdlib.h> 24 #include <string.h> 25 26 #include "ssnail_error.h" 27 28 #ifndef nitems 29 #define nitems(_a) (sizeof(_a) / sizeof((_a)[0])) 30 #endif 31 32 const struct ssnail_error * 33 ssnail_error_msg(int code, const char *msg) 34 { 35 static struct ssnail_error error; 36 size_t i; 37 38 for (i = 0; i < nitems(ssnail_errors); i++) { 39 if (code == ssnail_errors[i].code) { 40 error.code = code; 41 error.msg = msg; 42 return &error; 43 } 44 } 45 46 abort(); 47 } 48 49 const struct ssnail_error * 50 ssnail_error_from_errno(const char *prefix) 51 { 52 static struct ssnail_error error; 53 static char error_msg[PATH_MAX + 20]; 54 55 snprintf(error_msg, sizeof(error_msg), "%s: %s", prefix, 56 strerror(errno)); 57 58 error.code = SSNAIL_ERR_ERRNO; 59 error.msg = error_msg; 60 return &error; 61 } 62 63 void * 64 ssnail_error_fprintf(const struct ssnail_error *error) 65 { 66 /* not checking for fprintf errors */ 67 fprintf(stderr, "%s: ERR: %s\n", getprogname(), error->msg); 68 69 return NULL; 70 }