/* Copyright (C) 2002 Mitsuru KANDA 
 * 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. Neither the name of the project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/types.h>
#include <asm/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <linux/if.h>
#include <linux/if_arp.h>
#include <linux/if_tunnel.h>
#include <linux/netlink.h>

#include "libnetlink.h"
#include "ll_map.h"

#include "nl.h"

/********** link **********/
/* 
 * link up   : updown = 1 
 * link down : updown = 0
 */
int 
link_set(char *dev, int updown)
{
	__u32 mask = 0;
	__u32 flags = 0;
	struct ifreq ifr;
	int s;
	int err;

        s = socket(PF_INET, SOCK_DGRAM, 0);
        if (s < 0) 
		return -1; /* err */

	if (updown == 1) {
		mask |= IFF_UP;
		flags |= IFF_UP;
	} else if (updown == 0){
		mask |= IFF_UP;
		flags &= ~IFF_UP;
	} else {
		return -1;
	}

	memset(&ifr, 0, sizeof(ifr));
	strcpy(ifr.ifr_name, dev);
	err = ioctl(s, SIOCGIFFLAGS, &ifr);
	if (err) {
		perror("SIOCGIFFLAGS");
		close(s);
		return -1;
	}
	if ((ifr.ifr_flags^flags)&mask) {
		ifr.ifr_flags &= ~mask;
		ifr.ifr_flags |= mask&flags;
		err = ioctl(s, SIOCSIFFLAGS, &ifr);
		if (err) 
			perror("SIOCSIFFLAGS");
	}
	close(s);
	
	return 0;
}

int
link_set_mtu(char *dev, int mtu)
{
	struct ifreq ifr;
	int s;
	int err = -1 ;

	s = socket(PF_INET, SOCK_DGRAM, 0);
	if (s < 0) 
		return -1;

	memset(&ifr, 0, sizeof(ifr));
	strcpy(ifr.ifr_name, dev);
	ifr.ifr_mtu = mtu;
	err = ioctl(s, SIOCSIFMTU, &ifr);
	if (err) 
		perror("SIOCSIFMTU");
	close(s);

	return err;
}
/* link check */
struct nlmsg_list
{
        struct nlmsg_list *next;
        struct nlmsghdr   h;
};

static int 
store_nlmsg(struct sockaddr_nl *who, struct nlmsghdr *n, void *arg)
{
	struct nlmsg_list **linfo = (struct nlmsg_list**)arg;
	struct nlmsg_list *h;
	struct nlmsg_list **lp;

	h = malloc(n->nlmsg_len+sizeof(void*));
	if (h == NULL)
		return -1;

	memcpy(&h->h, n, n->nlmsg_len);
	h->next = NULL;

	for (lp = linfo; *lp; lp = &(*lp)->next) /* NOTHING */;
	*lp = h;

	ll_remember_index(who, n, NULL);
	return 0;
}

static int
link_exist(char *devname, struct nlmsghdr *n)
{
	struct ifinfomsg *ifi = NLMSG_DATA(n);
	struct rtattr *tb[IFLA_MAX+1];
	int len = n->nlmsg_len;
	//unsigned m_flag = 0;

	if (n->nlmsg_type != RTM_NEWLINK && n->nlmsg_type != RTM_DELLINK)
		return 0;

	len -= NLMSG_LENGTH(sizeof(*ifi));
	if (len < 0)
		return -1;
	memset(tb, 0, sizeof(tb));
	parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len);
	if (tb[IFLA_IFNAME] == NULL)  /* BUG! */
		return -1;
	
	if (n->nlmsg_type == RTM_DELLINK)
		return -1; /* deleted! */
	/*
	printf("%d:%s\n", ifi->ifi_index, 
	       tb[IFLA_IFNAME] ? (char*)RTA_DATA(tb[IFLA_IFNAME]) : "<nil>");
	*/
	if (strcmp(devname, (char *)RTA_DATA(tb[IFLA_IFNAME])))
		return -1; /* nothing! */

	return 0;
}

/* flag: IFF_?? */
static int
link_flag_match(struct nlmsghdr *n, int flag)
{
	struct ifinfomsg *ifi = NLMSG_DATA(n);
	struct rtattr *tb[IFLA_MAX+1];
	int len = n->nlmsg_len;
	unsigned m_flags = 0;

	if (n->nlmsg_type != RTM_NEWLINK && n->nlmsg_type != RTM_DELLINK)
		return 0;

	len -= NLMSG_LENGTH(sizeof(*ifi));
	if (len < 0)
		return -1;
	memset(tb, 0, sizeof(tb));
	parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len);
	if (tb[IFLA_IFNAME] == NULL)  /* BUG! */
		return -1;
	
	if (n->nlmsg_type == RTM_DELLINK)
		return -1; /* deleted! */

	m_flags = ifi->ifi_flags;
	m_flags &= ~IFF_RUNNING;
	if (m_flags & flag) {
		m_flags &= ~flag;
		return 0;
	}
	
	return -1;
}

int 
link_check(char *devname, int flag)
{
	struct nlmsg_list *linfo = NULL;
	struct nlmsg_list *l;
	struct rtnl_handle rth;
	int rtn;

	if (rtnl_open(&rth, 0) < 0)
		return -1;

	if (rtnl_wilddump_request(&rth, AF_PACKET, RTM_GETLINK) < 0) {
		perror("Cannot send dump request");
		return -1;
	}

	if (rtnl_dump_filter(&rth, store_nlmsg, &linfo, NULL, NULL) < 0) {
		fprintf(stderr, "Dump terminated\n");
		return -1;
	}

	for (l=linfo; l; l = l->next) {
		rtn = link_exist(devname, &l->h);
		if (!rtn) {
			if (flag)
				rtn = link_flag_match(&l->h, flag);
			return rtn; /* 0 */
		}
	}

	return -1;
}

