/* $Id: proc.c,v 1.8 2009/12/16 05:51:12 onoe Exp $ */

/*-
 * Copyright (c) 1998-2001 Atsushi Onoe
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/wait.h>

#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "cue.h"

#ifdef __sgi
#define	vfork()	fork()
#endif

struct procs {
	struct procs *pr_next;
	int pr_pid;
	int pr_efd;
	int pr_running;
	int pr_type;
	int pr_status;
	char *pr_emsg;
	void (*pr_cbfunc)(void *, int);
	void *pr_cbarg;
};

static struct procs *prochead;

int
proc_running(int type)
{
	struct procs *pr;

	for (pr = prochead; pr != NULL; pr = pr->pr_next) {
		if (pr->pr_pid > 0 && pr->pr_running && pr->pr_type == type)
			return 1;
	}
	return 0;
}

static void
proc_clean(int pid)
{
	struct procs *pr, **pp;

	for (pp = &prochead; (pr = *pp) != NULL; pp = &pr->pr_next) {
		if (pr->pr_pid == pid)
			break;
	}
	if (pr != NULL) {
		*pp = pr->pr_next;
		if (pr->pr_efd >= 0)
			close(pr->pr_efd);
		if (pr->pr_emsg)
			free(pr->pr_emsg);
		free(pr);
	}
}

int
proc_getstate(int type, int *status, char *buf, int bufsize)
{
	struct procs *pr;
	sigset_t mask, omask;

	sigemptyset(&mask);
	sigaddset(&mask, SIGCHLD);
	sigprocmask(SIG_BLOCK, &mask, &omask);
	for (;;) {
		for (pr = prochead; pr != NULL; pr = pr->pr_next) {
			if ((type == PTYPE_ANY && !pr->pr_running) ||
			    pr->pr_type == type)
				break;
		}
		if (pr == NULL) {
			sigprocmask(SIG_SETMASK, &omask, NULL);
			return -1;
		}
		if (!pr->pr_running)
			break;
		sigsuspend(&omask);
	}
	if (status)
		*status = pr->pr_status;
	if (buf != NULL) {
		if (pr->pr_emsg)
			strlcpy(buf, pr->pr_emsg, bufsize);
		else
			buf[0] = '\0';
	}
	type = pr->pr_type;
	proc_clean(pr->pr_pid);
	sigprocmask(SIG_SETMASK, &omask, NULL);
	return type;
}

static void
proc_sigchld(int sig)
{
	pid_t pid;
	struct procs *pr;
	int status, n;
	char buf[CHARBLOCK];
	char *p;

	while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
		for (pr = prochead; pr != NULL; pr = pr->pr_next) {
			if (pr->pr_pid == pid && pr->pr_running)
				break;
		}
		if (pr == NULL) {
			/* ignore unknown children */
			continue;
		}
		pr->pr_status = status;
		pr->pr_running = 0;
		if (pr->pr_efd >= 0) {
			if ((n = read(pr->pr_efd, buf, sizeof(buf)-1)) > 0) {
				buf[n] = '\0';
				if ((p = strchr(buf, '\n')) != NULL)
					*p = '\0';
				pr->pr_emsg = strdup(buf);
			}
			close(pr->pr_efd);
			pr->pr_efd = -1;
		}
		if (pr->pr_cbfunc != NULL)
			(*pr->pr_cbfunc)(pr->pr_cbarg, status);
	}
}

int
proc_exec(int type, int infd, int outfd, void (*cbfunc)(void *, int), void *cbarg, const char *fmt, ...)
{
	char buf[CHARBLOCK];
	char *argv[MAXARGS];
	char *s, *d, q;
	int n;
	va_list ap;
	struct procs *pr;
	int pfds[2];
	sigset_t mask, omask;

	va_start(ap, fmt);
	vsprintf(buf, fmt, ap);
	va_end(ap);
	n = strlen(buf);
	if ((pr = malloc(sizeof(*pr) + (n + 1))) == NULL)
		return -1;
	s = buf;
	d = (char *)(pr + 1);
	for (n = 0; n < MAXARGS && *s; n++) {
		if (n == MAXARGS) {
			errno = E2BIG;
			free(pr);
			return -1;
		}
		while (*s && isspace((u_char)*s))
			s++;
		if (*s == '\0')
			break;
		argv[n] = d;
		while (*s && !isspace((u_char)*s)) {
			if (*s == '"' || *s == '\'') {
				for (q = *s++; *s && *s != q; ) {
					if (*s == '\\' && s[1] != '\0')
						s++;
					*d++ = *s++;
				}
				s++;
			} else {
				if (*s == '\\' && s[1] != '\0')
					s++;
				*d++ = *s++;
			}
		}
		*d++ = '\0';
	}
	if (n == 0) {
		errno = EINVAL;
		free(pr);
		return -1;
	}
	argv[n] = NULL;
	pr->pr_type = type;
	if (type != PTYPE_EDITOR) {
		if (pipe(pfds) < 0) {
			free(pr);
			return -1;
		}
		fcntl(pfds[0], F_SETFL, O_NONBLOCK);
		fcntl(pfds[1], F_SETFL, O_NONBLOCK);
		pr->pr_efd = pfds[0];
	} else {
		pr->pr_efd = -1;
		pfds[0] = pfds[1] = -1;
	}
	pr->pr_emsg = NULL;
	pr->pr_running = 1;
	pr->pr_pid = -1;
	pr->pr_cbfunc = cbfunc;
	pr->pr_cbarg = cbarg;
	pr->pr_status = 0;
	signal(SIGCHLD, proc_sigchld);
	sigemptyset(&mask);
	sigaddset(&mask, SIGCHLD);
	sigprocmask(SIG_BLOCK, &mask, &omask);
	pr->pr_next = prochead;
	prochead = pr;
	if ((pr->pr_pid = vfork()) == -1) {
		proc_clean(-1);
		sigprocmask(SIG_SETMASK, &omask, NULL);
		if (pfds[1] != -1)
			close(pfds[1]);
		return -1;
	}
	if (pr->pr_pid == 0) {
		/* XXX: is it ok for vfork? */
		sigprocmask(SIG_SETMASK, &omask, NULL);
		if (type != PTYPE_EDITOR) {
			close(pfds[0]);
			if (pfds[1] != 2) {
				dup2(pfds[1], 2);
				close(pfds[1]);
			}
			if (outfd == -1)
				outfd = open("/dev/null", O_RDWR);
			if (outfd != 1) {
				dup2(outfd, 1);
				close(outfd);
			}
			if (infd == -1)
				dup2(1, 0);
			else {
				if (infd != 0) {
					dup2(infd, 0);
					close(infd);
				}
			}
		}
		execvp(argv[0], argv);
		perror(argv[0]);
		_exit(1);
	}
	if (pfds[1] != -1)
		close(pfds[1]);
	sigprocmask(SIG_SETMASK, &omask, NULL);
	return 0;
}
