CookieJar.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. #if NETFX_CORE
  7. using FileStream = BestHTTP.PlatformSupport.IO.FileStream;
  8. using Directory = BestHTTP.PlatformSupport.IO.Directory;
  9. using File = BestHTTP.PlatformSupport.IO.File;
  10. using BestHTTP.PlatformSupport.IO;
  11. #else
  12. using FileStream = System.IO.FileStream;
  13. using Directory = System.IO.Directory;
  14. using System.IO;
  15. #endif
  16. namespace BestHTTP.Cookies
  17. {
  18. /// <summary>
  19. /// The Cookie Jar implementation based on RFC 6265(http://tools.ietf.org/html/rfc6265).
  20. /// </summary>
  21. public static class CookieJar
  22. {
  23. // Version of the cookie store. It may be used in a future version for maintaining compatibility.
  24. private const int Version = 1;
  25. /// <summary>
  26. /// Returns true if File apis are supported.
  27. /// </summary>
  28. public static bool IsSavingSupported
  29. {
  30. get
  31. {
  32. if (IsSupportCheckDone)
  33. return _isSavingSupported;
  34. try
  35. {
  36. File.Exists(HTTPManager.GetRootCacheFolder());
  37. _isSavingSupported = true;
  38. }
  39. catch
  40. {
  41. _isSavingSupported = false;
  42. HTTPManager.Logger.Warning("CookieJar", "Cookie saving and loading disabled!");
  43. }
  44. finally
  45. {
  46. IsSupportCheckDone = true;
  47. }
  48. return _isSavingSupported;
  49. }
  50. }
  51. /// <summary>
  52. /// The plugin will delete cookies that are accessed this threshold ago. Its default value is 7 days.
  53. /// </summary>
  54. public static TimeSpan AccessThreshold = TimeSpan.FromDays(7);
  55. #region Privates
  56. /// <summary>
  57. /// List of the Cookies
  58. /// </summary>
  59. private static List<Cookie> Cookies = new List<Cookie>();
  60. private static string CookieFolder { get; set; }
  61. private static string LibraryPath { get; set; }
  62. /// <summary>
  63. /// Synchronization object for thread safety.
  64. /// </summary>
  65. private static object Locker = new object();
  66. private static bool _isSavingSupported;
  67. private static bool IsSupportCheckDone;
  68. private static bool Loaded;
  69. #endregion
  70. #region Internal Functions
  71. internal static void SetupFolder()
  72. {
  73. if (!CookieJar.IsSavingSupported)
  74. return;
  75. try
  76. {
  77. if (string.IsNullOrEmpty(CookieFolder) || string.IsNullOrEmpty(LibraryPath))
  78. {
  79. CookieFolder = System.IO.Path.Combine(HTTPManager.GetRootCacheFolder(), "Cookies");
  80. LibraryPath = System.IO.Path.Combine(CookieFolder, "Library");
  81. }
  82. }
  83. catch
  84. { }
  85. }
  86. /// <summary>
  87. /// Will set or update all cookies from the response object.
  88. /// </summary>
  89. internal static void Set(HTTPResponse response)
  90. {
  91. if (response == null)
  92. return;
  93. lock(Locker)
  94. {
  95. try
  96. {
  97. Maintain();
  98. List<Cookie> newCookies = new List<Cookie>();
  99. var setCookieHeaders = response.GetHeaderValues("set-cookie");
  100. // No cookies. :'(
  101. if (setCookieHeaders == null)
  102. return;
  103. foreach (var cookieHeader in setCookieHeaders)
  104. {
  105. try
  106. {
  107. Cookie cookie = Cookie.Parse(cookieHeader, response.baseRequest.CurrentUri);
  108. if (cookie != null)
  109. {
  110. int idx;
  111. var old = Find(cookie, out idx);
  112. // if no value for the cookie or already expired then the server asked us to delete the cookie
  113. bool expired = string.IsNullOrEmpty(cookie.Value) || !cookie.WillExpireInTheFuture();
  114. if (!expired)
  115. {
  116. // no old cookie, add it straight to the list
  117. if (old == null)
  118. {
  119. Cookies.Add(cookie);
  120. newCookies.Add(cookie);
  121. }
  122. else
  123. {
  124. // Update the creation-time of the newly created cookie to match the creation-time of the old-cookie.
  125. cookie.Date = old.Date;
  126. Cookies[idx] = cookie;
  127. newCookies.Add(cookie);
  128. }
  129. }
  130. else if (idx != -1) // delete the cookie
  131. Cookies.RemoveAt(idx);
  132. }
  133. }
  134. catch
  135. {
  136. // Ignore cookie on error
  137. }
  138. }
  139. response.Cookies = newCookies;
  140. }
  141. catch
  142. {}
  143. }
  144. }
  145. /// <summary>
  146. /// Deletes all expired or 'old' cookies, and will keep the sum size of cookies under the given size.
  147. /// </summary>
  148. internal static void Maintain()
  149. {
  150. // It's not the same as in the rfc:
  151. // http://tools.ietf.org/html/rfc6265#section-5.3
  152. lock (Locker)
  153. {
  154. try
  155. {
  156. uint size = 0;
  157. for (int i = 0; i < Cookies.Count; )
  158. {
  159. var cookie = Cookies[i];
  160. // Remove expired or not used cookies
  161. if (!cookie.WillExpireInTheFuture() || (cookie.LastAccess + AccessThreshold) < DateTime.UtcNow)
  162. Cookies.RemoveAt(i);
  163. else
  164. {
  165. if (!cookie.IsSession)
  166. size += cookie.GuessSize();
  167. i++;
  168. }
  169. }
  170. if (size > HTTPManager.CookieJarSize)
  171. {
  172. Cookies.Sort();
  173. while (size > HTTPManager.CookieJarSize && Cookies.Count > 0)
  174. {
  175. var cookie = Cookies[0];
  176. Cookies.RemoveAt(0);
  177. size -= cookie.GuessSize();
  178. }
  179. }
  180. }
  181. catch
  182. { }
  183. }
  184. }
  185. /// <summary>
  186. /// Saves the Cookie Jar to a file.
  187. /// </summary>
  188. /// <remarks>Not implemented under Unity WebPlayer</remarks>
  189. internal static void Persist()
  190. {
  191. if (!IsSavingSupported)
  192. return;
  193. lock (Locker)
  194. {
  195. if (!Loaded)
  196. return;
  197. try
  198. {
  199. // Delete any expired cookie
  200. Maintain();
  201. if (!Directory.Exists(CookieFolder))
  202. Directory.CreateDirectory(CookieFolder);
  203. using (var fs = new FileStream(LibraryPath, FileMode.Create))
  204. using (var bw = new System.IO.BinaryWriter(fs))
  205. {
  206. bw.Write(Version);
  207. // Count how many non-session cookies we have
  208. int count = 0;
  209. foreach (var cookie in Cookies)
  210. if (!cookie.IsSession)
  211. count++;
  212. bw.Write(count);
  213. // Save only the persistable cookies
  214. foreach (var cookie in Cookies)
  215. if (!cookie.IsSession)
  216. cookie.SaveTo(bw);
  217. }
  218. }
  219. catch
  220. { }
  221. }
  222. }
  223. /// <summary>
  224. /// Load previously persisted cookie library from the file.
  225. /// </summary>
  226. internal static void Load()
  227. {
  228. if (!IsSavingSupported)
  229. return;
  230. lock (Locker)
  231. {
  232. if (Loaded)
  233. return;
  234. SetupFolder();
  235. try
  236. {
  237. Cookies.Clear();
  238. if (!Directory.Exists(CookieFolder))
  239. Directory.CreateDirectory(CookieFolder);
  240. if (!File.Exists(LibraryPath))
  241. return;
  242. using (var fs = new FileStream(LibraryPath, FileMode.Open))
  243. using (var br = new System.IO.BinaryReader(fs))
  244. {
  245. /*int version = */br.ReadInt32();
  246. int cookieCount = br.ReadInt32();
  247. for (int i = 0; i < cookieCount; ++i)
  248. {
  249. Cookie cookie = new Cookie();
  250. cookie.LoadFrom(br);
  251. if (cookie.WillExpireInTheFuture())
  252. Cookies.Add(cookie);
  253. }
  254. }
  255. }
  256. catch
  257. {
  258. Cookies.Clear();
  259. }
  260. finally
  261. {
  262. Loaded = true;
  263. }
  264. }
  265. }
  266. #endregion
  267. #region Public Functions
  268. /// <summary>
  269. /// Returns all Cookies that corresponds to the given Uri.
  270. /// </summary>
  271. public static List<Cookie> Get(Uri uri)
  272. {
  273. lock (Locker)
  274. {
  275. Load();
  276. List<Cookie> result = null;
  277. for (int i = 0; i < Cookies.Count; ++i)
  278. {
  279. Cookie cookie = Cookies[i];
  280. if (cookie.WillExpireInTheFuture() && uri.Host.IndexOf(cookie.Domain) != -1 && uri.AbsolutePath.StartsWith(cookie.Path))
  281. {
  282. if (result == null)
  283. result = new List<Cookie>();
  284. result.Add(cookie);
  285. }
  286. }
  287. return result;
  288. }
  289. }
  290. /// <summary>
  291. /// Will add a new, or overwrite an old cookie if already exists.
  292. /// </summary>
  293. public static void Set(Uri uri, Cookie cookie)
  294. {
  295. Set(cookie);
  296. }
  297. /// <summary>
  298. /// Will add a new, or overwrite an old cookie if already exists.
  299. /// </summary>
  300. public static void Set(Cookie cookie)
  301. {
  302. lock (Locker)
  303. {
  304. Load();
  305. int idx;
  306. Find(cookie, out idx);
  307. if (idx >= 0)
  308. Cookies[idx] = cookie;
  309. else
  310. Cookies.Add(cookie);
  311. }
  312. }
  313. public static List<Cookie> GetAll()
  314. {
  315. lock (Locker)
  316. {
  317. Load();
  318. return Cookies;
  319. }
  320. }
  321. /// <summary>
  322. /// Deletes all cookies from the Jar.
  323. /// </summary>
  324. public static void Clear()
  325. {
  326. lock (Locker)
  327. {
  328. Load();
  329. Cookies.Clear();
  330. }
  331. }
  332. /// <summary>
  333. /// Removes cookies that older than the given parameter.
  334. /// </summary>
  335. public static void Clear(TimeSpan olderThan)
  336. {
  337. lock (Locker)
  338. {
  339. Load();
  340. for (int i = 0; i < Cookies.Count; )
  341. {
  342. var cookie = Cookies[i];
  343. // Remove expired or not used cookies
  344. if (!cookie.WillExpireInTheFuture() || (cookie.Date + olderThan) < DateTime.UtcNow)
  345. Cookies.RemoveAt(i);
  346. else
  347. i++;
  348. }
  349. }
  350. }
  351. /// <summary>
  352. /// Removes cookies that matches to the given domain.
  353. /// </summary>
  354. public static void Clear(string domain)
  355. {
  356. lock (Locker)
  357. {
  358. Load();
  359. for (int i = 0; i < Cookies.Count; )
  360. {
  361. var cookie = Cookies[i];
  362. // Remove expired or not used cookies
  363. if (!cookie.WillExpireInTheFuture() || cookie.Domain.IndexOf(domain) != -1)
  364. Cookies.RemoveAt(i);
  365. else
  366. i++;
  367. }
  368. }
  369. }
  370. public static void Remove(Uri uri, string name)
  371. {
  372. lock(Locker)
  373. {
  374. Load();
  375. for (int i = 0; i < Cookies.Count; )
  376. {
  377. var cookie = Cookies[i];
  378. if (cookie.Name.Equals(name, StringComparison.OrdinalIgnoreCase) && uri.Host.IndexOf(cookie.Domain) != -1)
  379. Cookies.RemoveAt(i);
  380. else
  381. i++;
  382. }
  383. }
  384. }
  385. #endregion
  386. #region Private Helper Functions
  387. /// <summary>
  388. /// Find and return a Cookie and his index in the list.
  389. /// </summary>
  390. private static Cookie Find(Cookie cookie, out int idx)
  391. {
  392. for (int i = 0; i < Cookies.Count; ++i)
  393. {
  394. Cookie c = Cookies[i];
  395. if (c.Equals(cookie))
  396. {
  397. idx = i;
  398. return c;
  399. }
  400. }
  401. idx = -1;
  402. return null;
  403. }
  404. #endregion
  405. }
  406. }
  407. #endif