/*
 * Copyright (c) 2004	Greg A. Woods <woods@planix.com>
 */

#ident "@(#)librfc2822: :errors.c,v 1.1 2004/08/09 06:13:05 woods Exp "

#include <sys/cdefs.h>

#include <stdio.h>			/* just for FILE in rfc2822.h */
#include <errno.h>
#include <limits.h>
#include <string.h>

#include "rfc2822.h"

int    rfc2822_errno = 0;		/* global parser error code */

/*
 * these must defined in the same order as the numerated errors given in
 * rfc2822.h
 *
 * IMPORTANT:  always update ERRSTR_COUNT to the ordinal number of entries!!!
 */
const char     *rfc2822_errstrs[] = {
	"no error",
	"syntax error",
	"EOF on input",
	"intput/output error",
	"invalid header form",
	"empty header"
};
#define ERRSTR_COUNT	6

#if (ERRSTR_COUNT < NRFC2822ERRORS) /* ((sizeof(rfc2822_errstrs) / sizeof(char *)) < NRFC2822ERRORS) */
# include "ERROR: not enough strings in rfc2822_errstrs!"
#endif

#ifndef NL_TEXTMAX
# define NL_TEXTMAX	BUFSIZ
#endif

const char *
rfc2822_strerror(ecode)
	int ecode;
{
	/*
	 * this storage area must be at least the maximum strlen(strerror())
	 * result, plus the maximum strlen() of rfc2822_errstrs, plus 2
	 */
	static char buf[NL_TEXTMAX * 2];

	if (ecode == RFC2822_FATAL_ERROR) {
		return strerror(errno);
	} else if (ecode == RFC2822_STDIO_EOF) {
		snprintf(buf, sizeof(buf), "%s", rfc2822_errstrs[ecode]);
		return buf;
	} else if (ecode == RFC2822_STDIO_ERROR) {
		snprintf(buf, sizeof(buf), "%s: %s", rfc2822_errstrs[ecode], strerror(errno));
		return buf;
	} else if (ecode < RFC2822_FATAL_ERROR || ecode > NRFC2822ERRORS) {
		snprintf(buf, sizeof(buf), "Unknown librfc2822 error code: %d", ecode);
		return buf;
	}

	return rfc2822_errstrs[ecode];
}
