/* 
   authentication daemon for podfuk-smb

   Copyright (C) Tim Potter 2000
   
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/uio.h>
#include <ctype.h>

#include "tdb.h"
#include "podfuk-smb-auth.h"

static int interactive = 0;

static struct cli_state *client_list = NULL;
static int num_clients = 0;
static int do_sighup = False;

static TDB_CONTEXT *tdb;

/* Client state structure */

struct cli_state {
	struct cli_state *prev, *next;
	int sock;
	int read_buf_len, write_buf_len;
	int finished;
	int write_extra_data;
	struct cli_request request;
	struct cli_response response;
	struct ucred creds;
};

/* Move process into background */

static void become_daemon(void)
{
	int fd;
	int i;
	close(0);
	close(1);
#ifndef __INSURE__
	close(2);
#endif
	if (fork()) {
		_exit(0);
	}

	/* detach from the terminal */
	setsid();

	/* Close fd's 0,1,2. Needed if started by rsh */

	/* try and use up these file descriptors, so silly
	   library routines writing to stdout etc won't cause havoc */

	for (i = 0; i < 3; i++) {
		fd = open("/dev/null", O_RDWR, 0);
		if (fd < 0)
			fd = open("/dev/null", O_WRONLY, 0);
		if (fd < 0 || fd != i) return;
	}
}

/*******************************************************************
 Catch a signal. This should implement the following semantics:

 1) The handler remains installed after being called.
 2) The signal should be blocked during handler execution.
********************************************************************/

static void CatchSignal(int signum,void (*handler)(int ))
{
	struct sigaction act;

	ZERO_STRUCT(act);

	act.sa_handler = handler;

	sigemptyset(&act.sa_mask);
	sigaddset(&act.sa_mask,signum);
	sigaction(signum,&act,NULL);
}

/*******************************************************************
  convert a string to lower case
********************************************************************/
void strlower(char *s)
{
	while (*s) {
		if (isupper(*s)) *s = tolower(*s);
		s++;
	}
}

/*******************************************************************
 Block sigs.
********************************************************************/

static void BlockSignals(int block,int signum)
{
	sigset_t set;

	sigemptyset(&set);
	sigaddset(&set,signum);
	sigprocmask(block?SIG_BLOCK:SIG_UNBLOCK,&set,NULL);
}

static void sighup_handler(int signum)
{
	BlockSignals(True, SIGHUP);
	do_sighup = True;
	BlockSignals(False, SIGHUP);
}

/* Handle the signal by unlinking socket and exiting */

static void termination_handler(int signum)
{
	pstring path;
	
	/* Remove socket file */
	
	snprintf(path, sizeof(path) - 1, "%s/%s", 
		 PODFUK_SOCKET_DIR, PODFUK_SOCKET_NAME);
	path[sizeof(pstring) - 1] = '\0';

	unlink(path);
	
	exit(0);
}

/* Fetch the user credentials for the other end of the socket.  */

static int read_creds(int sock, struct ucred *creds)
{
	struct cmsghdr *cmsg;
	struct msghdr msg;
	struct iovec iov[1];
	int result, value = 1;
	char c;

	union {
		struct cmsghdr cm;
		char control[CMSG_SPACE(sizeof(struct ucred))];
	} cm;

	/* Set up for recvmsg() call */

	msg.msg_control = &cm;
	msg.msg_controllen = sizeof(cm);

	msg.msg_name = NULL;         /* No network address */
	msg.msg_namelen = 0;

	iov[0].iov_base = &c;      /* Read one byte only */
	iov[0].iov_len = 1;

	msg.msg_iov = iov;
	msg.msg_iovlen = 1;

	msg.msg_flags = 0;

	/* Set SO_PASSCRED socket option to receive user credentials */

	result = setsockopt(sock, SOL_SOCKET, SO_PASSCRED,
			    &value, sizeof(int));

	if (result == -1) {
		DEBUG(("could not set socket options\n"));
		goto done;
	}

	/* Call recvmsg() */

	if ((result = recvmsg(sock, &msg, 0)) == -1) {
		DEBUG(("recvmsg failed\n"));
		goto done;
	}

	/* Extract results */

	result = -1;

	if (creds) {
		for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; 
		     cmsg = CMSG_NXTHDR(&msg, cmsg)) {
			
			if (cmsg->cmsg_level == SOL_SOCKET &&
			    cmsg->cmsg_type == SCM_CREDENTIALS) {

				memcpy(creds, CMSG_DATA(cmsg), 
				       sizeof(struct ucred));

				result = 0;
				goto done;
			}
		}
	}

 done:
	return result;
}

