/**
 * Copyright (C) 2006 International Business Machines
 * Author(s): Michael A. Halcrow <mhalcrow@us.ibm.com>
 *            Stephan Mueller <smueller@chronox.de>
 *            Tyler Hicks <tyhicks@ou.edu>
 *            Michael C. Thompson <mcthomps@us.ibm.com>
 *
 * 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 <fcntl.h>
#include <gcrypt.h>
#include <getopt.h>
#include <keyutils.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "ecryptfs.h"
#include "io.h"

struct ecryptfs_nv_pair {
	const int value;
	const char *name;
};

enum { O_KEY, O_PASSTHROUGH };

#define NUM_REQUIRED_ARGS 3

static void usage()
{
	fprintf(stderr, "\teCryptfs mount helper\n\tusage: "
		"mount -t ecryptfs [lower directory] [ecryptfs mount point]\n"
		"Available options:\n"
		"\tkey=<pki alias>\n"
		"\n\t\tAvailable pki aliases: passphrase\n"
		"\tpassthrough\n"
		"\tplaintext_passthrough\n"
		);
	exit(-EINVAL);
}

/**
 * This function will malloc any argument that is passed in as non-NULL.
 * In the event of a failure, all returned pointers are invalid and no
 * memory is left allocated.
 *
 * returns 0 on success
 */
static int parse_arguments(int argc, char **argv, char **src, char **target,
			   char **options)
{
	int rc = 0;
	char *ptr;
	size_t len;

	if (src)
		*src = NULL;
	if (target)
		*target = NULL;
	if (options)
		*options = NULL;

	if (src) {
		ptr = argv[1];
		len = strlen(ptr) + 1; /* + NULL terminator */
		*src = malloc(len);
		if (!*src) {
			fprintf(stderr, "Unable to allocate source buffer\n");
			rc = -ENOMEM;
			goto out;
		}
		memcpy(*src, ptr, len);
		if ((*src)[len - 1] == '/')
			(*src)[len - 1] = '\0';
	}
	if (target) {
		ptr = argv[2];
		len = strlen(ptr) + 1; /* +  NULL-terminator */
		*target = malloc(len);
		if (!*target) {
			fprintf(stderr, "Unable to allocate target buffer\n");
			rc = -ENOMEM;
			goto out;
		}
		memcpy(*target, ptr, len);
		if ((*target)[len - 1] == '/')
			(*target)[len - 1] = '\0';
	}
	if (options && (argc == NUM_REQUIRED_ARGS)) {
		fprintf(stderr, "Not enough remaining data for options\n");
		return -EINVAL;
	} else if ((options) && (argc > NUM_REQUIRED_ARGS)) {
		int i;

		ptr = NULL;
		for (i = 3; i < (argc-1); i++)
			if (!strcmp("-o", argv[i])) {
				ptr = argv[i+1];
				break;
			}
		if (!ptr) {
			fprintf(stderr, "Unable to find a list of options to "
					"parse, defaulting to interactive "
					"mount\n");
			rc = -ENOENT;
			goto out;
		}
		len = strlen(ptr) + 1; /* + NULL-terminator */
		*options = malloc(len);
		if (!*options){
			fprintf(stderr, "Unable to allocate memory for options "
					"buffer\n");
			rc = -ENOMEM;
			goto out;
		}
		memcpy(*options, ptr, len);
	}
	return 0;
out:
	if (src && *src)
		free(*src);
	if (target && *target)
		free(*target);
	if (options && *options)
		free(*options);
	return rc;
}

