/*
Copyright 1990-2001 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/
/*
 * Copyright (c) 1999 Sun Microsystems, Inc.
 * Copyright (c) 1999 Nihon Sun Microsystems K.K.
 * All rights reserved.
 */

/*
 * "$Id: csc_conf_info.c,v 1.1.1.1.2.1 2001/03/15 07:52:16 himi Exp $"
 */

#pragma ident	"@(#)csc_conf_info.c 1.9	00/09/14 SMI"

#include <stddef.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>
#include <dlfcn.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>

#include "csconv.h"
#include "csc_conf_info.h"

#include "trace_message.h"

#define CSC_CONF_FILE		"encoding.norm"

#define CSC_CONF_HOME_DIR	CSC_BASE_DIR_PERSONAL
#define CSC_CONF_SYSTEM_DIR	CSC_BASE_DIR_SYSTEM
#define CSC_CONF_VENDOR_DIR	CSC_BASE_DIR_DEFAULT

#define CSC_ISCOMMENT(addr, rest)		\
		(('#' == *(addr)) ||		\
		 ((1 < (rest)) &&		\
		  ('/' == *(addr)) &&		\
		  ('/' == *((addr) + 1))))
#define CSC_ISEOL(addr, rest)		(('\n' == *(addr)) ||		\
					 ('\0' == *(addr)))
#define CSC_IS_SPACE_TAB(addr, rest)	((' ' == *(addr)) ||		\
					 ('\t' == *(addr)) ||		\
					 ((1 < (rest)) &&		\
					  ('\\' == *((addr) + 0)) &&	\
					  ('\n' == *((addr) + 1))) ||	\
					 ((2 <= (rest)) &&		\
					  ('\\' == *((addr) + 1)) &&	\
					  ('\r' == *((addr) + 2)) &&	\
					  ('\n' == *((addr) + 3))))
#define CSC_IS_SPACE(addr, rest)	((isspace((int)(*(addr)))) ||	\
					 ((2 <= (rest)) &&		\
					  ('\\' == *((addr) + 1)) &&	\
					  ('\n' == *((addr) + 2))) ||	\
					 ((3 <= (rest)) &&		\
					  ('\\' == *((addr) + 1)) &&	\
					  ('\r' == *((addr) + 2)) &&	\
					  ('\n' == *((addr) + 3))))
#define CSC_IS_ANY(ptr, len)		((NULL == (ptr)) || \
					 ((1 == (len)) && ('-' == *(ptr))) || \
					 ((0 == (len))))

#define CSC_IS_PATH_ABS(path)				\
		(('/' == *(path)) ||			\
		 (0 == strncmp((path), "./", 2)) ||	\
		 (0 == strncmp((path), "../", 3)))


#define CSC_SKIP_ONE_CHAR(addr, rest)			\
	if ((1 < (rest))            &&			\
	    ('\\' == *((addr) + 0)) &&			\
	    ('\n' == *((addr) + 1))) {			\
		(rest) -= 2;				\
		(addr) += 2;				\
	} else {					\
		(rest) -= 1;				\
		(addr) += 1;				\
	}

#define CSC_SKIP_TO_EOL(addr, rest)					\
	while ((0 < (rest)) && !CSC_ISEOL((addr), (rest))) {		\
		CSC_SKIP_ONE_CHAR(addr, rest);				\
	}

#define CSC_SKIP_SPACE_TAB(addr, rest)					\
	while ((0 < (rest)) && CSC_IS_SPACE_TAB((addr), (rest))) {	\
		CSC_SKIP_ONE_CHAR(addr, rest);				\
	}

#define CSC_SKIP_SPACE(addr, rest)					\
	while ((0 < (rest)) && CSC_IS_SPACE((addr), (rest))) {		\
		CSC_SKIP_ONE_CHAR(addr, rest);				\
	}

#define CSC_CONF_ONE_ITEM(addr, rest, csc_conf_str)			\
	CSC_SKIP_SPACE_TAB((addr), (rest));				\
	(csc_conf_str)->ptr = addr;					\
	if (CSC_ISCOMMENT((addr), (rest)) ||				\
	    CSC_ISEOL((addr), (rest))) {				\
		(csc_conf_str)->len = 0;				\
	} else {							\
		while ((0 < rest) &&					\
		       !CSC_ISCOMMENT((addr), (rest)) &&		\
		       !CSC_ISEOL((addr), (rest)) &&			\
		       !CSC_IS_SPACE_TAB((addr), (rest))) {		\
			CSC_SKIP_ONE_CHAR(addr, rest);			\
		}							\
		(csc_conf_str)->len = (addr) - (csc_conf_str)->ptr;	\
	}


