/*
 * Copyright 2002,2003 Christopher SEKIYA <wileyc@rezrov.net>
 *
 * parse_config.c: parse configuration file
 */

#include "tacshell.h"

extern char    *server_secret;
extern char    *user_shell;
extern char    *servers[MAX_SERVERS];

void
parse_config(void)
{
	FILE           *file;
	char           *key;
	char           *value;
	static char     buffer[1024];
	int             index;
	char           *filenames[] =
	{	"/etc/tacshell.conf",
		"/usr/etc/tacshell.conf",
		"/usr/local/etc/tacshell.conf",
		"/usr/pkg/etc/tacshell.conf",
		NULL
	};
	char           *shell;

	for (index = 0; index < MAX_SERVERS; index++)
		servers[index] = NULL;

	index = 0;
	while (filenames[index] != NULL) {
		if ((file = fopen(filenames[index], "r")) != NULL)
			break;
		index++;
	}

	if (file == NULL) {
		fprintf(stderr, "tacshell: tacshell.conf does not exist.\n");
		cleanup();
		exit(-1);
	}
	index = 0;
	while ((fgets(buffer, 1023, file)) != NULL) {
		if (buffer[0] == '#')
			continue;
		key = strtok(buffer, " #\t");
		value = strtok(NULL, "#\n");
		if (value == NULL)
			continue;
		value = (char *) (value + strspn(value, " \t"));

		if (!strcmp(key, "server")) {
			if (index == MAX_SERVERS)
				continue;
			servers[index] = malloc(strlen(value) + 1);
			strcpy(servers[index], value);
			index++;
			continue;
		}
		if (!strcmp(key, "secret")) {
			if (server_secret != NULL)
				free(server_secret);
			server_secret = malloc(strlen(value) + 1);
			strcpy(server_secret, value);
			continue;
		}
		if (!strcmp(key, "shell")) {
			if (user_shell != NULL)
				free(user_shell);
			user_shell = malloc(strlen(value) + 1);
			strcpy(user_shell, value);
			continue;
		}
	}

	fclose(file);

	if ((servers[0] == NULL) || (server_secret == NULL) || (user_shell == NULL)) {
		fprintf(stderr, "tacshell: must specify server parameters in configuration file\n");
		cleanup();
		exit(-1);
	}
	/*
	 * Allow per-user shell override in ~/.tacshell
	 * 
	 * We want to be a bit more paranoid about the user-specified shells --
	 * must be in /etc/shells, must not be suid.
	 */
	snprintf(buffer, (1020 - strlen(getenv("HOME"))), "%s/.tacshell", getenv("HOME"));
	if ((file = fopen(buffer, "r")) == NULL)
		return;

	while ((fgets(buffer, 1023, file)) != NULL) {
		if (buffer[0] == '#')
			continue;
		key = strtok(buffer, " #\t");
		value = strtok(NULL, "#\n");
		if (value == NULL)
			continue;
		value = (char *) (value + strspn(value, " \t"));

		if (!strcmp(key, "shell")) {
			while ((shell = getusershell()) != NULL) {
				if (!strncmp(shell, value, strcspn(value, " ")))
				{
					if (user_shell != NULL)
						free(user_shell);
					user_shell = malloc(strlen(value) + 1);
					strcpy(user_shell, value);
				}
			}

			endusershell();
		}
	}

	fclose(file);
}


syntax highlighted by Code2HTML, v. 0.9.1