/********** tunnel *********/
#ifndef IP_DF
#define IP_DF  0x4000 /* Don't Fragment */
#endif

int 
sit_set(char *devname, struct in_addr *in, int add_del)
{
	struct ip_tunnel_parm p;
	struct ifreq ifr;
	const char *mode = "";
	int s;
	int err = -1;

	memset(&p, 0, sizeof(p));
	p.iph.version = 4;
	p.iph.ihl = 5;
	p.iph.frag_off = htons(IP_DF);

	mode = "sit";
	p.iph.protocol = IPPROTO_IPV6; /* sit */
#ifdef SITMODE_GENERIC
	p.sit_mode = SITMODE_GENERIC;
#endif
	if (add_del == 1) { /* add "devname" */
		if (!in)
			return -1;
		p.iph.daddr = in->s_addr; /* remote */
		p.iph.ttl = 64;
	}
	strncpy(p.name, devname, IFNAMSIZ);
	p.iph.protocol = IPPROTO_IPV6;
	if (add_del == 1) {
		strcpy(ifr.ifr_name, "sit0");
	} else if (add_del == 0) {
		strcpy(ifr.ifr_name, p.name);
	} else {
		return -1;
	}
	ifr.ifr_ifru.ifru_data = (void *)&p;
	s = socket(AF_INET, SOCK_DGRAM, 0);
	if (add_del == 1) {
		err = ioctl(s, SIOCADDTUNNEL, &ifr);
	} else if (add_del == 0) {
		err = ioctl(s, SIOCDELTUNNEL, &ifr);
	} else {
		return -1;
	}

	if (err)
		perror("ioctl");

	close(s);

	return err;
}


/********** addr **********/
int
ipaddr6_set(char *devname, struct in6_addr *in6, unsigned char plen, int add_or_del)
{
	struct rtnl_handle rth;
	struct {
		struct nlmsghdr 	n;
		struct ifaddrmsg 	ifa;
		char   			buf[256];
	} req;

	memset(&req, 0, sizeof(req));

	req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
	req.n.nlmsg_flags = NLM_F_REQUEST;
	if (add_or_del == 1)
		req.n.nlmsg_type = RTM_NEWADDR;
	else if (add_or_del == 0)
		req.n.nlmsg_type = RTM_DELADDR;
	else
		return -1;
	req.ifa.ifa_family = AF_INET6;

	addattr_l(&req.n, sizeof(req), IFA_LOCAL, in6, 16);

	if (devname == NULL) {
		fprintf(stderr, "device name required\n");
		return -1;
	}

	addattr_l(&req.n, sizeof(req), IFA_ADDRESS, in6, 16);

	req.ifa.ifa_prefixlen = plen;

	if (rtnl_open(&rth, 0) < 0)
		return -1;

	ll_init_map(&rth);

	if ((req.ifa.ifa_index = ll_name_to_index(devname)) == 0) {
		fprintf(stderr, "device: %s not found\n", devname);
		return -1;
	}

	if (rtnl_talk(&rth, &req.n, 0, 0, NULL, NULL, NULL) < 0)
		return -1;

	return 0;
}

/********** route **********/
/* set/unset default route */
int 
rt6_set(char *devname, struct in6_dst_room *in6dr, int add_del)
{
	struct rtnl_handle rth;
	struct {
		struct nlmsghdr 	n;
		struct rtmsg 		r;
		char   			buf[1024];
	} req;
	int idx;

	if (!devname)
		return -1;

	memset(&req, 0, sizeof(req));

	if (add_del == 1) { /* add route */ 
		req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
		req.n.nlmsg_flags = NLM_F_REQUEST|NLM_F_CREATE|NLM_F_EXCL; /* is NLM_F_EXCL  nessesaly ? */
		req.n.nlmsg_type = RTM_NEWROUTE;
		req.r.rtm_family = AF_INET6;
		req.r.rtm_table = RT_TABLE_MAIN;
		req.r.rtm_protocol = RTPROT_BOOT;
		req.r.rtm_scope = RT_SCOPE_UNIVERSE;
		req.r.rtm_type = RTN_UNICAST;
		req.r.rtm_dst_len = in6dr->plen; /* 0: default route, bit length */
	} else if (add_del == 0) {
		req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
		req.n.nlmsg_flags = NLM_F_REQUEST;
		req.n.nlmsg_type = RTM_DELROUTE;
		req.r.rtm_family = AF_INET6;
		req.r.rtm_table = RT_TABLE_MAIN;
		req.r.rtm_scope = RT_SCOPE_NOWHERE;
		req.r.rtm_dst_len = in6dr->plen;
	} else {
		return -1;
	}

	if (in6dr->plen && in6dr->range)
		addattr_l(&req.n, sizeof(req), RTA_DST, in6dr->range, 16);

	if (in6dr->gw)
		addattr_l(&req.n, sizeof(req), RTA_GATEWAY, in6dr->gw, 16);
		
	if (rtnl_open(&rth, 0) < 0)
		return -1;

	ll_init_map(&rth);
	if ((idx = ll_name_to_index(devname)) == 0) {
		fprintf(stderr, "device: %s not found.\n", devname);
		return -1;
	}
	addattr32(&req.n, sizeof(req), RTA_OIF, idx);
	

	if (rtnl_talk(&rth, &req.n, 0, 0, NULL, NULL, NULL) < 0)
		return -1;

	return 0;
}
