/*
 * The author of this code is John Ioannidis, ji@tla.org,
 * 	(except when noted otherwise).
 *
 * This code was written for BSD/OS in Athens, Greece, in November 1995.
 *
 * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
 * by Angelos D. Keromytis, kermit@forthnet.gr.
 *
 * Copyright (C) 1995, 1996, 1997 by John Ioannidis and Angelos D. Keromytis.
 *	
 * Permission to use, copy, and modify this software without fee
 * is hereby granted, provided that this entire notice is included in
 * all copies of any software which is or includes a copy or
 * modification of this software.
 *
 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTY. IN PARTICULAR, NEITHER AUTHOR MAKES ANY
 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
 * PURPOSE.
 */

#include <sys/param.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/sysctl.h>

#include <net/if.h>
#include <net/route.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <paths.h>

#include <linux/skbuff.h>
#include "radij.h"
#include "ipsec_encap.h"
#include "ipsec_netlink.h"
#include "ipsec_xform.h"
#include "ipsec_ah.h"
#include "ipsec_esp.h"

char buf[2048];

int
main(int argc, char **argv)
{
    struct sockaddr_encap *dst, *msk, *gw;
    struct encap_msghdr *em;
    int sd, proto;

    if (argc != 11)
      fprintf(stderr, "usage: %s isrc isrcmask idst idstmask tproto sport dport raddr spi fespah\n", argv[0]), exit(1);
    
    switch(argv[10][0]) {
    case '0':
	 proto = IPPROTO_AH;
	 break;
    case '1':
	 proto = IPPROTO_ESP;
	 break;
    case '-':
	 proto = 0;
	 break;
    case 'p':
	 proto = atoi(argv[10]+1);
	 break;
    default:
	 fprintf(stderr, "flag fespah: wrong value %s\n", argv[10]);
	 exit(-1);
    }	 


    sd = open("/dev/ipsec", 2);
    if (sd < 0)
      perror("open /dev/ipsec"), exit(1);
	
    memset(buf, 0, EMT_ENABLESPI_FLEN);

    em = (struct encap_msghdr *)(buf);
	
    em->em_msglen = EMT_ENABLESPI_FLEN;
    em->em_version = PFENCAP_VERSION_1;
    em->em_type = EMT_ENABLESPI;
	
    em->em_ena_isrc.s_addr = inet_addr(argv[1]);
    em->em_ena_ismask.s_addr = inet_addr(argv[2]);
    em->em_ena_idst.s_addr = inet_addr(argv[3]);
    em->em_ena_idmask.s_addr = inet_addr(argv[4]);
    
    if (atoi(argv[5]) > 0)
    {
	em->em_ena_protocol = atoi(argv[5]);

	if (atoi(argv[6]) > 0)
	    em->em_ena_sport = atoi(argv[6]);

	if (atoi(argv[7]) > 0)
	    em->em_ena_dport = atoi(argv[7]);
    }

    em->em_ena_dst.s_addr = inet_addr(argv[8]);
    em->em_ena_spi = htonl(strtoul(argv[9], NULL, 16));
    em->em_ena_sproto = proto;
    em->em_ena_flags = 0; /* XXX */

    if (write(sd, (caddr_t) buf, em->em_msglen) < 0)
      perror("write");
    exit(0);
}
