/* 
   The weblist listproc web interface

   Copyright (C) Andrew Tridgell 1997

   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.
*/

/* screens:

   1) choose mailing list
   2) view user list with wildcards
   3) choose user
   4) enter password for user
   5) change email, name, password, ack, public
*/

#include "weblist.h"

static struct user_info users[MAXUSERS];
static int num_users, num_matched;
static int user_num = -1;
static char **lists;
static time_t open_time;
static int private_interface;

static char *states[] = {"DIGEST","ACK","NOACK","POSTPONE",NULL};
static char *conceal[] = {"NO","YES",NULL};

static char *sanitize(char *s)
{
	int i;
	s = xstrdup(s);

	for (i=0;s[i];i++) {
		if (strchr("\n\r<>\t", s[i])) s[i] = '_';
	}

	trim_string(s," ", " ");

	return s;
}

/* show some pre-formatted text */
static void preformatted(char *s)
{
	printf("<pre>");
	printf("%s", NS(s));
	printf("</pre>\n");
}

/* display a file as html. This is used for various info files
   in the system. Set html to 1 if the file contains html codes */
static int display_file(char *fname, int html)
{
	char *data;

	if (getuid() == 0) return 0;

	data = load_file(fname, NULL, 0);
	if (!data) return 0;

	if (html) {
		printf("%s\n", NS(data));
	} else {
		char *s = quotedup(data);
		preformatted(s);
		free(s);
	}

	free(data);
	return 1;
}	

static void set_buffering(void)
{
	char *buf = (char *)malloc(BUFSIZ + 1024);
	if (buf) {
		setbuf(stdout, buf);
	}
}

static void display_header(void)
{
	char *p;
	static int done;
	if (done) return;
	done = 1;

	display_file("header.html", 1);

	if ((p=cgi_variable("list")) && valid_list(lists, p)) {
		printf("<h3>%s Mailing List</h3><br>\n", p);
	}

	if ((p=getenv("REMOTE_USER"))) {
		printf("<b>Connected as %s</b><p>", p);
	}
}

static void display_footer(void)
{

	printf("<hr>\n");
	printf("<a href=\"%s\">choose list</a>&nbsp;&nbsp;",
	       getenv_null("SCRIPT_NAME"));
	if (valid_list(lists, cgi_variable("list"))) {
		printf("<a href=\"%s?list=%s\">choose user</a>&nbsp;&nbsp;",
		       getenv_null("SCRIPT_NAME"), cgi_variable("list"));
		printf("<a href=\"%s?list=%s;newuser=1\">new user</a><p>",
		       getenv_null("SCRIPT_NAME"), cgi_variable("list"));
	}

	display_file("footer.html", 1);
}

/* panic when something goes wrong */
void fatal(char *why, ...)
{
	display_header();
	printf("FATAL: %s\n", why);
	display_footer();
	exit(0);
}


/* add a audit message */
void audit(char *msg, ...)
{
	va_list ap;
	FILE *f;
	char *p, *l;
	
	va_start(ap, msg);
	
	f = fopen("weblist.log", "a");
	if (f) {
		p=getenv("REMOTE_USER");
		l = cgi_variable("list");
		fprintf(f,"%s %s [%s] [%s] ", timestring(),
			getenv_null("REMOTE_ADDR"),
			p?p:"",
			l?l:"");
		vfprintf(f,msg,ap);
		fprintf(f,"\n");
		fclose(f);
	}

	va_end(ap);
}


