Path: blob/main/crypto/krb5/src/util/support/errors.c
34889 views
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */1/*2* Can't include krb5.h here, or k5-int.h which includes it, because krb5.h3* needs to be generated with error tables, after util/et, which builds after4* this directory.5*/6#include "k5-platform.h"7#include "k5-err.h"8#include "k5-thread.h"9#include "supp-int.h"1011/*12* It would be nice to just use error_message() always. Pity that it's defined13* in a library that depends on this one, and we're not allowed to make14* circular dependencies.15*/16/*17* We really want a rwlock here, since we should hold it while calling the18* function and copying out its results. But I haven't implemented shims for19* rwlock yet.20*/21static k5_mutex_t krb5int_error_info_support_mutex =22K5_MUTEX_PARTIAL_INITIALIZER;23static const char *(KRB5_CALLCONV *fptr)(long); /* = &error_message */2425/* Fallback error message if we cannot allocate a copy of the real one. */26static char *oom_msg = "Out of memory";2728int29krb5int_err_init (void)30{31return k5_mutex_finish_init(&krb5int_error_info_support_mutex);32}33#define initialize() krb5int_call_thread_support_init()34#define lock() k5_mutex_lock(&krb5int_error_info_support_mutex)35#define unlock() k5_mutex_unlock(&krb5int_error_info_support_mutex)3637void38k5_set_error(struct errinfo *ep, long code, const char *fmt, ...)39{40va_list args;4142va_start(args, fmt);43k5_vset_error(ep, code, fmt, args);44va_end(args);45}4647void48k5_vset_error(struct errinfo *ep, long code, const char *fmt, va_list args)49{50char *str;5152k5_clear_error(ep);53ep->code = code;5455if (vasprintf(&str, fmt, args) < 0)56return;57ep->msg = str;58}5960static inline const char *61oom_check(const char *str)62{63return (str == NULL) ? oom_msg : str;64}6566const char *67k5_get_error(struct errinfo *ep, long code)68{69const char *r;70char buf[128];7172if (code == ep->code && ep->msg != NULL)73return oom_check(strdup(ep->msg));7475if (initialize())76return oom_check(strdup(_("Kerberos library initialization failure")));7778lock();79if (fptr == NULL) {80/* Should be rare; fptr should be set whenever libkrb5 is loaded. */81unlock();82return oom_check(strdup(_("Error code translation unavailable")));83}84r = fptr(code);85#ifndef HAVE_COM_ERR_INTL86/* Translate com_err results here if libcom_err won't do it. */87r = _(r);88#endif89if (r == NULL) {90unlock();91snprintf(buf, sizeof(buf), _("error %ld"), code);92return oom_check(strdup(buf));93}9495r = strdup(r);96unlock();97return oom_check(r);98}99100void101k5_free_error(struct errinfo *ep, const char *msg)102{103if (msg != oom_msg)104free((char *)msg);105}106107void108k5_clear_error(struct errinfo *ep)109{110k5_free_error(ep, ep->msg);111ep->msg = NULL;112}113114void115k5_set_error_info_callout_fn(const char *(KRB5_CALLCONV *f)(long))116{117initialize();118lock();119fptr = f;120unlock();121}122123124