/*-
 * Copyright (c) 2004 Robert N. M. Watson
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 OR CONTRIBUTORS 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.
 *
 * [id for your version control system, if any]
 */

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

#include <net/ethernet.h>

#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "ether.h"

#define	TAP_THREAD_NONE		-1	/* Nothing at all. */
#define	TAP_THREAD_CREATED	0	/* Created, not yet active. */
#define	TAP_THREAD_RUNNING	1	/* Up and running. */
#define	TAP_THREAD_DOSTOP	2	/* Stop requested. */
#define	TAP_THREAD_STOPPING	3	/* Thread signalled stopping. */

static int		 tap_fd = -1;
static pthread_t	 tap_thread;
static pthread_mutex_t	 tap_mutex;
static pthread_cond_t	 tap_cond;
static int		 tap_thread_state = TAP_THREAD_NONE;

#define	BUFSIZE	32768
static u_char		 tap_buffer[BUFSIZE];

static void
tap_read(void)
{
	ssize_t len;

	len = read(tap_fd, tap_buffer, BUFSIZE);
	if (len < 0) {
		perror("tap_read read");
		return;
	}

	ether_input(tap_buffer, len);
}

static void *
tap_worker(void *arg)
{

	tap_thread_state = TAP_THREAD_RUNNING;
	assert(pthread_cond_signal(&tap_cond) == 0);

	while (1) {
		tap_read();
		if (tap_thread_state == TAP_THREAD_DOSTOP)
			break;
	}

	tap_thread_state = TAP_THREAD_STOPPING;
	assert(pthread_cond_signal(&tap_cond) == 0);

	return (NULL);
}

int
tap_output(u_char *packet, u_int packetlen)
{

	return (write(tap_fd, packet, packetlen));
}

int
tap_start(const char *interface)
{
	char name[1024];
	int error, fd;

	if (snprintf(name, 1024, "/dev/%s", interface) > 1024) {
		fprintf(stderr, "tap_start: name too long\n");
		errno = EINVAL;
		return (-1);
	}

	fd = open(name, O_RDWR);
	if (fd == -1) {
		error = errno;
		perror("TAP open");
		errno = error;
		return (-1);
	}

	if (pthread_mutex_init(&tap_mutex, NULL) < 0) {
		error = errno;
		perror("pthread_mutex_init");
		close(fd);
		errno = error;
		return (-1);
	}

	if (pthread_cond_init(&tap_cond, NULL) < 0) {
		error = errno;
		perror("pthread_cond_init");
		close(fd);
		(void)pthread_mutex_destroy(&tap_mutex);
		errno = error;
		return (-1);
	}

	tap_fd = fd;

	tap_thread_state = TAP_THREAD_CREATED;
	if (pthread_create(&tap_thread, NULL, tap_worker, NULL) < 0) {
		error = errno;
		perror("pthread_create");
		close(fd);
		(void)pthread_cond_destroy(&tap_cond);
		(void)pthread_mutex_destroy(&tap_mutex);
		errno = errno;
		tap_thread_state = TAP_THREAD_NONE;
		return (-1);
	}

	/*
	 * Wait for thread to be in a non-created state.
	 */
	assert(pthread_mutex_lock(&tap_mutex) == 0);
	while (tap_thread_state == TAP_THREAD_CREATED)
		assert(pthread_cond_wait(&tap_cond, &tap_mutex) == 0);
	assert(pthread_mutex_unlock(&tap_mutex) == 0);

	return (0);
}

void
tap_stop(void)
{

	if (tap_fd == -1)
		return;

	/*
	 * Signal desire for a shutdown.
	 */
	assert(pthread_mutex_lock(&tap_mutex) == 0);
	assert(tap_thread_state == TAP_THREAD_RUNNING);
	tap_thread_state = TAP_THREAD_DOSTOP;
	assert(pthread_cond_signal(&tap_cond) == 0);
	assert(pthread_mutex_unlock(&tap_mutex) == 0);

	/*
	 * Wait for thread to indicate it's moved into the shutdown state,
	 * then join it.
	 */
	assert(pthread_mutex_lock(&tap_mutex) == 0);
	while (tap_thread_state != TAP_THREAD_STOPPING)
		assert(pthread_cond_wait(&tap_cond, &tap_mutex) == 0);
	assert(pthread_mutex_unlock(&tap_mutex) == 0);

	if (pthread_join(tap_thread, NULL) < 0)
		perror("pthread_join tap_thread");

	if (tap_thread_state != TAP_THREAD_NONE &&
	    tap_thread_state != TAP_THREAD_STOPPING)
		fprintf(stderr, "tap_stop: invalid thread state %d",
		    tap_thread_state);
	tap_thread_state = TAP_THREAD_NONE;

	if (pthread_cond_destroy(&tap_cond) < 0)
		perror("pthread_cond_destroy");

	if (pthread_mutex_destroy(&tap_mutex) < 0)
		perror("pthread_mutex_destroy");

	close(tap_fd);
	tap_fd = -1;
}
