forked from smiley22/S22.Imap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtil.cs
375 lines (359 loc) · 13.5 KB
/
Util.cs
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace S22.Imap {
/// <summary>
/// A static utility class containing methods for decoding encoded
/// non-ASCII data as is often used in mail messages as well as
/// extension methods for some classes of the base class library.
/// </summary>
internal static class Util {
/// <summary>
/// Returns a copy of the string enclosed in double-quotes and with escaped
/// CRLF, back-slash and double-quote characters (as is expected by some
/// commands of the IMAP protocol).
/// </summary>
/// <param name="value">Extends the System.String class</param>
/// <returns>A copy of the string enclosed in double-quotes and properly
/// escaped as is required by the IMAP protocol.</returns>
internal static string QuoteString(this string value) {
return "\"" + value
.Replace("\\", "\\\\")
.Replace("\r", "\\r")
.Replace("\n", "\\n")
.Replace("\"", "\\\"") + "\"";
}
/// <summary>
/// Returns true if the string contains only ASCII characters.
/// </summary>
/// <param name="s">Extension method for the String class.</param>
/// <returns>Returns true if the string contains only ASCII characters,
/// otherwise false is returned.</returns>
internal static bool IsASCII(this string s) {
return s.All(c => c < 127);
}
/// <summary>
/// Splits a string into chunks of the specified number of
/// characters.
/// </summary>
/// <param name="str">Extension method for the String class.</param>
/// <param name="characters">The length of a chunk, measured in
/// characters.</param>
/// <returns>An array of string chunks</returns>
internal static string[] ToChunks(this string str, int characters) {
List<string> list = new List<string>();
while (str.Length > 0) {
int length = str.Length > characters ? characters :
str.Length;
string t = str.Substring(0, length);
str = str.Remove(0, length);
list.Add(t);
}
return list.ToArray();
}
/// <summary>
/// Returns a value indicating whether the specified string occurs within
/// this string. A parameter specifies the type of search to use for the
/// specified string.
/// </summary>
/// <param name="str">Extension method for the String class.</param>
/// <param name="value">The string to seek.</param>
/// <param name="comparer">One of the enumeration values that specifies
/// the rules for the search.</param>
/// <returns>true if the value parameter occurs within this string, or
/// if value is the empty string (""); otherwise, false.</returns>
/// <exception cref="ArgumentNullException">Thrown if the value
/// parameter is null.</exception>
internal static bool Contains(this string str, string value,
StringComparison comparer) {
return str.IndexOf(value, comparer) >= 0;
}
/// <summary>
/// Raises the event. Ensures the event is only raised, if it is not null.
/// </summary>
/// <typeparam name="T">Extends System.EventHandler class</typeparam>
/// <param name="event">Extends System.EventHandler class</param>
/// <param name="sender">The sender of the event</param>
/// <param name="args">The event arguments associated with this event</param>
internal static void Raise<T>(this EventHandler<T> @event, object sender, T args)
where T : EventArgs {
if (@event == null)
return;
@event(sender, args);
}
/// <summary>
/// Throws an ArgumentNullException if the given data item is null.
/// </summary>
/// <param name="data">The item to check for nullity.</param>
/// <param name="name">The name to use when throwing an
/// exception, if necessary</param>
/// <remarks>Courtesy of Jon Skeet.</remarks>
internal static void ThrowIfNull<T>(this T data, string name)
where T : class {
if (data == null)
throw new ArgumentNullException(name);
}
/// <summary>
/// Throws an ArgumentNullException if the given data item is null.
/// </summary>
/// <param name="data">The item to check for nullity.</param>
/// <remarks>Courtesy of Jon Skeet.</remarks>
internal static void ThrowIfNull<T>(this T data)
where T : class {
if (data == null)
throw new ArgumentNullException();
}
/// <summary>
/// Reads an unsigned short value from the underlying stream, optionally
/// using big endian byte ordering.
/// </summary>
/// <param name="reader">Extension method for BinaryReader.</param>
/// <param name="bigEndian">Set to true to interpret the short value
/// as big endian value.</param>
/// <returns>The 16-byte unsigned short value read from the underlying
/// stream.</returns>
internal static ushort ReadUInt16(this BinaryReader reader,
bool bigEndian) {
if (!bigEndian)
return reader.ReadUInt16();
int ret = 0;
ret |= (reader.ReadByte() << 8);
ret |= (reader.ReadByte() << 0);
return (ushort) ret;
}
/// <summary>
/// Decodes a string composed of one or several MIME 'encoded-words'.
/// </summary>
/// <param name="words">A string to composed of one or several MIME
/// 'encoded-words'</param>
/// <exception cref="FormatException">Thrown when an unknown encoding
/// (other than Q-Encoding or Base64) is encountered.</exception>
/// <returns>A concatenation of all enconded-words in the passed
/// string</returns>
public static string DecodeWords(string words) {
if (String.IsNullOrEmpty(words))
return String.Empty;
MatchCollection matches = rxDecodeWord.Matches(words);
if (matches.Count == 0)
return words;
string decoded = String.Empty;
foreach (Match m in matches)
decoded = decoded + DecodeWord(m.Groups[0].Value);
return decoded;
}
private static readonly Regex rxDecodeWord =
new Regex(@"=\?([A-Za-z0-9\-_]+)\?([BbQq])\?([^\?]+)\?=", RegexOptions.Compiled);
/// <summary>
/// Decodes a MIME 'encoded-word' string.
/// </summary>
/// <param name="word">The encoded word to decode</param>
/// <exception cref="FormatException">Thrown when an unknown encoding
/// (other than Q-Encoding or Base64) is encountered.</exception>
/// <returns>A decoded string</returns>
/// <remarks>MIME encoded-word syntax is a way to encode strings that
/// contain non-ASCII data. Commonly used encodings for the encoded-word
/// sytax are Q-Encoding and Base64. For an in-depth description, refer
/// to RFC 2047</remarks>
internal static string DecodeWord(string word) {
if (String.IsNullOrEmpty(word))
return String.Empty;
Match m = rxDecodeWord.Match(word);
if (!m.Success)
return word;
Encoding encoding = Util.GetEncoding(m.Groups[1].Value);
string type = m.Groups[2].Value.ToUpper();
string text = m.Groups[3].Value;
switch (type) {
case "Q":
return Util.QDecode(text, encoding);
case "B":
return encoding.GetString(Util.Base64Decode(text));
default:
throw new FormatException("Encoding not recognized " +
"in encoded word: " + word);
}
}
/// <summary>
/// Takes a Q-encoded string and decodes it using the specified
/// encoding.
/// </summary>
/// <param name="value">The Q-encoded string to decode</param>
/// <param name="encoding">The encoding to use for encoding the
/// returned string</param>
/// <exception cref="FormatException">Thrown if the string is
/// not a valid Q-encoded string.</exception>
/// <returns>A Q-decoded string</returns>
internal static string QDecode(string value, Encoding encoding) {
try {
using (MemoryStream m = new MemoryStream()) {
for (int i = 0; i < value.Length; i++) {
if (value[i] == '=') {
string hex = value.Substring(i + 1, 2);
m.WriteByte(Convert.ToByte(hex, 16));
i = i + 2;
} else if (value[i] == '_') {
m.WriteByte(Convert.ToByte(' '));
} else {
m.WriteByte(Convert.ToByte(value[i]));
}
}
return encoding.GetString(m.ToArray());
}
} catch {
throw new FormatException("value is not a valid Q-encoded " +
"string");
}
}
/// <summary>
/// Takes a quoted-printable encoded string and decodes it using
/// the specified encoding.
/// </summary>
/// <param name="value">The quoted-printable-encoded string to
/// decode</param>
/// <param name="encoding">The encoding to use for encoding the
/// returned string</param>
/// <exception cref="FormatException">Thrown if the string is
/// not a valid quoted-printable encoded string.</exception>
/// <returns>A quoted-printable decoded string</returns>
internal static string QPDecode(string value, Encoding encoding) {
try {
using (MemoryStream m = new MemoryStream()) {
for (int i = 0; i < value.Length; i++) {
if (value[i] == '=') {
string hex = value.Substring(i + 1, 2);
// Deal with soft line breaks.
if(hex != "\r\n")
m.WriteByte(Convert.ToByte(hex, 16));
i = i + 2;
} else {
m.WriteByte(Convert.ToByte(value[i]));
}
}
return encoding.GetString(m.ToArray());
}
} catch {
throw new FormatException("value is not a valid quoted-printable " +
"encoded string");
}
}
/// <summary>
/// Takes a Base64-encoded string and decodes it.
/// </summary>
/// <param name="value">The Base64-encoded string to decode</param>
/// <returns>A byte array containing the Base64-decoded bytes
/// of the input string.</returns>
/// <exception cref="System.ArgumentNullException">Thrown if the
/// input value is null.</exception>
/// <exception cref="System.FormatException">The length of value,
/// ignoring white-space characters, is not zero or a multiple of 4,
/// or the format of value is invalid. value contains a non-base-64
/// character, more than two padding characters, or a non-white
/// space-character among the padding characters.</exception>
internal static byte[] Base64Decode(string value) {
return Convert.FromBase64String(value);
}
/// <summary>
/// Takes a UTF-16 encoded string and encodes it as modified
/// UTF-7.
/// </summary>
/// <param name="s">The string to encode.</param>
/// <returns>A UTF-7 encoded string</returns>
/// <remarks>IMAP uses a modified version of UTF-7 for encoding
/// international mailbox names. For details, refer to RFC 3501
/// section 5.1.3 (Mailbox International Naming
/// Convention).</remarks>
internal static string UTF7Encode(string s) {
StringReader reader = new StringReader(s);
StringBuilder builder = new StringBuilder();
while (reader.Peek() != -1) {
char c = (char)reader.Read();
int codepoint = Convert.ToInt32(c);
// It's a printable ASCII character.
if (codepoint > 0x1F && codepoint < 0x80) {
builder.Append(c == '&' ? "&-" : c.ToString());
} else {
// The character sequence needs to be encoded.
StringBuilder sequence = new StringBuilder(c.ToString());
while (reader.Peek() != -1) {
codepoint = Convert.ToInt32((char)reader.Peek());
if (codepoint > 0x1F && codepoint < 0x80)
break;
sequence.Append((char)reader.Read());
}
byte[] buffer = Encoding.BigEndianUnicode.GetBytes(
sequence.ToString());
string encoded = Convert.ToBase64String(buffer).Replace('/', ',').
TrimEnd('=');
builder.Append("&" + encoded + "-");
}
}
return builder.ToString();
}
/// <summary>
/// Takes a modified UTF-7 encoded string and decodes it.
/// </summary>
/// <param name="s">The UTF-7 encoded string to decode.</param>
/// <returns>A UTF-16 encoded "standard" C# string</returns>
/// <exception cref="FormatException">Thrown if the input string is
/// not a proper UTF-7 encoded string.</exception>
/// <remarks>IMAP uses a modified version of UTF-7 for encoding
/// international mailbox names. For details, refer to RFC 3501
/// section 5.1.3 (Mailbox International Naming
/// Convention).</remarks>
internal static string UTF7Decode(string s) {
StringReader reader = new StringReader(s);
StringBuilder builder = new StringBuilder();
while (reader.Peek() != -1) {
char c = (char)reader.Read();
if (c == '&' && reader.Peek() != '-') {
// The character sequence needs to be decoded.
StringBuilder sequence = new StringBuilder();
while (reader.Peek() != -1) {
if ((c = (char)reader.Read()) == '-')
break;
sequence.Append(c);
}
string encoded = sequence.ToString().Replace(',', '/');
int pad = encoded.Length % 4;
if (pad > 0)
encoded = encoded.PadRight(encoded.Length + (4 - pad), '=');
try {
byte[] buffer = Convert.FromBase64String(encoded);
builder.Append(Encoding.BigEndianUnicode.GetString(buffer));
} catch (Exception e) {
throw new FormatException(
"The input string is not in the correct Format", e);
}
} else {
if (c == '&' && reader.Peek() == '-')
reader.Read();
builder.Append(c);
}
}
return builder.ToString();
}
/// <summary>
/// This just wraps Encoding.GetEncoding in a try-catch block to
/// ensure it never fails. If the encoding can not be determined
/// ASCII is returned as a default.
/// </summary>
/// <param name="name">The code page name of the preferred encoding.
/// Any value returned by System.Text.Encoding.WebName is a valid
/// input.</param>
/// <returns>The System.Text.Encoding associated with the specified
/// code page or Encoding.ASCII if the specified code page could not
/// be resolved.</returns>
internal static Encoding GetEncoding(string name) {
Encoding encoding;
try {
encoding = Encoding.GetEncoding(name);
} catch {
encoding = Encoding.ASCII;
}
return encoding;
}
}
}