static int ecryptfs_generate_mount_flags(char *options, int *flags)
{
	char *opt;
	char *next_opt;
	char *end;
	int num_options = 0;

	end = strchr(options, '\0');
	opt = options;
	while (opt) {
		if ((next_opt = strchr(opt, ',')))
			next_opt++;
		/* the following mount options should be
		 * stripped out from what is passed into the
		 * kernel since these eight options are best
		 * passed as the mount flags rather than
		 * redundantly to the kernel and could
		 * generate spurious warnings depending on the
		 * level of the corresponding cifs vfs kernel
		 * code */
		if (!strncmp(opt, "nosuid", 6))
			*flags |= MS_NOSUID;
		else if (!strncmp(opt, "suid", 4))
			*flags &= ~MS_NOSUID;
		else if (!strncmp(opt, "nodev", 5))
			*flags |= MS_NODEV;
		else if (!strncmp(opt, "dev", 3))
			*flags &= ~MS_NODEV;
		else if (!strncmp(opt, "noexec", 6))
			*flags |= MS_NOEXEC;
		else if (!strncmp(opt, "exec", 4))
			*flags &= ~MS_NOEXEC;
		else if (!strncmp(opt, "ro", 2))
			*flags |= MS_RDONLY;
		else if (!strncmp(opt, "rw", 2))
			*flags &= ~MS_RDONLY;
		else if (!strncmp(opt, "remount", 7))
			*flags |= MS_REMOUNT;
		else {
			opt = next_opt;
			num_options++;
			continue;
		}
		if (!next_opt) {
			if (opt != options)
				end = --opt;
			else
				end = options;
			*end = '\0';
			break;
		}
		memcpy(opt, next_opt, end - next_opt);
		end = end - (next_opt - opt);
		*end = '\0';
	}
	return num_options;
}

char *parameters_to_scrub[] = {
	"key=",
	"cipher=",
	"passthrough",
	"xattr",
	"encrypted_view",
	NULL
};

char *parameters_to_not_scrub[] = {
	"xattr_user",
	NULL
};

static int parameter_should_not_be_scrubbed(char *str) {
	int i;

	for (i = 0; parameters_to_not_scrub[i]; i++)
		if (strstr(str, parameters_to_not_scrub[i]) == str)
			return 1;
	return 0;
}

static int parameter_should_be_scrubbed(char *str)
{
	int i;

	for (i = 0; parameters_to_scrub[i]; i++)
		if (strstr(str, parameters_to_scrub[i]) == str
		    && !parameter_should_not_be_scrubbed(str))
			return 1;
	return 0;
}

/**
 * Remove from the options string known options which should not be passed
 * into the kernel. Any options that are unknown will be passed in.
 * This is to account for options like "rw".
 *
 * Returns zero on success, non-zero otherwise
 */
static int strip_userland_opts(char *options)
{
	char *cur = NULL, *next = NULL;
	char *temp, *temp_end;
	size_t len;
	int used = 0, first = 1;

	/* Allocate temporary buffer */
	len = strlen(options)+1;
	temp = (char*)malloc(len);
	if (!temp) {
		fprintf(stderr, "Can't malloc\n");
		return -1;
	}
	temp_end = temp;
	memset(temp,0,len);

	cur = options;
	while (cur) {
		int opt_len;

		next = strstr(cur, ",");
		if (next) {
			*next='\0';
			next++;
		}
		if (!parameter_should_be_scrubbed(cur)) {
			if (!first) {
				memcpy(temp_end, ",", 1);
				temp_end++;
			}
			opt_len = strlen(cur);
			memcpy(temp_end, cur, opt_len);
			temp_end = temp_end + opt_len;
			used += opt_len;
			first = 0;
		}
		cur = next;
	}
	memcpy(options,temp,len);
	free(temp);
	return 0;
}