/* Create podfuk-smb socket */

static int create_sock(void)
{
	struct sockaddr_un sunaddr;
	struct stat st;
	int sock = -1;
	mode_t old_umask;
	pstring path;
	
	/* Create the socket directory or reuse the existing one */
	
	old_umask = umask(0);
	
	if (lstat(PODFUK_SOCKET_DIR, &st) == -1) {
		
		if (errno == ENOENT) {
			
			/* Create directory */
			
			if (mkdir(PODFUK_SOCKET_DIR, 0755) == -1) {
				fprintf(stderr, 
					"error creating socket directory %s: "
					"%s\n", PODFUK_SOCKET_DIR, 
					strerror(errno));
				goto done;
			}
			
		} else {
			fprintf(stderr, "lstat failed on socket directory "
				"%s: %s\n", PODFUK_SOCKET_DIR, 
				strerror(errno));
			goto done;
		}
		
	} else {
		
		/* Check ownership and permission on existing directory */
		
		if (!S_ISDIR(st.st_mode)) {
			fprintf(stderr, "socket directory %s isn't a "
				"directory\n", PODFUK_SOCKET_DIR);
			goto done;
		}
		
		if ((st.st_uid != 0) || ((st.st_mode & 0777) != 0755)) {
			fprintf(stderr, "invalid permissions on socket "
				"directory %s\n", PODFUK_SOCKET_DIR);
			goto done;
		}
	}
	
	/* Create the socket file */
	
	sock = socket(AF_UNIX, SOCK_STREAM, 0);
	
	if (sock == -1) {
		fprintf(stderr, "error creating socket: %s\n",
			strerror(errno));
		goto done;
	}

	snprintf(path, sizeof(path), "%s/%s", PODFUK_SOCKET_DIR, 
		 PODFUK_SOCKET_NAME);
	
	unlink(path);
	memset(&sunaddr, 0, sizeof(sunaddr));
	sunaddr.sun_family = AF_UNIX;
	strncpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)-1);
	sunaddr.sun_path[sizeof(sunaddr.sun_path) - 1] = '\0';
	
	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
		fprintf(stderr, "bind failed on podfuk-smb socket %s: %s\n",
			path, strerror(errno));
		close(sock);
		sock = -1;
		
		goto done;
	}
	
	if (listen(sock, 5) == -1) {
		fprintf(stderr, "listen failed on podfuk-smb socket %s: %s\n",
			path, strerror(errno));
		close(sock);
		sock = -1;
		
		goto done;
	}
	
 done:
	
	umask(old_umask);
	
	return sock;
}

struct auth_rec {
	fstring workgroup;
	fstring username;
	fstring password;
};

/* Add a token */

static enum auth_result auth_add_token(struct ucred *creds, char *sharename,
				       char *workgroup, char *username, 
				       char *password)
{
	struct auth_rec rec;
	TDB_DATA key, data;
	fstring keystr;
	int result;

	strlower(sharename);
	strlower(workgroup);
	strlower(username);

	DEBUG(("\tadding %s\\%s for share %s\n", workgroup, username, 
	       sharename));

	/* Add to tdb */

	snprintf(keystr, sizeof(keystr) - 1, "UID%d/%s", creds->uid,
		 sharename);

	strncpy(rec.workgroup, workgroup, sizeof(rec.workgroup) - 1);
	rec.workgroup[sizeof(rec.workgroup) - 1] = '\0';

	strncpy(rec.username, username, sizeof(rec.username) - 1);
	rec.username[sizeof(rec.username) - 1] = '\0';

	strncpy(rec.password, password, sizeof(rec.password) - 1);
	rec.password[sizeof(rec.password) - 1] = '\0';

	key.dptr = keystr;
	key.dsize = strlen(keystr) + 1;

	data.dptr = (char *)&rec;
	data.dsize = sizeof(rec);

	fprintf(stderr, ">>> storing key %s\n", key.dptr);

	result = tdb_store(tdb, key, data, TDB_REPLACE);

	return result == -1 ? AUTH_CMD_FAILED : AUTH_CMD_OK;
}

/* Remove a token */

static enum auth_result auth_remove_token(struct ucred *creds, char *sharename)
{
	TDB_DATA key;
	fstring keystr;
	int result;

