Extensions.cs 15 KB

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