Extensions.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using Best.HTTP.Shared.PlatformSupport.Text;
  6. using Cryptography = System.Security.Cryptography;
  7. using Best.HTTP.Shared.Streams;
  8. using Best.HTTP.Shared.PlatformSupport.Memory;
  9. using static Best.HTTP.Hosts.Connections.HTTP1.Constants;
  10. namespace Best.HTTP.Shared.Extensions
  11. {
  12. public static class Extensions
  13. {
  14. #region ASCII Encoding (These are required because Windows Phone doesn't supports the Encoding.ASCII class.)
  15. /// <summary>
  16. /// On WP8 platform there are no ASCII encoding.
  17. /// </summary>
  18. public static string AsciiToString(this byte[] bytes)
  19. {
  20. StringBuilder sb = StringBuilderPool.Get(bytes.Length); //new StringBuilder(bytes.Length);
  21. foreach (byte b in bytes)
  22. sb.Append(b <= 0x7f ? (char)b : '?');
  23. return StringBuilderPool.ReleaseAndGrab(sb);
  24. }
  25. /// <summary>
  26. /// On WP8 platform there are no ASCII encoding.
  27. /// </summary>
  28. public static BufferSegment GetASCIIBytes(this string str)
  29. {
  30. byte[] result = BufferPool.Get(str.Length, true);
  31. for (int i = 0; i < str.Length; ++i)
  32. {
  33. char ch = str[i];
  34. result[i] = (byte)((ch < (char)0x80) ? ch : '?');
  35. }
  36. return new BufferSegment(result, 0, str.Length);
  37. }
  38. public static void SendAsASCII(this BinaryWriter stream, string str)
  39. {
  40. for (int i = 0; i < str.Length; ++i)
  41. {
  42. char ch = str[i];
  43. stream.Write((byte)((ch < (char)0x80) ? ch : '?'));
  44. }
  45. }
  46. #endregion
  47. #region Headers
  48. public static Dictionary<string, List<string>> AddHeader(this Dictionary<string, List<string>> headers, string name, string value)
  49. {
  50. if (headers == null)
  51. headers = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
  52. List<string> values;
  53. if (!headers.TryGetValue(name, out values))
  54. headers.Add(name, values = new List<string>(1));
  55. values.Add(value);
  56. return headers;
  57. }
  58. public static Dictionary<string, List<string>> SetHeader(this Dictionary<string, List<string>> headers, string name, string value)
  59. {
  60. if (headers == null)
  61. headers = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
  62. List<string> values;
  63. if (!headers.TryGetValue(name, out values))
  64. headers.Add(name, values = new List<string>(1));
  65. values.Clear();
  66. values.Add(value);
  67. return headers;
  68. }
  69. public static bool RemoveHeader(this Dictionary<string, List<string>> headers, string name) => headers != null && headers.Remove(name);
  70. public static void RemoveHeaders(this Dictionary<string, List<string>> headers) => headers?.Clear();
  71. public static List<string> GetHeaderValues(this Dictionary<string, List<string>> headers, string name)
  72. {
  73. if (headers == null)
  74. return null;
  75. List<string> values;
  76. if (!headers.TryGetValue(name, out values) || values.Count == 0)
  77. return null;
  78. return values;
  79. }
  80. public static string GetFirstHeaderValue(this Dictionary<string, List<string>> headers, string name)
  81. {
  82. if (headers == null)
  83. return null;
  84. List<string> values;
  85. if (!headers.TryGetValue(name, out values) || values.Count == 0)
  86. return null;
  87. return values[0];
  88. }
  89. public static bool HasHeaderWithValue(this Dictionary<string, List<string>> headers, string headerName, string value)
  90. {
  91. var values = headers.GetHeaderValues(headerName);
  92. if (values == null)
  93. return false;
  94. for (int i = 0; i < values.Count; ++i)
  95. if (string.Compare(values[i], value, StringComparison.OrdinalIgnoreCase) == 0)
  96. return true;
  97. return false;
  98. }
  99. public static bool HasHeader(this Dictionary<string, List<string>> headers, string headerName)
  100. => headers != null && headers.ContainsKey(headerName);
  101. #endregion
  102. #region FileSystem WriteLine function support
  103. public static void WriteString(this Stream fs, string value)
  104. {
  105. int count = System.Text.Encoding.UTF8.GetByteCount(value);
  106. var buffer = BufferPool.Get(count, true);
  107. try
  108. {
  109. System.Text.Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, 0);
  110. fs.Write(buffer, 0, count);
  111. }
  112. finally
  113. {
  114. BufferPool.Release(buffer);
  115. }
  116. }
  117. public static void WriteLine(this Stream fs)
  118. {
  119. fs.Write(EOL, 0, 2);
  120. }
  121. public static void WriteLine(this Stream fs, string line)
  122. {
  123. var buff = line.GetASCIIBytes();
  124. try
  125. {
  126. fs.Write(buff.Data, buff.Offset, buff.Count);
  127. fs.WriteLine();
  128. }
  129. finally
  130. {
  131. BufferPool.Release(buff);
  132. }
  133. }
  134. public static void WriteLine(this Stream fs, string format, params object[] values)
  135. {
  136. var buff = string.Format(format, values).GetASCIIBytes();
  137. try
  138. {
  139. fs.Write(buff.Data, buff.Offset, buff.Count);
  140. fs.WriteLine();
  141. }
  142. finally
  143. {
  144. BufferPool.Release(buff);
  145. }
  146. }
  147. #endregion
  148. #region Other Extensions
  149. public static AutoReleaseBuffer AsAutoRelease(this byte[] buffer) => new AutoReleaseBuffer(buffer);
  150. public static BufferSegment AsBuffer(this byte[] bytes)
  151. {
  152. return new BufferSegment(bytes, 0, bytes.Length);
  153. }
  154. public static BufferSegment AsBuffer(this byte[] bytes, int length)
  155. {
  156. return new BufferSegment(bytes, 0, length);
  157. }
  158. public static BufferSegment AsBuffer(this byte[] bytes, int offset, int length)
  159. {
  160. return new BufferSegment(bytes, offset, length);
  161. }
  162. public static BufferSegment CopyAsBuffer(this byte[] bytes, int offset, int length)
  163. {
  164. var newBuff = BufferPool.Get(length, true);
  165. Array.Copy(bytes, offset, newBuff, 0, length);
  166. return newBuff.AsBuffer(0, length);
  167. }
  168. public static string GetRequestPathAndQueryURL(this Uri uri)
  169. {
  170. string requestPathAndQuery = uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped);
  171. // http://forum.unity3d.com/threads/best-http-released.200006/page-26#post-2723250
  172. if (string.IsNullOrEmpty(requestPathAndQuery))
  173. requestPathAndQuery = "/";
  174. return requestPathAndQuery;
  175. }
  176. public static string[] FindOption(this string str, string option)
  177. {
  178. //s-maxage=2678400, must-revalidate, max-age=0
  179. string[] options = str.ToLowerInvariant().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  180. option = option.ToLowerInvariant();
  181. for (int i = 0; i < options.Length; ++i)
  182. if (options[i].Contains(option))
  183. return options[i].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
  184. return null;
  185. }
  186. public static string[] FindOption(this string[] options, string option)
  187. {
  188. for (int i = 0; i < options.Length; ++i)
  189. if (options[i].Contains(option))
  190. return options[i].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
  191. return null;
  192. }
  193. public static void WriteArray(this Stream stream, byte[] array)
  194. {
  195. stream.Write(array, 0, array.Length);
  196. }
  197. public static void WriteBufferSegment(this Stream stream, BufferSegment buffer)
  198. {
  199. stream.Write(buffer.Data, buffer.Offset, buffer.Count);
  200. }
  201. /// <summary>
  202. /// Returns true if the Uri's host is a valid IPv4 or IPv6 address.
  203. /// </summary>
  204. public static bool IsHostIsAnIPAddress(this Uri uri)
  205. {
  206. if (uri == null)
  207. return false;
  208. return IsIpV4AddressValid(uri.Host) || IsIpV6AddressValid(uri.Host);
  209. }
  210. // Original idea from: https://www.code4copy.com/csharp/c-validate-ip-address-string/
  211. // Working regex: https://www.regular-expressions.info/ip.html
  212. private static readonly System.Text.RegularExpressions.Regex validIpV4AddressRegex = new System.Text.RegularExpressions.Regex("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  213. /// <summary>
  214. /// Validates an IPv4 address.
  215. /// </summary>
  216. public static bool IsIpV4AddressValid(string address)
  217. {
  218. if (!string.IsNullOrEmpty(address))
  219. return validIpV4AddressRegex.IsMatch(address.Trim());
  220. return false;
  221. }
  222. /// <summary>
  223. /// Validates an IPv6 address.
  224. /// </summary>
  225. public static bool IsIpV6AddressValid(string address)
  226. {
  227. if (!string.IsNullOrEmpty(address))
  228. {
  229. System.Net.IPAddress ip;
  230. if (System.Net.IPAddress.TryParse(address, out ip))
  231. return ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6;
  232. }
  233. return false;
  234. }
  235. #endregion
  236. #region String Conversions
  237. public static int ToInt32(this string str, int defaultValue = default(int)) => int.TryParse(str, out var value) ? value : defaultValue;
  238. public static uint ToUInt32(this string str, uint defaultValue = default) => uint.TryParse(str, out var value) ? value : defaultValue;
  239. public static long ToInt64(this string str, long defaultValue = default(long)) => long.TryParse(str, out var value) ? value : defaultValue;
  240. public static ulong ToUInt64(this string str, ulong defaultValue = default(ulong)) => ulong.TryParse(str, out var value) ? value : defaultValue;
  241. public static DateTime ToDateTime(this string str, DateTime defaultValue = default(DateTime))
  242. {
  243. if (str == null)
  244. return defaultValue;
  245. try
  246. {
  247. DateTime.TryParse(str, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out defaultValue);
  248. return defaultValue;
  249. }
  250. catch
  251. {
  252. return defaultValue;
  253. }
  254. }
  255. public static string ToStrOrEmpty(this string str)
  256. {
  257. if (str == null)
  258. return String.Empty;
  259. return str;
  260. }
  261. public static string ToStr(this string str, string defaultVale)
  262. {
  263. if (str == null)
  264. return defaultVale;
  265. return str;
  266. }
  267. public static string ToBinaryStr(this byte value)
  268. {
  269. return Convert.ToString(value, 2).PadLeft(8, '0');
  270. }
  271. #endregion
  272. #region MD5 Hashing
  273. public static string CalculateMD5Hash(this string input)
  274. {
  275. var asciiBuff = input.GetASCIIBytes();
  276. var hash = asciiBuff.CalculateMD5Hash();
  277. BufferPool.Release(asciiBuff);
  278. return hash;
  279. }
  280. public static string CalculateMD5Hash(this BufferSegment input)
  281. {
  282. using (var md5 = Cryptography.MD5.Create()) {
  283. var hash = md5.ComputeHash(input.Data, input.Offset, input.Count);
  284. var sb = StringBuilderPool.Get(hash.Length); //new StringBuilder(hash.Length);
  285. for (int i = 0; i < hash.Length; ++i)
  286. sb.Append(hash[i].ToString("x2"));
  287. BufferPool.Release(hash);
  288. return StringBuilderPool.ReleaseAndGrab(sb);
  289. }
  290. }
  291. #endregion
  292. #region Efficient String Parsing Helpers
  293. internal static string Read(this string str, ref int pos, char block, bool needResult = true)
  294. {
  295. return str.Read(ref pos, (ch) => ch != block, needResult);
  296. }
  297. internal static string Read(this string str, ref int pos, Func<char, bool> block, bool needResult = true)
  298. {
  299. if (pos >= str.Length)
  300. return string.Empty;
  301. str.SkipWhiteSpace(ref pos);
  302. int startPos = pos;
  303. while (pos < str.Length && block(str[pos]))
  304. pos++;
  305. string result = needResult ? str.Substring(startPos, pos - startPos) : null;
  306. // set position to the next char
  307. pos++;
  308. return result;
  309. }
  310. internal static string ReadPossibleQuotedText(this string str, ref int pos)
  311. {
  312. string result = string.Empty;
  313. if (str == null)
  314. return result;
  315. // It's a quoted text?
  316. if (str[pos] == '\"')
  317. {
  318. // Skip the starting quote
  319. str.Read(ref pos, '\"', false);
  320. // Read the text until the ending quote
  321. result = str.Read(ref pos, '\"');
  322. // Next option
  323. str.Read(ref pos, (ch) => ch != ',' && ch != ';', false);
  324. }
  325. else
  326. // It's not a quoted text, so we will read until the next option
  327. result = str.Read(ref pos, (ch) => ch != ',' && ch != ';');
  328. return result;
  329. }
  330. internal static void SkipWhiteSpace(this string str, ref int pos)
  331. {
  332. if (pos >= str.Length)
  333. return;
  334. while (pos < str.Length && char.IsWhiteSpace(str[pos]))
  335. pos++;
  336. }
  337. internal static string TrimAndLower(this string str)
  338. {
  339. if (str == null)
  340. return null;
  341. char[] buffer = new char[str.Length];
  342. int length = 0;
  343. for (int i = 0; i < str.Length; ++i)
  344. {
  345. char ch = str[i];
  346. if (!char.IsWhiteSpace(ch) && !char.IsControl(ch))
  347. buffer[length++] = char.ToLowerInvariant(ch);
  348. }
  349. return new string(buffer, 0, length);
  350. }
  351. internal static char? Peek(this string str, int pos)
  352. {
  353. if (pos < 0 || pos >= str.Length)
  354. return null;
  355. return str[pos];
  356. }
  357. #endregion
  358. #region Specialized String Parsers
  359. //public, max-age=2592000
  360. internal static List<HeaderValue> ParseOptionalHeader(this string str)
  361. {
  362. List<HeaderValue> result = new List<HeaderValue>();
  363. if (str == null)
  364. return result;
  365. int idx = 0;
  366. // process the rest of the text
  367. while (idx < str.Length)
  368. {
  369. // Read key
  370. string key = str.Read(ref idx, (ch) => ch != '=' && ch != ',').TrimAndLower();
  371. HeaderValue qp = new HeaderValue(key);
  372. if (str[idx - 1] == '=')
  373. qp.Value = str.ReadPossibleQuotedText(ref idx);
  374. result.Add(qp);
  375. }
  376. return result;
  377. }
  378. //deflate, gzip, x-gzip, identity, *;q=0
  379. internal static List<HeaderValue> ParseQualityParams(this string str)
  380. {
  381. List<HeaderValue> result = new List<HeaderValue>();
  382. if (str == null)
  383. return result;
  384. int idx = 0;
  385. while (idx < str.Length)
  386. {
  387. string key = str.Read(ref idx, (ch) => ch != ',' && ch != ';').TrimAndLower();
  388. HeaderValue qp = new HeaderValue(key);
  389. if (str[idx - 1] == ';')
  390. {
  391. str.Read(ref idx, '=', false);
  392. qp.Value = str.Read(ref idx, ',');
  393. }
  394. result.Add(qp);
  395. }
  396. return result;
  397. }
  398. #endregion
  399. #region Buffer Filling
  400. /// <summary>
  401. /// Will fill the entire buffer from the stream. Will throw an exception when the underlying stream is closed.
  402. /// </summary>
  403. public static void ReadBuffer(this Stream stream, byte[] buffer)
  404. {
  405. int count = 0;
  406. do
  407. {
  408. int read = stream.Read(buffer, count, buffer.Length - count);
  409. if (read <= 0)
  410. throw ExceptionHelper.ServerClosedTCPStream();
  411. count += read;
  412. } while (count < buffer.Length);
  413. }
  414. public static void ReadBuffer(this Stream stream, byte[] buffer, int length)
  415. {
  416. int count = 0;
  417. do
  418. {
  419. int read = stream.Read(buffer, count, length - count);
  420. if (read <= 0)
  421. throw ExceptionHelper.ServerClosedTCPStream();
  422. count += read;
  423. } while (count < length);
  424. }
  425. #endregion
  426. #region BufferPoolMemoryStream
  427. public static void WriteString(this BufferPoolMemoryStream ms, string str)
  428. {
  429. var byteCount = Encoding.UTF8.GetByteCount(str);
  430. byte[] buffer = BufferPool.Get(byteCount, true);
  431. Encoding.UTF8.GetBytes(str, 0, str.Length, buffer, 0);
  432. ms.Write(buffer, 0, byteCount);
  433. BufferPool.Release(buffer);
  434. }
  435. public static void WriteLine(this BufferPoolMemoryStream ms)
  436. {
  437. ms.Write(EOL, 0, EOL.Length);
  438. }
  439. public static void WriteLine(this BufferPoolMemoryStream ms, string str)
  440. {
  441. ms.WriteString(str);
  442. ms.Write(EOL, 0, EOL.Length);
  443. }
  444. #endregion
  445. #if NET_STANDARD_2_0 || NET_4_6
  446. public static void Clear<T>(this System.Collections.Concurrent.ConcurrentQueue<T> queue)
  447. {
  448. T result;
  449. while (queue.TryDequeue(out result))
  450. ;
  451. }
  452. #endif
  453. }
  454. public static class ExceptionHelper
  455. {
  456. public static Exception ServerClosedTCPStream()
  457. {
  458. return new Exception("TCP Stream closed unexpectedly by the remote server");
  459. }
  460. }
  461. }