/**
 * Userspace daemon which responds to the eCryptfs kernel module's requests
 *
 * Copyright (C) 2004-2006 International Business Machines Corp.
 *   Author(s): Tyler Hicks <tyhicks@ou.edu>
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 */

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <string.h>
#include "../include/ecryptfs.h"

static int ecryptfs_socket = 0;

static void ecryptfsd_exit(int retval)
{
	if (!ecryptfs_socket)
		goto out;
	if (ecryptfs_send_netlink(ecryptfs_socket, NULL,
				  ECRYPTFS_NLMSG_QUIT, 0, 0) < 0) {
		ecryptfs_syslog(LOG_ERR, "Failed to unregister netlink "
				"daemon with the eCryptfs kernel module\n");
	}
	ecryptfs_release_netlink(ecryptfs_socket);
out:
	ecryptfs_syslog(LOG_INFO, "Closing eCryptfs userspace netlink "
			"daemon [%u]\n", getpid());
	exit(retval);
}

void sigterm_handler(int sig)
{
	ecryptfsd_exit(0);
}

int main(int argc, char **argv)
{
	pid_t daemon_pid;
	int rc = 0;

	daemon_pid = fork();
	if (daemon_pid < 0) {
		rc = -errno;
		printf("Failed to create daemon process: %s\n", strerror(errno));
	} else if (!daemon_pid) {
		if (signal(SIGTERM, sigterm_handler)) {
			rc = -ENOTSUP;
			printf("Failed to attach handler to SIGTERM\n");
			goto daemon_out;
		}
		rc = init_netlink_daemon();
		if (rc) {
			syslog(LOG_ERR, "Error initializing netlink daemon; rc = [%d]\n", rc);
			goto daemon_out;
		}
		rc = ecryptfs_init_netlink(&ecryptfs_socket);
		if (rc) {
			syslog(LOG_ERR, "Failed to run netlink daemon\n");
			goto daemon_out;
		}
		rc = ecryptfs_send_netlink(ecryptfs_socket, NULL,
					   ECRYPTFS_NLMSG_HELO, 0, 0);
		if (rc < 0) {
			syslog(LOG_ERR, "Failed to register netlink daemon with the eCryptfs kernel module\n");
			goto daemon_out;
		}
		rc = ecryptfs_run_netlink_daemon(ecryptfs_socket);
daemon_out:
		ecryptfsd_exit(rc);
	}
	return rc;
}