	strlower(sharename);

	DEBUG(("\tremoving %s\n", sharename));

	/* Remove from tdb */

	snprintf(keystr, sizeof(keystr) - 1, "UID%d/%s", creds->uid,
		 sharename);

	key.dptr = keystr;
	key.dsize = strlen(keystr) + 1;

	DEBUG((">>> key is %s\n", keystr));

	result = tdb_delete(tdb, key);

	DEBUG((">>> result was %s\n", result == -1 ? "FAIL" : "PASS"));

	return (result == -1) ? AUTH_CMD_FAILED : AUTH_CMD_OK;
}

/* Clear tokens for this user */

struct auth_traverse_tokens_data {
	struct ucred *creds;
	struct cli_state *state;
	int user_data;
};

static int auth_clear_tokens_traverse(TDB_CONTEXT *the_tdb, TDB_DATA key,
				      TDB_DATA data, void *user_data)
{
	struct auth_traverse_tokens_data *auth_data =
		(struct auth_traverse_tokens_data *)user_data;
	fstring keystr;

	snprintf(keystr, sizeof(keystr) - 1, "UID%d/", auth_data->creds->uid);

	if (auth_data->user_data ||
	    strncmp(key.dptr, keystr, strlen(keystr)) == 0) {

		/* Remove this key */

		DEBUG(("\tclearing %s\n", key.dptr));
		tdb_delete(tdb, key);
	}

	return 0;
}

static enum auth_result auth_clear_tokens(struct cli_state *state,
					  struct ucred *creds, int clear_all)
{
	struct auth_traverse_tokens_data data;

	/* Security check */

	if (clear_all && (creds->uid != 0 || creds->pid == 0)) {
		return AUTH_CMD_FAILED;
	}

	DEBUG(("\tclearing %stokens\n", clear_all ? "all" : ""));

	/* Traverse list of tokens */

	data.creds = creds;
	data.state = state;
	data.user_data = clear_all;

	tdb_traverse(tdb, auth_clear_tokens_traverse, &data);

	return AUTH_CMD_OK;
}

/* Add a token to the list of tokens to be returned for this request */

static void append_token(struct cli_state *state, uid_t uid, char *uncname, 
			 struct auth_rec *rec)
{
	int extra_data_len = state->response.extra_data_len;
	char *extra_data = state->response.extra_data;
	struct auth_token *token;

	/* Allocate some memory for the token */

	if (!extra_data) {
		extra_data = state->response.extra_data =
			malloc(sizeof(struct auth_token));
	} else {
		extra_data = state->response.extra_data =
			realloc(extra_data, extra_data_len +
				sizeof(struct auth_token));
	}

	/* Copy token */
	
	token = (struct auth_token *)&extra_data[extra_data_len];

	token->uid = uid;

	strlower(rec->workgroup);
	strlower(rec->username);

	memcpy(token->workgroup, rec->workgroup, sizeof(rec->workgroup));
	memcpy(token->username, rec->username, sizeof(rec->username));
	memcpy(token->password, rec->password, sizeof(rec->password));

	memcpy(token->sharename, uncname, sizeof(token->sharename));

	state->response.extra_data_len += sizeof(struct auth_token);
}

/* List tokens for this user */

static int auth_list_tokens_traverse(TDB_CONTEXT *the_tdb, TDB_DATA key,
				     TDB_DATA data, void *user_data)
{
	struct auth_traverse_tokens_data *auth_data =
		(struct auth_traverse_tokens_data *)user_data;
	fstring keystr;

	snprintf(keystr, sizeof(keystr) - 1, "UID%d/", auth_data->creds->uid);

	/* List token if we are listing all (auth_data->user_data == True) 
	   or if the userid matches. */

	if (auth_data->user_data ||
	    strncmp(key.dptr, keystr, strlen(keystr)) == 0) {
		struct auth_rec *rec = (struct auth_rec *)data.dptr;
		char *sep;
		uid_t uid;

		DEBUG(("\treturning %s data %s/%s\n", key.dptr, 
		       rec->workgroup, rec->username));

		/* Append token to reply list */

		sscanf(key.dptr, "UID%d", &uid);

		sep = strchr(key.dptr, '/');

		append_token(auth_data->state, uid, sep + 1, rec);
	}

	return 0;
}

static enum auth_result auth_list_tokens(struct cli_state *state, 
					 struct ucred *creds, int list_all)
{
	struct auth_traverse_tokens_data data;

