1package de.measite.minidns.util;
2
3import java.io.ByteArrayOutputStream;
4import java.io.DataInputStream;
5import java.io.DataOutputStream;
6import java.io.IOException;
7import java.net.IDN;
8import java.util.HashSet;
9
10public class NameUtil {
11
12 public static int size(String name) {
13 return name.length() + 2;
14 }
15
16 public static byte[] toByteArray(String name) throws IOException {
17 ByteArrayOutputStream baos = new ByteArrayOutputStream(64);
18 DataOutputStream dos = new DataOutputStream(baos);
19 for (String s: name.split("[.\u3002\uFF0E\uFF61]")) {
20 byte[] buffer = IDN.toASCII(s).getBytes();
21 dos.writeByte(buffer.length);
22 dos.write(buffer);
23 }
24 dos.writeByte(0);
25 dos.flush();
26 return baos.toByteArray();
27 }
28
29 public static String parse(DataInputStream dis, byte data[])
30 throws IOException
31 {
32 int c = dis.readUnsignedByte();
33 if ((c & 0xc0) == 0xc0) {
34 c = ((c & 0x3f) << 8) + dis.readUnsignedByte();
35 HashSet<Integer> jumps = new HashSet<Integer>();
36 jumps.add(c);
37 return parse(data, c, jumps);
38 }
39 if (c == 0) {
40 return "";
41 }
42 byte b[] = new byte[c];
43 dis.readFully(b);
44 String s = IDN.toUnicode(new String(b));
45 String t = parse(dis, data);
46 if (t.length() > 0) {
47 s = s + "." + t;
48 }
49 return s;
50 }
51
52 public static String parse(
53 byte data[],
54 int offset,
55 HashSet<Integer> jumps
56 ) {
57 int c = data[offset] & 0xff;
58 if ((c & 0xc0) == 0xc0) {
59 c = ((c & 0x3f) << 8) + data[offset + 1];
60 if (jumps.contains(c)) {
61 throw new IllegalStateException("Cyclic offsets detected.");
62 }
63 jumps.add(c);
64 return parse(data, c, jumps);
65 }
66 if (c == 0) {
67 return "";
68 }
69 String s = new String(data,offset + 1, c);
70 String t = parse(data, offset + 1 + c, jumps);
71 if (t.length() > 0) {
72 s = s + "." + t;
73 }
74 return s;
75 }
76
77}