static int choose_list(void)
{
	int i;

	display_header();

	printf("
Welcome to the listproc web interface!<p>

You can use this interface to:
<ul>
<li>Find out who is subscribed to a list
<li>Change your subscription details
<li>Unsubscribe from a list
</ul>
<p>

Please choose a mailing list<p>
");

	for (i=0;lists[i];i++) {
		printf("<A HREF=\"%s?list=%s\">%s</A><br>", 
		       getenv_null("SCRIPT_NAME"),lists[i], lists[i]);
	}

	display_file("footer.html", 1);
	exit(0);
}


static int match_user(int i, char *user)
{
	if (!user || !*user) return 0;

	if (!private_interface &&
	    strcmp(users[i].conceal,"NO")) {
		return strcasecmp(user,users[i].email) == 0;
	}

	return (pmatch(user,users[i].email) ||
		pmatch(user,users[i].name));
}

static int choose_user(void)
{
	int i, n=0, m=0;
	int page = 0;
	char *p;
	char *pattern = cgi_variable("user");

	if (!pattern || !*pattern) pattern = "*";

	display_header();

	printf("
<form method=POST>
Please enter a username, or a wildcard pattern<br>
If your subscription is concealed then you must enter your exact email address<p>

Username: 
<input type=text name=user size=50 value=\"%s\"><p>
<input type=hidden name=list value=\"%s\">
", 
	       quotedup(pattern),
	       cgi_variable("list"));

	p = cgi_variable("page");
	if (p) page = atoi(p);

	printf("%d matching users<br>\n", num_matched);
	printf("%d total users<p>\n", num_users);

	printf("<table>\n");

	page = MAX(page, 0);
	page = MIN(page, (num_matched-1)/USERS_PER_PAGE);

	for (i=0;i<num_users && m<USERS_PER_PAGE;i++) {
		if (match_user(i, pattern)) {
			if (n >= page*USERS_PER_PAGE) {
				printf("<tr><td><A HREF=\"%s?list=%s;user=%s;force_match=%d\">%s</A></td><td>%s</td></tr>",
				       getenv_null("SCRIPT_NAME"),
				       cgi_variable("list"),
				       urlquote(users[i].email), 
				       i,
				       quotedup(users[i].email), 
				       users[i].name);
				m++;
			}
			n++;
		}
	}
	printf("</table><p>\n");

	if (page > 0) {
		printf("<a href=\"%s?list=%s;user=%s;page=%d\">prev</a>&nbsp;\n",
		       getenv_null("SCRIPT_NAME"),cgi_variable("list"),
		       urlquote(pattern), page-1);
	}

	if (i < num_users) {
		printf("<A HREF=\"%s?list=%s;user=%s;page=%d\">next</a><br>\n",
		       getenv_null("SCRIPT_NAME"),cgi_variable("list"),
		       urlquote(pattern), page+1);
	}

	printf("</form>");

	display_footer();
	exit(0);
}


static void load_subscribers(void)
{
	FILE *f;
	char *t;
	char fname[1000];
	char line[1000];
	int i = 0;
	struct stat st;
	char *pattern = cgi_variable("user");

	if (!pattern || !*pattern) pattern = "*";

	slprintf(fname,sizeof(fname)-1,"%s/%s/.subscribers", 
		 LIST_DIRECTORY, cgi_variable("list"));
	f = fopen(fname,"r");
	if (!f) {
		fatal(fname);
		return;
	}

	if (fstat(fileno(f), &st) != 0) fatal("fstat failed");

	open_time = st.st_mtime;

	num_users = 0;
	num_matched = 0;

	while (fgets(line,sizeof(line)-1,f)) {
		if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = 0;

		trim_string(line," "," ");

		if (!(t = strtok(line," "))) continue;	       
		users[i].email = xstrdup(t);

		if (!(t = strtok(NULL," "))) continue;
		users[i].state = xstrdup(t);

		if (!(t = strtok(NULL," "))) continue;
		users[i].password = xstrdup(t);

		if (!(t = strtok(NULL," "))) continue;
		users[i].conceal = xstrdup(t);

		t = t + strlen(t)+1;
		users[i].name = xstrdup(t);

		if (match_user(i, pattern)) {
			users[i].matched = 1;
			user_num = i;
			num_matched++;
		}

		i++;

		if (i == MAXUSERS) fatal("too many users");
	}

	fclose(f);

	num_users = i;
}


static void write_subscribers(void)
{
	FILE *f;
	char fnamenew[1000];
	char fname[1000];
	int i = 0;
	struct stat st;

	slprintf(fname,sizeof(fname)-1,"%s/%s/.subscribers", 
		 LIST_DIRECTORY, cgi_variable("list"));
	slprintf(fnamenew,sizeof(fnamenew)-1,"%s.%d", fname, (int)getpid());
	f = fopen(fnamenew,"w");
	if (!f) return;

	for (i=0;i<num_users;i++) {
		if (!users[i].email) continue;

		fprintf(f,"%s %s %s %s %s\n", 
			users[i].email,
			users[i].state,
			users[i].password,
			users[i].conceal,
			users[i].name);
	}

	fclose(f);

	if (stat(fname,&st) || st.st_mtime != open_time) 
		fatal("subscribers file changed");

	rename(fnamenew, fname);

	num_users = i;
}


static int check_password(void)
{
	char *pass = cgi_variable("password");

	if (!pass) return 0;

	return strcmp(pass,users[user_num].password) == 0;
}


static int enter_password(void)
{
	char *p;
	display_header();

	if (cgi_variable("password")) {
		printf("Incorrect password<p>\n");
	}

	printf("
Please enter the password for %s or press the <em>E-Mail Password</em>
button to have your password sent to your subscription address
in an email<br>", 
	       quotedup(users[user_num].email));

	printf("
<form method=POST>
<input type=text name=password size=30 value=\"%s\">
<p>
<input type=submit name=enter value=Enter>
<input type=submit name=mailpass value=\"E-Mail Password\">
<input type=hidden name=list value=\"%s\">
<input type=hidden name=user value=\"%s\">
", 
	       quotedup(cgi_variable("password")),
	       quotedup(cgi_variable("list")),
	       quotedup(cgi_variable("user")));

	if ((p=cgi_variable("force_match"))) {
		printf("<input type=hidden name=force_match value=\"%s\">\n",p);
	}

printf("</form>\n");


	display_footer();
	exit(0);
}


static int user_form(void)
{
	display_header();

	printf("
<form method=POST>
<table>
<tr>
<td>Username:</td>
<td><input type=text size=60 name=username value=\"%s\"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type=text size=60 name=email value=\"%s\"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type=text size=30 name=newpass value=\"%s\"></td>
</tr>
<tr>
<td>Subscription:</td>
<td>%s</td>
</tr>
<tr>
<td>Concealed:</td>
<td>%s</td>
</tr>
</table>
<p>
<input type=submit name=commit value=\"Update\">
<input type=submit name=unsubscribe value=\"Unsubscribe\">
<input type=reset value=Reset>
<input type=hidden name=list value=\"%s\">
<input type=hidden name=user value=\"%s\">
<input type=hidden name=password value=\"%s\">
<input type=hidden name=newuser value=\"%d\">
</form>
", 
	       quotedup(users[user_num].name), 
	       quotedup(users[user_num].email),
	       quotedup(users[user_num].password),
	       sel_list(states, "state", users[user_num].state),
	       sel_list(conceal, "conceal", users[user_num].conceal),
	       quotedup(cgi_variable("list")),
	       quotedup(cgi_variable("user")),
	       quotedup(users[user_num].password),
	       cgi_boolean("newuser", 0));

	display_footer();
	exit(0);
}

static void commit_user(void)
{
	char *email, *username, *newpass, *con, *state;

	if (cgi_boolean("newuser", 0)) {
		user_num = num_users;
		num_users++;
		memset(&users[user_num], 0, sizeof(users[user_num]));
	}

	display_header();

	email = sanitize(cgi_variable("email"));
	username = sanitize(cgi_variable("username"));
	newpass = sanitize(cgi_variable("newpass"));
	con = sanitize(cgi_variable("conceal"));
	state = sanitize(cgi_variable("state"));

	if (!*email || strchr(email,' ')) {
		printf("<b>ERROR: Invalid email address<b><br>\n");
		goto failed;
	}

	if (!*username) {
		printf("<b>ERROR: Invalid username</b><br>\n");
		goto failed;
	}

	if (!*newpass || strchr(newpass,' ')) {
		printf("<b>ERROR: Invalid password</b><br>\n");
		goto failed;
	}

	if (!valid_list(states, state)) {
		printf("<b>ERROR: Invalid subscription state</b><br>\n");
		goto failed;
	}

	if (!valid_list(conceal, con)) {
		printf("<b>ERROR: Invalid conceal state</b><br>\n");
		goto failed;
	}

	if (cgi_boolean("newuser",0)) {
		audit("added user [%s %s %s %s %s]",
		      email, 
		      state, 
		      newpass,
		      con,
		      username);
	} else {
		audit("updated user %s to [%s %s %s %s %s]",
		      users[user_num].email,
		      email, 
		      state, 
		      newpass,
		      con,
		      username);
	}

	users[user_num].email = email;
	users[user_num].name = username;
	users[user_num].password = newpass;
	users[user_num].state = state;
	users[user_num].conceal = con;

	write_subscribers();

	printf("<b>Committed update for user %s</b><p>\n", users[user_num].email);

 failed:
	user_form();
	
	display_footer();
	exit(0);
}


static void unsubscribe_user(void)
{
	display_header();

	printf("<b>Unsubscribed user %s</b><p>\n", users[user_num].email);

	audit("unsubscribed user %s",
	      users[user_num].email);

	users[user_num].email = NULL;
	write_subscribers();

	load_subscribers();

	choose_user();
	
	display_footer();
	exit(0);
}


static void mail_password(void)
{
	int fd;

	display_header();	

	fd = smtp_start_mail(FROM_ADDRESS, users[user_num].email, NULL, NULL, 
			     "Listproc password", 4096);
	if (fd == -1) fatal("can't start mailer");
	smtp_write(fd, "\nThe password for %s is %s\n", 
		   cgi_variable("list"), users[user_num].password);
	smtp_write(fd, "\nYou can now use this password to change your subscription details at http://lists.samba.org/cgi-bin/weblist\n");

	smtp_end_mail(fd);

	printf("The password has been mailed to %s<p>\n",
	       quotedup(users[user_num].email));

	audit("mailed password for user %s",
	      users[user_num].email);

	display_footer();
	exit(0);
}

static void private_subscribe_form(void)
{
	user_num = num_users;
	memset(&users[user_num], 0, sizeof(users[user_num]));
	users[user_num].state = strdup("ACK");
	users[user_num].conceal = strdup("NO");
	users[user_num].password = strdup("XXXXXXXXXXXX");
	slprintf(users[user_num].password, 11, "%0X", (unsigned)random());
	user_form();
}

static void subscribe_form(void)
{
	display_header();	

	printf("To subscribe to the %s list 
<a href=\"mailto:%s\">send an email</a> like this:<p>

<pre>
       To: %s
       Subject: subscribe

       subscribe %s YOUR NAME
</pre>

You should receive a email reply giving you your password a few minutes later<p>
", 
	       cgi_variable("list"),
	       SUBSCRIBE_ADDRESS,
	       SUBSCRIBE_ADDRESS,
	       cgi_variable("list"));

	display_footer();
	exit(0);
}

int main(int argc, char *argv[])
{
	char *s, *p;

	setuid(geteuid());

	set_buffering();
	alarm(300);

	srandom(time(NULL) ^ getpid());

	if (chdir(BASE_DIRECTORY)) exit(1);

	cgi_load_variables(NULL, NULL);

	if (getenv("REMOTE_USER")) private_interface = 1;

	if (private_interface) {
		lists = load_dir_list(LIST_DIRECTORY, NULL);
	} else {
		lists = load_file_list("weblists", NULL);
	}

	if ((s=cgi_variable("sleep"))) {
		sleep(atoi(s));
	}

	if (!valid_list(lists, cgi_variable("list"))) {
		choose_list();
	}

	load_subscribers();

	if (cgi_boolean("newuser",0)) {
		if (private_interface) {
			if (cgi_variable("commit")) {
				commit_user();
			} else {
				private_subscribe_form();
			}
		} else {
			subscribe_form();
		}
	}

	/* allow handling of duplicates */
	if (num_matched > 1 && (p=cgi_variable("force_match"))) {
		user_num = atoi(p);
		if (user_num < num_users && user_num >= 0) {
			num_matched = 1;
		}
	}

	if (num_matched != 1 ||
	    !(s=cgi_variable("user")) ||
	    strcmp(s, users[user_num].email)) {
		choose_user();
	}

	if (cgi_variable("mailpass")) {
		mail_password();
	}

	if (!private_interface &&
	    !check_password()) {
		enter_password();
	}

	if (cgi_variable("unsubscribe")) {
		unsubscribe_user();
	}

	if (!cgi_variable("commit")) {
		user_form();
	}

	commit_user();

	fflush(stdout);

	return 0;
}