static int ecryptfs_do_mount(int argc, char **argv, struct val_node *params)
{
	int rc;
	int flags = 0;
	int num_opts = 0;
	char *src = NULL, *targ = NULL, *opts = NULL, *new_opts = NULL, *temp;
	char *val;

	if ((rc = parse_arguments(argc, argv, &src, &targ, &opts))) {
		fprintf(stderr, "Unable to understand the mount options\n");
		goto out;
	}
	rc = strip_userland_opts(opts);
	if (rc)
		goto out;
	num_opts = ecryptfs_generate_mount_flags(opts, &flags);
	asprintf(&new_opts, "%s", opts);
	printf("Attempting to mount with the following options:\n");
	while (!stack_pop_val(&params, (void *)&val)) {
		if(!val)
			break;
		temp = new_opts;
		printf("  %s\n", val);
		rc = asprintf(&new_opts, "%s,%s", val, temp);
		if (rc == -1) {
			new_opts = NULL;
			rc = -ENOMEM;
			goto out;
		}
		rc = 0;
		free(temp);
	}
	rc = ecryptfs_mount(src, targ, flags, new_opts);
out:
	free(src);
	free(targ);
	free(opts);
	free(new_opts);
	return rc;
}

static int opts_str_contains_option(char *options, char *option)
{
	char *opt;
	char *next_opt;
	char *end;
	int option_len = strlen(option);

	end = strchr(options, '\0');
	opt = options;
	while (opt) {
		if ((next_opt = strchr(opt, ',')))
			next_opt++;
		if (!strncmp(opt, option, option_len))
			return 1;
		else {
			opt = next_opt;
			continue;
		}
		if (!next_opt) {
			if (opt != options)
				end = --opt;
			else
				end = options;
			*end = '\0';
			break;
		}
		memcpy(opt, next_opt, end - next_opt);
		end = end - (next_opt - opt);
		*end = '\0';
	}
	return 0;
}

int main(int argc, char **argv)
{
	uint32_t version;
	char *opts_str;
	struct val_node *head; /* Will contain final mount options */
	struct ecryptfs_ctx ctx;
	int rc;

	rc = mlockall(MCL_FUTURE);
	if (rc) {
		fprintf(stderr, "Exiting. Unable to mlockall address space\n");
		return 0;
	}
	if (argc < NUM_REQUIRED_ARGS) {
		fprintf(stderr, "Insufficient number of arguments\n");
		usage();
		rc = -EINVAL;
		goto out;
	}
	rc = ecryptfs_get_version(&version);
	if (rc) {
		printf("\nUnable to get the version number of the kernel\n");
		printf("module. Please make sure that you have the eCryptfs\n");
		printf("kernel module loaded, you have sysfs mounted, and\n");
		printf("the sysfs mount point is in /etc/mtab. This is\n");
		printf("necessary so that the mount helper knows which \n");
		printf("kernel options are supported.\n\n");
		printf("Make sure that your system is set up to auto-load\n"
		       "your filesystem kernel module on mount.\n\n");
		printf("Enabling passphrase-mode only for now.\n\n");
		version = ECRYPTFS_VERSIONING_PASSPHRASE;
	}
	head = malloc(sizeof(struct val_node));
	memset(head, 0, sizeof(struct val_node));
	memset(&ctx, 0, sizeof(struct ecryptfs_ctx));
	ctx.get_string = &get_string_stdin;
	if ((rc = parse_arguments(argc, argv, NULL, NULL, &opts_str)))
		goto out;
	if (!opts_str_contains_option(opts_str, "remount")) {
		rc = ecryptfs_process_decision_graph(&ctx, &head, version,
						     opts_str);
		if (rc) {
			printf("Error attempting to evaluate mount options; "
			       "rc = [%d]. Try updating/reinstalling your "
			       "ecryptfs-utils package, or submit a bug "
			       "report.\n", rc);
			goto out;
		}
		rc = ecryptfs_do_mount(argc, argv, head);
		if (rc) {
			printf("Error mounting eCryptfs; rc = [%d]; strerr = "
			       "[%s]\n", rc, strerror(-rc));
			if (rc == -ENODEV)
				printf("Try ``modprobe ecryptfs''\n");
		} else
			printf("Mounted eCryptfs\n");
	} else {
		fprintf(stderr, "When are remounting eCryptfs, you need "
			"to pass the mount utility the -i parameter to avoid "
			"calling the mount helper\n");
		rc = -EINVAL;
	}

out:
	munlockall();
	return rc;
}
