Extensions.cs 13 KB

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