#include <sys/param.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#ifdef IPSEC
#include <netipsec/ipsec.h>
#ifndef IPSEC_POLICY_IPSEC
#undef IPSEC
#endif
#endif
#include "ipsec.h"
#ifdef IPSEC
int
ipsecsetup(int af, int fd, const char *policy)
{
char *p0, *p;
int error;
if (policy == NULL || *policy == '\0')
p0 = p = strdup("in entrust; out entrust");
else
p0 = p = strdup(policy);
error = 0;
for (;;) {
p = strtok(p, ";");
if (p == NULL)
break;
while (isspace((unsigned char)*p))
p++;
if (*p == '\0') {
p = NULL;
continue;
}
error = ipsecsetup0(af, fd, p, true);
if (error < 0)
break;
p = NULL;
}
free(p0);
return error;
}
int
ipsecsetup_test(const char *policy)
{
char *p0, *p;
char *buf;
int error;
if (policy == NULL)
return -1;
p0 = p = strdup(policy);
if (p == NULL)
return -1;
error = 0;
for (;;) {
p = strtok(p, ";");
if (p == NULL)
break;
while (isspace((unsigned char)*p))
p++;
if (*p == '\0') {
p = NULL;
continue;
}
buf = ipsec_set_policy(p, (int)strlen(p));
if (buf == NULL) {
error = -1;
break;
}
free(buf);
p = NULL;
}
free(p0);
return error;
}
int
ipsecsetup0(int af, int fd, const char *policy, int commit)
{
int level;
int opt;
char *buf;
int error;
switch (af) {
case AF_INET:
level = IPPROTO_IP;
opt = IP_IPSEC_POLICY;
break;
#ifdef INET6
case AF_INET6:
level = IPPROTO_IPV6;
opt = IPV6_IPSEC_POLICY;
break;
#endif
default:
return -1;
}
buf = ipsec_set_policy(policy, (int)strlen(policy));
if (buf != NULL) {
error = 0;
if (commit && setsockopt(fd, level, opt,
buf, (socklen_t)ipsec_get_policylen(buf)) < 0) {
error = -1;
}
free(buf);
} else
error = -1;
return error;
}
#endif