	/* Security check */

	if (list_all && (creds->uid != 0 || creds->pid == 0)) {
		return AUTH_CMD_FAILED;
	}

	DEBUG(("\tlisting tokens\n"));

	/* Traverse list of tokens */

	data.creds = creds;
	data.state = state;
	data.user_data = list_all;

	tdb_traverse(tdb, auth_list_tokens_traverse, &data);

	return AUTH_CMD_OK;
}

static enum auth_result auth_fetch_token(struct cli_state *state, 
					 struct ucred *creds, 
					 char *servername, char *sharename)
{
	fstring keystr, uncname;
	TDB_DATA key, data;
	
	strlower(servername);
	strlower(sharename);
	
	DEBUG(("\tfetching token %s/%s\n", 
	       servername ? servername : "NULL", 
	       sharename ? sharename : "NULL"));

	/* Look for servername plus sharename in tdb */

	if (servername && sharename) {
			
		snprintf(uncname, sizeof(uncname) - 1, "//%s/%s", servername, 
			 sharename);

		snprintf(keystr, sizeof(keystr) - 1, "UID%d/%s", 
			 state->request.data.fetch_token.uid, uncname);
		
		key.dptr = keystr;
		key.dsize = strlen(keystr) + 1;
		
		data = tdb_fetch(tdb, key);
		
		if (data.dptr != NULL) {
			
			append_token(state, creds->uid, uncname, 
				     (struct auth_rec *)data.dptr);
			free(data.dptr);
			
			DEBUG(("\tfound record for %s\n", uncname));
			
			return AUTH_CMD_OK;
		}
	}

	if (servername) {

		/* Look for //servername in tdb */

		snprintf(keystr, sizeof(keystr) - 1, "UID%d///%s", 
			 state->request.data.fetch_token.uid, servername);
		
		printf(">>> key is %s\n", keystr);
		
		key.dptr = keystr;
		key.dsize = strlen(keystr) + 1;
		
		data = tdb_fetch(tdb, key);
		
		if (data.dptr != NULL) {
			fstring server_unc;

			snprintf(server_unc, sizeof(server_unc) - 1,
				 "//%s", servername);

			append_token(state, creds->uid, server_unc,
				     (struct auth_rec *)data.dptr);
			free(data.dptr);
			
			DEBUG(("\tfound record for %s\n", servername));
			
			return AUTH_CMD_OK;
		}
	}

	/* Look for a default user */

	snprintf(keystr, sizeof(keystr) - 1, "UID%d///",
		 state->request.data.fetch_token.uid);

	key.dptr = keystr;
	key.dsize = strlen(keystr) + 1;

	data = tdb_fetch(tdb, key);

	if (data.dptr) {
		append_token(state, creds->uid, "//",
			     (struct auth_rec *)data.dptr);
		free(data.dptr);

		DEBUG(("\tfound record\n"));

		return AUTH_CMD_OK;
	}

	DEBUG(("\tnot found\n"));

	return AUTH_CMD_FAILED;
}

/* Process a client request */

static void process_request(struct cli_state *state)
{
	/* Free response data - we may be interrupted and receive another
	   command before being able to send this data off. */

	if (state->response.extra_data) {
		free(state->response.extra_data);
	}

	ZERO_STRUCT(state->response);

	state->response.pid = getpid();
	state->response.result = AUTH_CMD_FAILED;

	switch(state->request.command) {

	case AUTH_ADD_TOKEN:

		state->response.result = 
			auth_add_token(
				&state->creds,
				state->request.data.add_token.sharename,
				state->request.data.add_token.workgroup,
				state->request.data.add_token.username,
				state->request.data.add_token.password);

		break;

	case AUTH_REMOVE_TOKEN:

		state->response.result =
			auth_remove_token(
				&state->creds,
				state->request.data.clear_token.sharename);
	       
		break;

	case AUTH_CLEAR_TOKENS:
	case AUTH_CLEAR_ALL_TOKENS:

		state->response.result = 
			auth_clear_tokens(state, &state->creds, 
					  state->request.command == 
					  AUTH_CLEAR_ALL_TOKENS);

		break;

	case AUTH_LIST_TOKENS:
	case AUTH_LIST_ALL_TOKENS:
		
		state->response.result =
			auth_list_tokens(state, &state->creds,
					 state->request.command ==
					 AUTH_LIST_ALL_TOKENS);

		break;

	case AUTH_FETCH_TOKEN:

		state->response.result =
			auth_fetch_token(
				state, &state->creds,
				state->request.data.fetch_token.servername,
				state->request.data.fetch_token.sharename);

		break;

	default:
		DEBUG(("\tunknown command %d\n", state->request.command));
		break;
	}
}

