summaryrefslogtreecommitdiff
path: root/csharp/IDNA.cs
blob: b527efbe1a74cd96c40bed98e57580e2dedd7495 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/// <summary>
/// Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation, Inc.
/// *
/// Author: Alexander Gnauck AG-Software, mailto:gnauck@ag-software.de
/// *
/// This file is part of GNU Libidn.
/// *
/// This library is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Lesser General Public License
/// as published by the Free Software Foundation; either version 2.1 of
/// the License, or (at your option) any later version.
/// *
/// This library is distributed in the hope that it will be useful, but
/// WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
/// Lesser General Public License for more details.
/// *
/// You should have received a copy of the GNU Lesser General Public
/// License along with this library; if not, write to the Free Software
/// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
/// USA
/// </summary>

using System;
using System.Text;

namespace Gnu.Inet.Encoding
{	
	public class IDNA
	{
		public const string ACE_PREFIX = "xn--";
		
		/// <summary>
        /// Converts a Unicode string to ASCII using the procedure in RFC3490
		/// section 4.1. Unassigned characters are not allowed and STD3 ASCII
		/// rules are enforced. The input string may be a domain name
		/// containing dots.
		/// </summary>
		/// <param name="input">Unicode string.</param>
		/// <returns> Encoded string.</returns>
		public static string ToASCII(string input)
		{
			StringBuilder o = new StringBuilder();
			StringBuilder h = new StringBuilder();
			
			for (int i = 0; i < input.Length; i++)
			{
				char c = input[i];
				if (c == '.' || c == '\u3002' || c == '\uff0e' || c == '\uff61')
				{
					o.Append(ToASCII(h.ToString(), false, true));
                    o.Append('.');
					h = new StringBuilder();
				}
				else
				{
					h.Append(c);
				}
			}
			o.Append(ToASCII(h.ToString(), false, true));
			return o.ToString();
		}
		
		/// <summary>
        /// Converts a Unicode string to ASCII using the procedure in RFC3490
		/// section 4.1. Unassigned characters are not allowed and STD3 ASCII
		/// rules are enforced.
        /// </summary>
		/// <param name="input">Unicode string.</param>
		/// <param name="allowUnassigned">Unassigned characters, allowed or not?</param>
		/// <param name="useSTD3ASCIIRules">STD3 ASCII rules, enforced or not?</param>
		/// <returns> Encoded string.</returns>
		public static string ToASCII(string input, bool allowUnassigned, bool useSTD3ASCIIRules)
		{
			// Step 1: Check if the string contains code points outside
			//         the ASCII range 0..0x7c.
			
			bool nonASCII = false;
			
			for (int i = 0; i < input.Length; i++)
			{
				int c = input[i];
				if (c > 0x7f)
				{
					nonASCII = true;
					break;
				}
			}
			
			// Step 2: Perform the nameprep operation.
			
			if (nonASCII)
			{
				try
				{
					input = Stringprep.NamePrep(input, allowUnassigned);
				}
				catch (StringprepException e)
				{
					// TODO 
					throw new IDNAException(e);
				}
			}
			
			// Step 3: - Verify the absence of non-LDH ASCII code points
			//    (char) 0..0x2c, 0x2e..0x2f, 0x3a..0x40, 0x5b..0x60,
			//    (char) 0x7b..0x7f
			//         - Verify the absence of leading and trailing
			//           hyphen-minus
			
			if (useSTD3ASCIIRules)
			{
				for (int i = 0; i < input.Length; i++)
				{
					int c = input[i];
					if ((c <= 0x2c) || (c >= 0x2e && c <= 0x2f) || (c >= 0x3a && c <= 0x40) || (c >= 0x5b && c <= 0x60) || (c >= 0x7b && c <= 0x7f))
					{
						throw new IDNAException(IDNAException.CONTAINS_NON_LDH);
					}
				}
				
				if (input.StartsWith("-") || input.EndsWith("-"))
				{
					throw new IDNAException(IDNAException.CONTAINS_HYPHEN);
				}
			}
			
			// Step 4: If all code points are inside 0..0x7f, skip to step 8
			
			nonASCII = false;
			
			for (int i = 0; i < input.Length; i++)
			{
				int c = input[i];
				if (c > 0x7f)
				{
					nonASCII = true;
					break;
				}
			}
			
			string output = input;
			
			if (nonASCII)
			{
				
				// Step 5: Verify that the sequence does not begin with the ACE prefix.
				
				if (input.StartsWith(ACE_PREFIX))
				{
					throw new IDNAException(IDNAException.CONTAINS_ACE_PREFIX);
				}
				
				// Step 6: Punycode
				
				try
				{
					output = Punycode.Encode(input);
				}
				catch (PunycodeException e)
				{
					// TODO
					throw new IDNAException(e);
				}
				
				// Step 7: Prepend the ACE prefix.
				
				output = ACE_PREFIX + output;
			}
			
			// Step 8: Check that the length is inside 1..63.
			
			if (output.Length < 1 || output.Length > 63)
			{
				throw new IDNAException(IDNAException.TOO_LONG);
			}
			
			return output;
		}
		
