1 module dnslib.aux;
2 
3 import std.conv: to;
4 
5 // ---------------------------------------------------------------------
6 
7 ubyte[] readHexString(const string input)
8 {
9 	if(input.length % 2 != 0)
10 	{
11 		throw new Exception("readHexString input odd length");
12 	}
13 	
14 	bool ubyteOkay(ubyte ub)
15 	{
16 		return (48 <= ub && ub <= 57) || (65 <= ub && ub <= 70) || (97 <= ub && ub <= 102);
17 	}
18 	
19 	ubyte[] output;
20 	output.length = input.length / 2;
21 	uint j = 0;
22 	for (int i = 0; i < input.length; i += 2)
23 	{
24 		ubyte first  = input[i];
25 		ubyte second = input[i+1];
26 
27 		if(!ubyteOkay(first) || !ubyteOkay(second))
28 		{
29 			throw new Exception("readHexString illegal char");
30 		}
31 		
32 		first  = to!ubyte(first >= 97 ? first - 87 : (first >= 65 ? first - 55 : first - 48));
33 		second = to!ubyte(second >= 97 ? second - 87 : (second >= 65 ? second - 55 : second - 48));
34 		
35 		output[j] = to!ubyte(16*first + second);
36 		j++;
37 	}
38 	
39 	assert(2*j == input.length);
40 	assert(1*j == output.length);
41 	
42 	return output;
43 }
44 
45 unittest
46 {
47   const string hexString = "00090a0f0A0F";
48   ubyte[] byteArray = readHexString(hexString);
49   assert(byteArray == [0,9,10,15,10,15]);
50 }
51 
52 // ---------------------------------------------------------------------
53 
54 // Simpel check for legal domain name elements	
55 bool noIllegalCharacters(ref string s)
56 {
57 	if ((s.length == 0) || (s[0] == '-') || (s[$-1] == '-'))
58 	{
59 		return false;
60 	}
61 	
62 	import std.regex;
63 	auto rx = ctRegex!(r"^[0-9a-zA-Z-]{1,64}$");  // Length requirement (64) can be tightened. 
64 
65 	auto capture = matchFirst(s, rx);
66 	return (!capture.empty);  		
67 }
68 
69 unittest
70 {
71 	string s = "";
72 	assert(!noIllegalCharacters(s));
73 
74 	s = "a";
75 	assert( noIllegalCharacters(s));
76 
77 	s = "1";
78 	assert( noIllegalCharacters(s));
79 
80 	s = "-";
81 	assert(!noIllegalCharacters(s));
82 
83 	s = "a-1";
84 	assert( noIllegalCharacters(s));
85 
86 	s = "-a1";
87 	assert(!noIllegalCharacters(s));
88 
89 	s = "0123456789012345678901234567890123456789012345678901234567890123";
90 	assert( noIllegalCharacters(s));
91 
92 	s = "01234567890123456789012345678901234567890123456789012345678901234";
93 	assert(!noIllegalCharacters(s));
94 
95 	s = "yahoo";
96 	assert( noIllegalCharacters(s));
97 
98 	s = "com";
99 	assert( noIllegalCharacters(s));
100 
101 }