/* Process a complete received packet from a client */

static void process_packet(struct cli_state *state)
{
	/* Process request */
	
	process_request(state);

	/* Update client state */
	
	state->read_buf_len = 0;
	state->write_buf_len = sizeof(struct cli_response);
}

/* Read some data from a client connection */

static void client_read(struct cli_state *state)
{
	int n;
    
	/* Read data */

	n = read(state->sock, state->read_buf_len + (char *)&state->request, 
		 sizeof(state->request) - state->read_buf_len);

	/* Read failed, kill client */
	
	if (n == -1 || n == 0) {

		if (n == -1 ) {
			DEBUG(("read failed on sock %d, pid %d: %s\n",
			       state->sock, state->creds.pid, 
			       strerror(errno)));
		}
		
		state->finished = True;
		return;
	}
	
	/* Update client state */
	
	state->read_buf_len += n;
}

/* Write some data to a client connection */

static void client_write(struct cli_state *state)
{
	char *data;
	int num_written;
	
	/* Write some data */
	
	if (!state->write_extra_data) {

		/* Write response structure */

		data = (char *)&state->response + sizeof(state->response) - 
			state->write_buf_len;

	} else {

		/* Write extra data */

		data = (char *)state->response.extra_data + 
			state->response.extra_data_len -
			state->write_buf_len;
	}

	num_written = write(state->sock, data, state->write_buf_len);
	
	/* Write failed, kill cilent */
	
	if (num_written == -1 || num_written == 0) {
		
		if (num_written == -1) {
			DEBUG(("write failed on sock %d, pid %d: %s\n",
			       state->sock, state->creds.pid, 
			       strerror(errno)));
		}
		
		state->finished = True;

		if (state->response.extra_data) {
			free(state->response.extra_data);
		}

		return;
	}
	
	/* Update client state */
	
	state->write_buf_len -= num_written;

	/* Have we written all data? */
	
	if (state->write_buf_len == 0) {
		
		/* Take care of extra data */
		
		if (state->write_extra_data) {

			if (state->response.extra_data) {
				free(state->response.extra_data);
			}

			state->response.extra_data = NULL;
			state->write_extra_data = False;

		} else if (state->response.extra_data_len > 0) {
			
			/* Start writing extra data */
			
			state->write_buf_len = state->response.extra_data_len;
			state->write_extra_data = True;
		}
	}
}

/* Process a new connection by adding it to the client connection list */

static void new_connection(int accept_sock)
{
	struct sockaddr_un sunaddr;
	struct cli_state *state;
	int len, sock;
	
	/* Accept connection */
	
	len = sizeof(sunaddr);

	if ((sock = accept(accept_sock, (struct sockaddr *)&sunaddr, &len)) 
	    == -1) {
		
		return;
	}
	
	/* Create new connection structure */
	
	if ((state = (struct cli_state *) malloc(sizeof(*state))) == NULL) {
		return;
	}
	
	ZERO_STRUCTP(state);
	state->sock = sock;
	
	/* Fetch credentials */

	if (read_creds(sock, &state->creds) == -1) {
		DEBUG(("could not read creds\n"));
		return;
	}

	DEBUG(("Connect from pid %d, uid %d\n", state->creds.pid, 
	       state->creds.uid));

	/* Add to connection list */
	
	DLIST_ADD(client_list, state);
	num_clients++;
}

/* Remove a client connection from client connection list */

static void remove_client(struct cli_state *state)
{
	/* It's a dead client - hold a funeral */
	
	if (state != NULL) {
		
		/* Close socket */
		
		close(state->sock);
		
		/* We may have some extra data that was not freed if the
		   client was killed unexpectedly */

		if (state->response.extra_data) {
			free(state->response.extra_data);
		}
		
		/* Remove from list and free */
		
		DLIST_REMOVE(client_list, state);
		free(state);
		num_clients--;
	}
}

/* Process incoming clients on accept_sock.  We use a tricky non-blocking,
   non-forking, non-threaded model which allows us to handle many
   simultaneous connections while remaining impervious to many denial of
   service attacks. */

