/*
 * libsysactivity
 * http://sourceforge.net/projects/libsysactivity/
 * Copyright (c) 2009-2011 Carlos Olmedo Escobar <carlos.olmedo.e@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <pthread.h>
#include <errno.h>
#include <sys/sysctl.h>
#include <net/if_dl.h>
#include <sys/socket.h>
#include <net/route.h>
#include <stdlib.h>
#include <string.h>
#include <net/if.h>

#include "utils.h"

pthread_key_t buffer_key;
pthread_key_t buffer_size_key;
pthread_key_t size_key;

static void create_keys();
static struct if_msghdr* get_next_if_hdr(size_t* offset, const void* buffer, const size_t size) SA_NONNULL;
static void assign(struct sa_net_interface* __restrict__ dst, struct if_msghdr* if_hdr) SA_NONNULL;

int sa_open_net() {
	pthread_once_t key_once = PTHREAD_ONCE_INIT;
	if (pthread_once(&key_once, create_keys))
		return ENOSYS;

	return 0;
}

int sa_count_net_interfaces(uint16_t* number) {
	if (number == NULL)
		return EINVAL;

	if (sa_reset_net_interfaces())
		return ENOSYS;

	size_t offset = 0;
	void* buffer = pthread_getspecific(buffer_key);
	size_t size = (size_t) pthread_getspecific(size_key);

	*number = 0;
	while (get_next_if_hdr(&offset, buffer, size) != NULL)
		++(*number);

	return 0;
}

int sa_reset_net_interfaces() {
	int mib[6] = { CTL_NET, AF_ROUTE, 0, 0, NET_RT_IFLIST, 0 };
	size_t size = (size_t) pthread_getspecific(size_key);

	do {
		if (sysctl(mib, 6, NULL, &size, NULL, 0) == -1)
			return ENOSYS;

		size_t buffer_size = (size_t) pthread_getspecific(buffer_size_key);
		void* buffer = pthread_getspecific(buffer_key);
		if (buffer_size < size) {
			safe_realloc(&buffer, &size);
			if (pthread_setspecific(buffer_key, buffer))
				return ENOSYS;
			buffer_size = size;
			if (pthread_setspecific(buffer_size_key, (void *) buffer_size))
				return ENOSYS;
			if (buffer == NULL)
				return ENOMEM;
		}

		errno = 0;
		if (sysctl(mib, 6, buffer, &size, NULL, 0) == -1 && errno != ENOMEM)
			return ENOSYS;
	} while (errno == ENOMEM);

	if (pthread_setspecific(size_key, (void *) size))
		return ENOSYS;
	return 0;
}

int sa_get_net_interfaces_ids(char* dst, uint16_t dst_size, uint16_t* written) {
	if (dst == NULL || dst_size == 0 || written == NULL)
		return EINVAL;

	size_t offset = 0;
	void* buffer = pthread_getspecific(buffer_key);
	size_t size = (size_t) pthread_getspecific(size_key);
	*written = 0;

	struct if_msghdr* if_hdr;
	struct sockaddr_dl* sdl;
	uint16_t i = 0;
	for (i = 0; (if_hdr = get_next_if_hdr(&offset, buffer, size)) != NULL; ++i) {
		if (i == dst_size)
			return ENOMEM;

		sdl = (struct sockaddr_dl*) (if_hdr + 1);
		strlcpy(&dst[i * SA_NET_INTERFACE_NAME], sdl->sdl_data, SA_NET_INTERFACE_NAME);
		++(*written);
	}
	return 0;
}

int sa_get_net_interface(char* name, struct sa_net_interface* dst) {
	if (name == NULL || dst == NULL)
		return EINVAL;

	size_t offset = 0;
	void* buffer = pthread_getspecific(buffer_key);
	size_t size = (size_t) pthread_getspecific(size_key);

	struct if_msghdr* if_hdr;
	struct sockaddr_dl* sdl;

	while ((if_hdr = get_next_if_hdr(&offset, buffer, size)) != NULL) {
		sdl = (struct sockaddr_dl*) (if_hdr + 1);
		if (strncmp(sdl->sdl_data, name, sizeof sdl->sdl_nlen) != 0)
			continue;

		assign(dst, if_hdr);
		return 0;
	}
	return ENODEV;
}

int sa_get_net_interfaces(struct sa_net_interface* dst, uint16_t dst_size, uint16_t* written) {
	if (dst == NULL || dst_size == 0 || written == NULL)
		return EINVAL;

	size_t offset = 0;
	void* buffer = pthread_getspecific(buffer_key);
	size_t size = (size_t) pthread_getspecific(size_key);
	*written = 0;

	struct if_msghdr* if_hdr;
	uint16_t i = 0;
	for (i = 0; (if_hdr = get_next_if_hdr(&offset, buffer, size)) != NULL; ++i) {
		if (i == dst_size)
			return ENOMEM;

		assign(&dst[i], if_hdr);
		++(*written);
	}
	return 0;
}

static void create_keys() {
	static short keys_created = 0;
	if (keys_created) {
		return;
	}

	pthread_key_create(&buffer_key, free_keys);
	pthread_key_create(&buffer_size_key, NULL);
	pthread_key_create(&size_key, NULL);

	keys_created = 1;
}

static struct if_msghdr* get_next_if_hdr(size_t* offset, const void* buffer, const size_t size) {
	struct if_msghdr* if_hdr;
	struct rt_msghdr* rt_hdr;
	struct sockaddr_dl* sdl;

	while (*offset < size) {
		rt_hdr = (struct rt_msghdr*) (buffer + *offset);
		if (rt_hdr->rtm_version != RTM_VERSION || rt_hdr->rtm_type != RTM_IFINFO) {
			*offset += rt_hdr->rtm_msglen;
			continue;
		}
		if_hdr = (struct if_msghdr*) (buffer + *offset);
		if (!(if_hdr->ifm_addrs & (1 << RTAX_IFP))) {
			*offset += rt_hdr->rtm_msglen;
			continue;
		}
		sdl = (struct sockaddr_dl*) (if_hdr + 1);
		if (sdl == NULL || sdl->sdl_family != AF_LINK) {
			*offset += rt_hdr->rtm_msglen;
			continue;
		}

		*offset += rt_hdr->rtm_msglen;
		return if_hdr;
	}
	return NULL;
}

static void assign(struct sa_net_interface* __restrict__ dst, struct if_msghdr* if_hdr) {
	struct sockaddr_dl* sdl = (struct sockaddr_dl*) (if_hdr + 1);
	struct if_data* if_data = &if_hdr->ifm_data;

	strlcpy(dst->name, sdl->sdl_data, sizeof dst->name);
	dst->received_bytes = if_data->ifi_ibytes;
	dst->received_packets = if_data->ifi_ipackets;
	dst->received_errors = if_data->ifi_ierrors;
	dst->received_drop = if_data->ifi_iqdrops;
	dst->received_multicast = if_data->ifi_imcasts;
	dst->sent_bytes = if_data->ifi_obytes;
	dst->sent_packets = if_data->ifi_opackets;
	dst->sent_errors = if_data->ifi_oerrors;
	dst->sent_multicast = if_data->ifi_omcasts;
}
