CookieJar.cs 14 KB

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