CookieJar.cs 15 KB

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