static void process_loop(int accept_sock)
{
	/* We'll be doing this a lot */

	while (1) {
		struct cli_state *state;
		fd_set r_fds, w_fds;
		int maxfd = accept_sock, selret;

		/* Initialise fd lists for select() */

		FD_ZERO(&r_fds);
		FD_ZERO(&w_fds);

		FD_SET(accept_sock, &r_fds);

		/* Set up client readers and writers */

		state = client_list;

		while (state) {

			/* Dispose of client connection if it is marked as 
			   finished */ 

			if (state->finished) {
				struct cli_state *next = state->next;

				remove_client(state);
				state = next;
				continue;
			}

			/* Select requires we know the highest fd used */

			if (state->sock > maxfd) maxfd = state->sock;

			/* Add fd for reading */

			if (state->read_buf_len != sizeof(state->request)) {
				FD_SET(state->sock, &r_fds);
			}

			/* Add fd for writing */

			if (state->write_buf_len) {
				FD_SET(state->sock, &w_fds);
			}

			state = state->next;
		}

		/* Check signal handling things */

		if (do_sighup) {
			do_sighup = False;
		}

		/* Call select */
        
		selret = select(maxfd + 1, &r_fds, &w_fds, NULL, NULL);

		if (selret == 0) continue;

		if ((selret == -1 && errno != EINTR) || selret == 0) {

			/* Select error, something is badly wrong */

			perror("select");
			exit(1);
		}

		/* Create a new connection if accept_sock readable */

		if (selret > 0) {

			if (FD_ISSET(accept_sock, &r_fds)) {
				new_connection(accept_sock);
			}
            
			/* Process activity on client connections */
            
			for (state = client_list; state; state = state->next) {
                
				/* Data available for reading */
                
				if (FD_ISSET(state->sock, &r_fds)) {
                    
					/* Read data */
                    
					client_read(state);
                    
					/* A request packet might be 
					   complete */
                    
					if (state->read_buf_len == 
					    sizeof(state->request)) {
						process_packet(state);
					}
				}
                
				/* Data available for writing */
                
				if (FD_ISSET(state->sock, &w_fds)) {
					client_write(state);
				}
			}
		}
	}
}

#ifdef __INSURE__

#include <dlfcn.h>
extern void pstring_sub(char *s,const char *pattern,const char *insert);

/*******************************************************************
This routine is a trick to immediately catch errors when debugging
with insure. A xterm with a gdb is popped up when insure catches
a error. It is Linux specific.
********************************************************************/
int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
{
	static int (*fn)();
	int ret;
	char pidstr[10];
	pstring cmd = "/usr/X11R6/bin/xterm -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; gdb /proc/%d/exe %d'";

	snprintf(pidstr, sizeof(pidstr) - 1, "%d", getpid());
	pstring_sub(cmd, "%d", pidstr);

	if (!fn) {
		static void *h;
		h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
		fn = dlsym(h, "_Insure_trap_error");
	}

	ret = fn(a1, a2, a3, a4, a5, a6);

	system(cmd);

	return ret;
}
#endif

/*
 * Main program
 */

int main(int argc, char **argv) 
{
	int accept_sock;
	int opt;

	/* Check for root access */

	if(geteuid() != (uid_t)0) {
		printf("%s: must have effective uid of 0 to run\n",
		       argv[0]);
		exit(1);
	}

	/* Command line args */

	while ((opt = getopt(argc, argv, "i")) != EOF) {
		switch (opt) {
		case 'i': 
			interactive = True;
			break;
		default:
			fprintf(stderr, "unknown option %c\n", (char)opt);
			return 1;
		}
	}

	/* Initialisation */

	CatchSignal(SIGINT, termination_handler);      /* Exit on these sigs */
	CatchSignal(SIGQUIT, termination_handler);
	CatchSignal(SIGTERM, termination_handler);

	CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
	CatchSignal(SIGHUP, sighup_handler);

	if ((accept_sock = create_sock()) == -1) {
		fprintf(stderr, "failed to create socket: %s\n",
			strerror(errno));
		return 1;
	}

	tdb = tdb_open(NULL, 0, TDB_INTERNAL, O_RDWR|O_CREAT, 0644);

	if (!tdb) {
		fprintf(stderr, "could not open internal tdb\n");
		return 1;
	}

	/* Process auth requests */

	if (!interactive) become_daemon();

	process_loop(accept_sock);

	return 0;
}
