Extensions.cs 14 KB

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