package net.windwards.dnsfrontend.backend;
import com.fasterxml.jackson.core.JsonProcessingException;
import net.windwards.dnsfrontend.api.Configuration;
import net.windwards.dnsfrontend.api.NoSuchDomainException;
import net.windwards.dnsfrontend.api.Protocol;
import net.windwards.dnsfrontend.dialog.JSONProtocol;
import net.windwards.dnsfrontend.dialog.Message;
import net.windwards.dnsfrontend.dialog.ProtocolCodingException;
import net.windwards.dnsfrontend.dialog.Request;
import net.windwards.dnsfrontend.dialog.Update;
import org.xbill.DNS.AAAARecord;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.DClass;
import org.xbill.DNS.Name;
import org.xbill.DNS.Record;
import java.io.IOException;
import java.net.InetAddress;
public class JSONBackendProtocol extends JSONProtocol implements Protocol {
@Override
public byte[] encode(Record record, Configuration configuration)
throws ProtocolCodingException, NoSuchDomainException {
Request request = new Request();
request.name = record.getName().getLabelString(0);
request.moniker = configuration.monikerFromName(new Name(record.getName(), 1));
try {
return this.mapper.writeValueAsBytes(request);
} catch (JsonProcessingException e) {
throw new RuntimeException("Internal error encoding request");
}
}
@Override
public Record decode(byte[] data, Configuration configuration)
throws ProtocolCodingException {
String str = new String(data);
Message message;
Update update;
Name qualified;
InetAddress address;
try {
message = this.mapper.readValue(str, Message.class);
if(!(message instanceof Update)) return null; // For now
update = (Update) message;
qualified = configuration.qualifiedDomainName(update.name, update.moniker);
address = InetAddress.getByName(update.address);
} catch (IOException e) {
throw new ProtocolCodingException(e);
}
int ttl = configuration.getTtl(update.moniker);
Record record;
if("ipv4".equals(update.family)) {
record = new ARecord(qualified, DClass.IN, ttl, address);
} else if ("ipv6".equals(update.family)) {
record = new AAAARecord(qualified, DClass.IN, ttl, address);
} else {
throw new ProtocolCodingException("Can't decode " + new String(data));
}
return record;
}
}