| 1 |
/* |
| 2 |
* Copyright 2015-2020 the original author or authors |
| 3 |
* |
| 4 |
* This software is licensed under the Apache License, Version 2.0, |
| 5 |
* the GNU Lesser General Public License version 2 or later ("LGPL") |
| 6 |
* and the WTFPL. |
| 7 |
* You may choose either license to govern your use of this software only |
| 8 |
* upon the condition that you accept all of the terms of either |
| 9 |
* the Apache License 2.0, the LGPL 2.1+ or the WTFPL. |
| 10 |
*/ |
| 11 |
package org.minidns.edns; |
| 12 |
|
| 13 |
import java.io.DataOutputStream; |
| 14 |
import java.io.IOException; |
| 15 |
|
| 16 |
import org.minidns.edns.Edns.OptionCode; |
| 17 |
|
| 18 |
public abstract class EdnsOption { |
| 19 |
|
| 20 |
public final int optionCode; |
| 21 |
public final int optionLength; |
| 22 |
|
| 23 |
protected final byte[] optionData; |
| 24 |
|
| 25 |
protected EdnsOption(int optionCode, byte[] optionData) { |
| 26 |
this.optionCode = optionCode; |
| 27 |
this.optionLength = optionData.length; |
| 28 |
this.optionData = optionData; |
| 29 |
} |
| 30 |
|
| 31 |
@SuppressWarnings("this-escape") |
| 32 |
protected EdnsOption(byte[] optionData) { |
| 33 |
this.optionCode = getOptionCode().asInt; |
| 34 |
this.optionLength = optionData.length; |
| 35 |
this.optionData = optionData; |
| 36 |
} |
| 37 |
|
| 38 |
public final void writeToDos(DataOutputStream dos) throws IOException { |
| 39 |
dos.writeShort(optionCode); |
| 40 |
dos.writeShort(optionLength); |
| 41 |
dos.write(optionData); |
| 42 |
} |
| 43 |
|
| 44 |
public abstract OptionCode getOptionCode(); |
| 45 |
|
| 46 |
private String toStringCache; |
| 47 |
|
| 48 |
@Override |
| 49 |
public final String toString() { |
| 50 |
if (toStringCache == null) { |
| 51 |
toStringCache = toStringInternal().toString(); |
| 52 |
} |
| 53 |
return toStringCache; |
| 54 |
} |
| 55 |
|
| 56 |
protected abstract CharSequence toStringInternal(); |
| 57 |
|
| 58 |
private String terminalOutputCache; |
| 59 |
|
| 60 |
public final String asTerminalOutput() { |
| 61 |
if (terminalOutputCache == null) { |
| 62 |
terminalOutputCache = asTerminalOutputInternal().toString(); |
| 63 |
} |
| 64 |
return terminalOutputCache; |
| 65 |
} |
| 66 |
|
| 67 |
protected abstract CharSequence asTerminalOutputInternal(); |
| 68 |
|
| 69 |
public static EdnsOption parse(int intOptionCode, byte[] optionData) { |
| 70 |
OptionCode optionCode = OptionCode.from(intOptionCode); |
| 71 |
EdnsOption res; |
| 72 |
switch (optionCode) { |
| 73 |
case NSID: |
| 74 |
res = new Nsid(optionData); |
| 75 |
break; |
| 76 |
default: |
| 77 |
res = new UnknownEdnsOption(intOptionCode, optionData); |
| 78 |
break; |
| 79 |
} |
| 80 |
return res; |
| 81 |
} |
| 82 |
|
| 83 |
} |