Extensions.cs 13 KB

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