typedef enum {
	CSC_CONF_NONE,
	CSC_CONF_FIXED,
	CSC_CONF_HOME,
	CSC_CONF_SYSTEM,
	CSC_CONF_VENDOR,
	CSC_CONF_INTERNAL,
} csc_conf_type_t;

struct _csc_conf_file {
	csc_conf_type_t	file_type;		/* cinfoguration file type */
	const char *	file_name;		/* configuration file name */
	const void *	addr;			/* mmap(2)'ed address */
	size_t		len;			/* length */
	const char *	addr_cur;		/* current address */
	const char *	internal;		/* internal */
	int		internal_length;	/* length of internal */
};


static csc_conf_file_t *	csc_conf_open_mmap(csc_conf_file_t *,
						   const char *);
static csc_conf_file_t *	csc_conf_open_real(csc_conf_file_t *);
static void			csc_conf_read_skip(csc_conf_file_t *);



/*
 * mmap(2) a file and setup csc_conf_file_t structure.
 */
static csc_conf_file_t *
csc_conf_open_mmap(csc_conf_file_t * conf_file, const char * path)
{
	int		fd;
	struct stat	st_buf;

	TRACE_MESSAGE('m', ("csc_conf_open_mmap: path=%s\n", path));

	if ((fd = open(path, O_RDONLY, 0)) < 0) {
		return NULL;
	}
	if (0 != fstat(fd, &st_buf)) {
		close(fd);
		return NULL;
	}
	conf_file->addr = mmap(0, st_buf.st_size,
			       PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
	close(fd);

	if (MAP_FAILED == conf_file->addr) {
		return NULL;
	}

	conf_file->len = st_buf.st_size;
	conf_file->addr_cur = conf_file->addr;

	return conf_file;
}


/*
 * real opener of csc_confuration file
 */
static csc_conf_file_t *
csc_conf_open_real(csc_conf_file_t * conf_file)
{
	size_t		len_dir;
	size_t		len_file;
	char		full_path[MAXPATHLEN];
	char *		env_home;

	TRACE_MESSAGE('o', ("csc_conf_open_real: %s\n",
			    (NULL == conf_file->file_name) ? "(nil)" :
			    conf_file->file_name));

	do {
		switch (conf_file->file_type) {
		case CSC_CONF_NONE:
			return NULL;

		case CSC_CONF_FIXED:
			conf_file->file_type = CSC_CONF_INTERNAL;
			strncpy(full_path, conf_file->file_name,
				sizeof (full_path));
			full_path[sizeof (full_path) - 1] = '\0';
			return csc_conf_open_mmap(conf_file, full_path);
			break;

		case CSC_CONF_HOME:
			if ((0 == getpid()) ||
			    (NULL == (env_home = getenv("HOME")))) {
				continue;
			}
			strncpy(full_path, env_home, sizeof (full_path));
			len_dir = strlen(env_home);
			len_file = strlen(CSC_CONF_HOME_DIR);
			strncpy(full_path + len_dir, CSC_CONF_HOME_DIR,
				(sizeof (full_path)) - len_dir);
			full_path[(sizeof (full_path)) - 1] = '\0';
			conf_file->file_type = CSC_CONF_SYSTEM;
			break;

		case CSC_CONF_SYSTEM:
			strcpy(full_path, CSC_CONF_SYSTEM_DIR);
			conf_file->file_type = CSC_CONF_VENDOR;
			break;

		case CSC_CONF_VENDOR:
			strcpy(full_path, CSC_CONF_VENDOR_DIR);
			conf_file->file_type = CSC_CONF_INTERNAL;
			break;

		case CSC_CONF_INTERNAL:
			conf_file->len = conf_file->internal_length;
			conf_file->addr = conf_file->internal;
			conf_file->addr_cur = conf_file->internal;
			conf_file->file_type = CSC_CONF_NONE;

			if (NULL == conf_file->addr) {
				return NULL;
			} else {
				return conf_file;
			}
			break;

		default:
			return NULL;
			break;
		}

		len_dir = strlen(full_path);
		len_file = strlen(conf_file->file_name);
		if ((len_dir + 1) <= (sizeof (full_path))) {
			strncpy(full_path + len_dir,
				conf_file->file_name,
				(sizeof (full_path)) - (len_dir + 1));
			full_path[(sizeof (full_path)) - 1] = '\0';
		}

		if (NULL == csc_conf_open_mmap(conf_file, full_path)) {
			continue;
		} else {
			return conf_file;
		}
	} while (1);
}


csc_conf_file_t *
csc_conf_open(
	const char *	path,
	int		customize,
	const char *	internal,
	int		internal_length)
{
	csc_conf_file_t *	conf_file;

	TRACE_MESSAGE('o', ("csc_conf_open: path=%s\n",
			    (NULL == path) ? path : "(nil)"));

	conf_file = malloc(sizeof (*conf_file));
	if (NULL == conf_file) {
		return NULL;
	}

	conf_file->file_name = ((NULL == path) ? path : strdup(path));
	conf_file->addr = NULL;
	conf_file->len = 0;
	conf_file->addr_cur = NULL;
	conf_file->internal = internal;
	conf_file->internal_length = internal_length;

	if (NULL == path) {
		conf_file->file_type = CSC_CONF_INTERNAL;
	} else if (CSC_IS_PATH_ABS(path)) {
		conf_file->file_type = CSC_CONF_FIXED;
	} else {
		if (0 == customize) {
			conf_file->file_type = CSC_CONF_SYSTEM;
		} else {
			conf_file->file_type = CSC_CONF_HOME;
		}
	}

	return conf_file;
}


static void
csc_conf_read_skip(csc_conf_file_t * conf_file)
{
	const char *	addr;
	int		rest;

	TRACE_MESSAGE('r', ("csc_conf_read_skip\n"));

	addr = conf_file->addr_cur;
	rest = (conf_file->len - (addr - (char *)(conf_file->addr)));

	while (0 < rest) {
		if (CSC_ISCOMMENT(addr, rest)) {
			CSC_SKIP_TO_EOL(addr, rest);
			continue;
		}
		if (CSC_IS_SPACE(addr, rest)) {
			CSC_SKIP_SPACE(addr, rest);
			continue;
		}
		break;
	}

	conf_file->addr_cur = addr;

	return;
}


int
csc_conf_read(
	csc_conf_file_t *	conf_file,
	csc_conf_str_t *	conf_str,
	int			conf_str_num)
{
	const char *	addr;
	int		rest;
	int		i;
	int		num;

	TRACE_MESSAGE('r', ("csc_conf_getline\n"));

	do {
		if (NULL == conf_file->addr) {
			if (NULL == csc_conf_open_real(conf_file)) {
				return 0;
			}
		}
		csc_conf_read_skip(conf_file);

		addr = conf_file->addr_cur;
		rest = (conf_file->len - (addr - (char *)(conf_file->addr)));

		if (rest <= 0) {
			if (conf_file->internal != conf_file->addr) {
				munmap((char *)(conf_file->addr),
				       conf_file->len);
			}
			conf_file->addr = NULL;
			conf_file->len = 0;
			continue;
		}

		for (i = 0, num = 0; i < conf_str_num; i++) {
			CSC_CONF_ONE_ITEM(addr, rest, conf_str + i);
			if (0 != (conf_str + i)->len) {
				num += 1;
			}
		}

		CSC_SKIP_TO_EOL((addr), (rest));

		conf_file->addr_cur = addr;

#if defined(ENABLE_TRACE)
		if (TRACE_P('R')) {
			TRACE_MESSAGE('R', ("csc_conf_read: "));
			for (i = 0; i < num; i++) {
				TRACE_MESSAGE('R',
					      ("\"%.*s\" ",
					       (conf_str + i)->len,
					       (conf_str + i)->ptr));
			}
			TRACE_MESSAGE('R', ("\n"));
		}
#endif /* ENABLE_TRACE */

		return num;
	} while (1);
}


void
csc_conf_close(csc_conf_file_t * conf_file)
{
	TRACE_MESSAGE('c', ("csc_conf_close\n"));

	if (NULL == conf_file) {
		return;
	}
	if ((NULL != conf_file->addr) &&
	    (conf_file->internal != conf_file->addr)) {
		munmap((char *)(conf_file->addr), conf_file->len);
	}
	if (NULL != conf_file->file_name) {
		free((void *)(conf_file->file_name));
	}
	free(conf_file);
	return;
}


int
csc_strcmp(const char * s, const csc_conf_str_t * cs)
{
	int	ret_val;
	int	len;

	ret_val = strncasecmp(s, cs->ptr, cs->len);

	if (0 == ret_val) {
		len = strlen(s);
		if (len == cs->len) {
			return 0;
		} else if (len < cs->len) {
			return -1;
		} else {
			return 1;
		}
	} else {
		return ret_val;
	}
}