		/// <summary>
        /// Converts an ASCII-encoded string to Unicode. Unassigned
		/// characters are not allowed and STD3 hostnames are enforced. Input
		/// may be domain name containing dots.
		/// </summary>
		/// <param name="input">ASCII input string.</param>
		/// <returns> Unicode string.</returns>
		public static string ToUnicode(string input)
		{
            input = input.ToLower();
			StringBuilder o = new StringBuilder();
			StringBuilder h = new StringBuilder();
			
			for (int i = 0; i < input.Length; i++)
			{
				char c = input[i];
				if (c == '.' || c == '\u3002' || c == '\uff0e' || c == '\uff61')
				{
					o.Append(ToUnicode(h.ToString(), false, true));
					o.Append(c);
					h = new StringBuilder();
				}
				else
				{
					h.Append(c);
				}
			}
			o.Append(ToUnicode(h.ToString(), false, true));
			return o.ToString();
		}
		
		/// <summary>
        /// Converts an ASCII-encoded string to Unicode.		
		/// </summary>
		/// <param name="input">ASCII input string.</param>
		/// <param name="allowUnassigned">Allow unassigned Unicode characters.</param>
		/// <param name="useSTD3ASCIIRules">Check that the output conforms to STD3.</param>
		/// <returns>Unicode string.</returns>
		public static string ToUnicode(string input, bool allowUnassigned, bool useSTD3ASCIIRules)
		{
			string original = input;
			bool nonASCII = false;
			
			// Step 1: If all code points are inside 0..0x7f, skip to step 3.
			
			for (int i = 0; i < input.Length; i++)
			{
				int c = input[i];
				if (c > 0x7f)
				{
					nonASCII = true;
					break;
				}
			}
			
			// Step 2: Perform the Nameprep operation.
			
			if (nonASCII)
			{
				try
				{
					input = Stringprep.NamePrep(input, allowUnassigned);
				}
				catch (StringprepException e)
				{
					// ToUnicode never fails!
					return original;
				}
			}
			
			// Step 3: Verify the sequence starts with the ACE prefix.
			
			if (!input.StartsWith(ACE_PREFIX))
			{
				// ToUnicode never fails!
				return original;
			}
			
			string stored = input;
			
			// Step 4: Remove the ACE prefix.
			
			input = input.Substring(ACE_PREFIX.Length);
			
			// Step 5: Decode using punycode
			
			string output;
			
			try
			{
				output = Punycode.Decode(input);
			}
			catch (PunycodeException e)
			{
				// ToUnicode never fails!
				return original;
			}
			
			// Step 6: Apply toASCII
			
			string ascii;
			
			try
			{
				ascii = ToASCII(output, allowUnassigned, useSTD3ASCIIRules);
			}
			catch (IDNAException e)
			{
				// ToUnicode never fails!
				return original;
			}
			
			// Step 7: Compare case-insensitively.
			
			if (!ascii.ToUpper().Equals(stored.ToUpper()))
			{
				// ToUnicode never fails!
				return original;
			}
			
			// Step 8: Return the result.
			
			return output;
		}
	}
}