CookieCollection.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. #region License
  2. /*
  3. * CookieCollection.cs
  4. *
  5. * This code is derived from CookieCollection.cs (System.Net) of Mono
  6. * (http://www.mono-project.com).
  7. *
  8. * The MIT License
  9. *
  10. * Copyright (c) 2004,2009 Novell, Inc. (http://www.novell.com)
  11. * Copyright (c) 2012-2019 sta.blockhead
  12. *
  13. * Permission is hereby granted, free of charge, to any person obtaining a copy
  14. * of this software and associated documentation files (the "Software"), to deal
  15. * in the Software without restriction, including without limitation the rights
  16. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17. * copies of the Software, and to permit persons to whom the Software is
  18. * furnished to do so, subject to the following conditions:
  19. *
  20. * The above copyright notice and this permission notice shall be included in
  21. * all copies or substantial portions of the Software.
  22. *
  23. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  24. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  25. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  26. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  27. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  28. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  29. * THE SOFTWARE.
  30. */
  31. #endregion
  32. #region Authors
  33. /*
  34. * Authors:
  35. * - Lawrence Pit <loz@cable.a2000.nl>
  36. * - Gonzalo Paniagua Javier <gonzalo@ximian.com>
  37. * - Sebastien Pouliot <sebastien@ximian.com>
  38. */
  39. #endregion
  40. using System;
  41. using System.Collections;
  42. using System.Collections.Generic;
  43. using System.Globalization;
  44. using System.Text;
  45. namespace WebSocketSharp.Net
  46. {
  47. /// <summary>
  48. /// Provides a collection of instances of the <see cref="Cookie"/> class.
  49. /// </summary>
  50. [Serializable]
  51. public class CookieCollection : ICollection<Cookie>
  52. {
  53. #region Private Fields
  54. private List<Cookie> _list;
  55. private bool _readOnly;
  56. private object _sync;
  57. #endregion
  58. #region Public Constructors
  59. /// <summary>
  60. /// Initializes a new instance of the <see cref="CookieCollection"/> class.
  61. /// </summary>
  62. public CookieCollection ()
  63. {
  64. _list = new List<Cookie> ();
  65. _sync = ((ICollection) _list).SyncRoot;
  66. }
  67. #endregion
  68. #region Internal Properties
  69. internal IList<Cookie> List {
  70. get {
  71. return _list;
  72. }
  73. }
  74. internal IEnumerable<Cookie> Sorted {
  75. get {
  76. var list = new List<Cookie> (_list);
  77. if (list.Count > 1)
  78. list.Sort (compareForSorted);
  79. return list;
  80. }
  81. }
  82. #endregion
  83. #region Public Properties
  84. /// <summary>
  85. /// Gets the number of cookies in the collection.
  86. /// </summary>
  87. /// <value>
  88. /// An <see cref="int"/> that represents the number of cookies in
  89. /// the collection.
  90. /// </value>
  91. public int Count {
  92. get {
  93. return _list.Count;
  94. }
  95. }
  96. /// <summary>
  97. /// Gets a value indicating whether the collection is read-only.
  98. /// </summary>
  99. /// <value>
  100. /// <para>
  101. /// <c>true</c> if the collection is read-only; otherwise, <c>false</c>.
  102. /// </para>
  103. /// <para>
  104. /// The default value is <c>false</c>.
  105. /// </para>
  106. /// </value>
  107. public bool IsReadOnly {
  108. get {
  109. return _readOnly;
  110. }
  111. internal set {
  112. _readOnly = value;
  113. }
  114. }
  115. /// <summary>
  116. /// Gets a value indicating whether the access to the collection is
  117. /// thread safe.
  118. /// </summary>
  119. /// <value>
  120. /// <para>
  121. /// <c>true</c> if the access to the collection is thread safe;
  122. /// otherwise, <c>false</c>.
  123. /// </para>
  124. /// <para>
  125. /// The default value is <c>false</c>.
  126. /// </para>
  127. /// </value>
  128. public bool IsSynchronized {
  129. get {
  130. return false;
  131. }
  132. }
  133. /// <summary>
  134. /// Gets the cookie at the specified index from the collection.
  135. /// </summary>
  136. /// <value>
  137. /// A <see cref="Cookie"/> at the specified index in the collection.
  138. /// </value>
  139. /// <param name="index">
  140. /// An <see cref="int"/> that specifies the zero-based index of the cookie
  141. /// to find.
  142. /// </param>
  143. /// <exception cref="ArgumentOutOfRangeException">
  144. /// <paramref name="index"/> is out of allowable range for the collection.
  145. /// </exception>
  146. public Cookie this[int index] {
  147. get {
  148. if (index < 0 || index >= _list.Count)
  149. throw new ArgumentOutOfRangeException ("index");
  150. return _list[index];
  151. }
  152. }
  153. /// <summary>
  154. /// Gets the cookie with the specified name from the collection.
  155. /// </summary>
  156. /// <value>
  157. /// <para>
  158. /// A <see cref="Cookie"/> with the specified name in the collection.
  159. /// </para>
  160. /// <para>
  161. /// <see langword="null"/> if not found.
  162. /// </para>
  163. /// </value>
  164. /// <param name="name">
  165. /// A <see cref="string"/> that specifies the name of the cookie to find.
  166. /// </param>
  167. /// <exception cref="ArgumentNullException">
  168. /// <paramref name="name"/> is <see langword="null"/>.
  169. /// </exception>
  170. public Cookie this[string name] {
  171. get {
  172. if (name == null)
  173. throw new ArgumentNullException ("name");
  174. var caseInsensitive = StringComparison.InvariantCultureIgnoreCase;
  175. foreach (var cookie in Sorted) {
  176. if (cookie.Name.Equals (name, caseInsensitive))
  177. return cookie;
  178. }
  179. return null;
  180. }
  181. }
  182. /// <summary>
  183. /// Gets an object used to synchronize access to the collection.
  184. /// </summary>
  185. /// <value>
  186. /// An <see cref="object"/> used to synchronize access to the collection.
  187. /// </value>
  188. public object SyncRoot {
  189. get {
  190. return _sync;
  191. }
  192. }
  193. #endregion
  194. #region Private Methods
  195. private void add (Cookie cookie)
  196. {
  197. var idx = search (cookie);
  198. if (idx == -1) {
  199. _list.Add (cookie);
  200. return;
  201. }
  202. _list[idx] = cookie;
  203. }
  204. private static int compareForSort (Cookie x, Cookie y)
  205. {
  206. return (x.Name.Length + x.Value.Length)
  207. - (y.Name.Length + y.Value.Length);
  208. }
  209. private static int compareForSorted (Cookie x, Cookie y)
  210. {
  211. var ret = x.Version - y.Version;
  212. return ret != 0
  213. ? ret
  214. : (ret = x.Name.CompareTo (y.Name)) != 0
  215. ? ret
  216. : y.Path.Length - x.Path.Length;
  217. }
  218. private static CookieCollection parseRequest (string value)
  219. {
  220. var ret = new CookieCollection ();
  221. Cookie cookie = null;
  222. var ver = 0;
  223. var caseInsensitive = StringComparison.InvariantCultureIgnoreCase;
  224. var pairs = value.SplitHeaderValue (',', ';').ToList ();
  225. for (var i = 0; i < pairs.Count; i++) {
  226. var pair = pairs[i].Trim ();
  227. if (pair.Length == 0)
  228. continue;
  229. var idx = pair.IndexOf ('=');
  230. if (idx == -1) {
  231. if (cookie == null)
  232. continue;
  233. if (pair.Equals ("$port", caseInsensitive)) {
  234. cookie.Port = "\"\"";
  235. continue;
  236. }
  237. continue;
  238. }
  239. if (idx == 0) {
  240. if (cookie != null) {
  241. ret.add (cookie);
  242. cookie = null;
  243. }
  244. continue;
  245. }
  246. var name = pair.Substring (0, idx).TrimEnd (' ');
  247. var val = idx < pair.Length - 1
  248. ? pair.Substring (idx + 1).TrimStart (' ')
  249. : String.Empty;
  250. if (name.Equals ("$version", caseInsensitive)) {
  251. if (val.Length == 0)
  252. continue;
  253. int num;
  254. if (!Int32.TryParse (val.Unquote (), out num))
  255. continue;
  256. ver = num;
  257. continue;
  258. }
  259. if (name.Equals ("$path", caseInsensitive)) {
  260. if (cookie == null)
  261. continue;
  262. if (val.Length == 0)
  263. continue;
  264. cookie.Path = val;
  265. continue;
  266. }
  267. if (name.Equals ("$domain", caseInsensitive)) {
  268. if (cookie == null)
  269. continue;
  270. if (val.Length == 0)
  271. continue;
  272. cookie.Domain = val;
  273. continue;
  274. }
  275. if (name.Equals ("$port", caseInsensitive)) {
  276. if (cookie == null)
  277. continue;
  278. if (val.Length == 0)
  279. continue;
  280. cookie.Port = val;
  281. continue;
  282. }
  283. if (cookie != null)
  284. ret.add (cookie);
  285. if (!Cookie.TryCreate (name, val, out cookie))
  286. continue;
  287. if (ver != 0)
  288. cookie.Version = ver;
  289. }
  290. if (cookie != null)
  291. ret.add (cookie);
  292. return ret;
  293. }
  294. private static CookieCollection parseResponse (string value)
  295. {
  296. var ret = new CookieCollection ();
  297. Cookie cookie = null;
  298. var caseInsensitive = StringComparison.InvariantCultureIgnoreCase;
  299. var pairs = value.SplitHeaderValue (',', ';').ToList ();
  300. for (var i = 0; i < pairs.Count; i++) {
  301. var pair = pairs[i].Trim ();
  302. if (pair.Length == 0)
  303. continue;
  304. var idx = pair.IndexOf ('=');
  305. if (idx == -1) {
  306. if (cookie == null)
  307. continue;
  308. if (pair.Equals ("port", caseInsensitive)) {
  309. cookie.Port = "\"\"";
  310. continue;
  311. }
  312. if (pair.Equals ("discard", caseInsensitive)) {
  313. cookie.Discard = true;
  314. continue;
  315. }
  316. if (pair.Equals ("secure", caseInsensitive)) {
  317. cookie.Secure = true;
  318. continue;
  319. }
  320. if (pair.Equals ("httponly", caseInsensitive)) {
  321. cookie.HttpOnly = true;
  322. continue;
  323. }
  324. continue;
  325. }
  326. if (idx == 0) {
  327. if (cookie != null) {
  328. ret.add (cookie);
  329. cookie = null;
  330. }
  331. continue;
  332. }
  333. var name = pair.Substring (0, idx).TrimEnd (' ');
  334. var val = idx < pair.Length - 1
  335. ? pair.Substring (idx + 1).TrimStart (' ')
  336. : String.Empty;
  337. if (name.Equals ("version", caseInsensitive)) {
  338. if (cookie == null)
  339. continue;
  340. if (val.Length == 0)
  341. continue;
  342. int num;
  343. if (!Int32.TryParse (val.Unquote (), out num))
  344. continue;
  345. cookie.Version = num;
  346. continue;
  347. }
  348. if (name.Equals ("expires", caseInsensitive)) {
  349. if (val.Length == 0)
  350. continue;
  351. if (i == pairs.Count - 1)
  352. break;
  353. i++;
  354. if (cookie == null)
  355. continue;
  356. if (cookie.Expires != DateTime.MinValue)
  357. continue;
  358. var buff = new StringBuilder (val, 32);
  359. buff.AppendFormat (", {0}", pairs[i].Trim ());
  360. DateTime expires;
  361. if (
  362. !DateTime.TryParseExact (
  363. buff.ToString (),
  364. new[] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
  365. CultureInfo.CreateSpecificCulture ("en-US"),
  366. DateTimeStyles.AdjustToUniversal
  367. | DateTimeStyles.AssumeUniversal,
  368. out expires
  369. )
  370. )
  371. continue;
  372. cookie.Expires = expires.ToLocalTime ();
  373. continue;
  374. }
  375. if (name.Equals ("max-age", caseInsensitive)) {
  376. if (cookie == null)
  377. continue;
  378. if (val.Length == 0)
  379. continue;
  380. int num;
  381. if (!Int32.TryParse (val.Unquote (), out num))
  382. continue;
  383. cookie.MaxAge = num;
  384. continue;
  385. }
  386. if (name.Equals ("path", caseInsensitive)) {
  387. if (cookie == null)
  388. continue;
  389. if (val.Length == 0)
  390. continue;
  391. cookie.Path = val;
  392. continue;
  393. }
  394. if (name.Equals ("domain", caseInsensitive)) {
  395. if (cookie == null)
  396. continue;
  397. if (val.Length == 0)
  398. continue;
  399. cookie.Domain = val;
  400. continue;
  401. }
  402. if (name.Equals ("port", caseInsensitive)) {
  403. if (cookie == null)
  404. continue;
  405. if (val.Length == 0)
  406. continue;
  407. cookie.Port = val;
  408. continue;
  409. }
  410. if (name.Equals ("comment", caseInsensitive)) {
  411. if (cookie == null)
  412. continue;
  413. if (val.Length == 0)
  414. continue;
  415. cookie.Comment = urlDecode (val, Encoding.UTF8);
  416. continue;
  417. }
  418. if (name.Equals ("commenturl", caseInsensitive)) {
  419. if (cookie == null)
  420. continue;
  421. if (val.Length == 0)
  422. continue;
  423. cookie.CommentUri = val.Unquote ().ToUri ();
  424. continue;
  425. }
  426. if (name.Equals ("samesite", caseInsensitive)) {
  427. if (cookie == null)
  428. continue;
  429. if (val.Length == 0)
  430. continue;
  431. cookie.SameSite = val.Unquote ();
  432. continue;
  433. }
  434. if (cookie != null)
  435. ret.add (cookie);
  436. Cookie.TryCreate (name, val, out cookie);
  437. }
  438. if (cookie != null)
  439. ret.add (cookie);
  440. return ret;
  441. }
  442. private int search (Cookie cookie)
  443. {
  444. for (var i = _list.Count - 1; i >= 0; i--) {
  445. if (_list[i].EqualsWithoutValue (cookie))
  446. return i;
  447. }
  448. return -1;
  449. }
  450. private static string urlDecode (string s, Encoding encoding)
  451. {
  452. if (s.IndexOfAny (new[] { '%', '+' }) == -1)
  453. return s;
  454. try {
  455. return HttpUtility.UrlDecode (s, encoding);
  456. }
  457. catch {
  458. return null;
  459. }
  460. }
  461. #endregion
  462. #region Internal Methods
  463. internal static CookieCollection Parse (string value, bool response)
  464. {
  465. try {
  466. return response
  467. ? parseResponse (value)
  468. : parseRequest (value);
  469. }
  470. catch (Exception ex) {
  471. throw new CookieException ("It could not be parsed.", ex);
  472. }
  473. }
  474. internal void SetOrRemove (Cookie cookie)
  475. {
  476. var idx = search (cookie);
  477. if (idx == -1) {
  478. if (cookie.Expired)
  479. return;
  480. _list.Add (cookie);
  481. return;
  482. }
  483. if (cookie.Expired) {
  484. _list.RemoveAt (idx);
  485. return;
  486. }
  487. _list[idx] = cookie;
  488. }
  489. internal void SetOrRemove (CookieCollection cookies)
  490. {
  491. foreach (var cookie in cookies._list)
  492. SetOrRemove (cookie);
  493. }
  494. internal void Sort ()
  495. {
  496. if (_list.Count > 1)
  497. _list.Sort (compareForSort);
  498. }
  499. #endregion
  500. #region Public Methods
  501. /// <summary>
  502. /// Adds the specified cookie to the collection.
  503. /// </summary>
  504. /// <param name="cookie">
  505. /// A <see cref="Cookie"/> to add.
  506. /// </param>
  507. /// <exception cref="InvalidOperationException">
  508. /// The collection is read-only.
  509. /// </exception>
  510. /// <exception cref="ArgumentNullException">
  511. /// <paramref name="cookie"/> is <see langword="null"/>.
  512. /// </exception>
  513. public void Add (Cookie cookie)
  514. {
  515. if (_readOnly) {
  516. var msg = "The collection is read-only.";
  517. throw new InvalidOperationException (msg);
  518. }
  519. if (cookie == null)
  520. throw new ArgumentNullException ("cookie");
  521. add (cookie);
  522. }
  523. /// <summary>
  524. /// Adds the specified cookies to the collection.
  525. /// </summary>
  526. /// <param name="cookies">
  527. /// A <see cref="CookieCollection"/> that contains the cookies to add.
  528. /// </param>
  529. /// <exception cref="InvalidOperationException">
  530. /// The collection is read-only.
  531. /// </exception>
  532. /// <exception cref="ArgumentNullException">
  533. /// <paramref name="cookies"/> is <see langword="null"/>.
  534. /// </exception>
  535. public void Add (CookieCollection cookies)
  536. {
  537. if (_readOnly) {
  538. var msg = "The collection is read-only.";
  539. throw new InvalidOperationException (msg);
  540. }
  541. if (cookies == null)
  542. throw new ArgumentNullException ("cookies");
  543. foreach (var cookie in cookies._list)
  544. add (cookie);
  545. }
  546. /// <summary>
  547. /// Removes all cookies from the collection.
  548. /// </summary>
  549. /// <exception cref="InvalidOperationException">
  550. /// The collection is read-only.
  551. /// </exception>
  552. public void Clear ()
  553. {
  554. if (_readOnly) {
  555. var msg = "The collection is read-only.";
  556. throw new InvalidOperationException (msg);
  557. }
  558. _list.Clear ();
  559. }
  560. /// <summary>
  561. /// Determines whether the collection contains the specified cookie.
  562. /// </summary>
  563. /// <returns>
  564. /// <c>true</c> if the cookie is found in the collection; otherwise,
  565. /// <c>false</c>.
  566. /// </returns>
  567. /// <param name="cookie">
  568. /// A <see cref="Cookie"/> to find.
  569. /// </param>
  570. /// <exception cref="ArgumentNullException">
  571. /// <paramref name="cookie"/> is <see langword="null"/>.
  572. /// </exception>
  573. public bool Contains (Cookie cookie)
  574. {
  575. if (cookie == null)
  576. throw new ArgumentNullException ("cookie");
  577. return search (cookie) > -1;
  578. }
  579. /// <summary>
  580. /// Copies the elements of the collection to the specified array,
  581. /// starting at the specified index.
  582. /// </summary>
  583. /// <param name="array">
  584. /// An array of <see cref="Cookie"/> that specifies the destination of
  585. /// the elements copied from the collection.
  586. /// </param>
  587. /// <param name="index">
  588. /// An <see cref="int"/> that specifies the zero-based index in
  589. /// the array at which copying starts.
  590. /// </param>
  591. /// <exception cref="ArgumentNullException">
  592. /// <paramref name="array"/> is <see langword="null"/>.
  593. /// </exception>
  594. /// <exception cref="ArgumentOutOfRangeException">
  595. /// <paramref name="index"/> is less than zero.
  596. /// </exception>
  597. /// <exception cref="ArgumentException">
  598. /// The space from <paramref name="index"/> to the end of
  599. /// <paramref name="array"/> is not enough to copy to.
  600. /// </exception>
  601. public void CopyTo (Cookie[] array, int index)
  602. {
  603. if (array == null)
  604. throw new ArgumentNullException ("array");
  605. if (index < 0)
  606. throw new ArgumentOutOfRangeException ("index", "Less than zero.");
  607. if (array.Length - index < _list.Count) {
  608. var msg = "The available space of the array is not enough to copy to.";
  609. throw new ArgumentException (msg);
  610. }
  611. _list.CopyTo (array, index);
  612. }
  613. /// <summary>
  614. /// Gets the enumerator that iterates through the collection.
  615. /// </summary>
  616. /// <returns>
  617. /// An <see cref="T:System.Collections.Generic.IEnumerator{Cookie}"/>
  618. /// instance that can be used to iterate through the collection.
  619. /// </returns>
  620. public IEnumerator<Cookie> GetEnumerator ()
  621. {
  622. return _list.GetEnumerator ();
  623. }
  624. /// <summary>
  625. /// Removes the specified cookie from the collection.
  626. /// </summary>
  627. /// <returns>
  628. /// <para>
  629. /// <c>true</c> if the cookie is successfully removed; otherwise,
  630. /// <c>false</c>.
  631. /// </para>
  632. /// <para>
  633. /// <c>false</c> if the cookie is not found in the collection.
  634. /// </para>
  635. /// </returns>
  636. /// <param name="cookie">
  637. /// A <see cref="Cookie"/> to remove.
  638. /// </param>
  639. /// <exception cref="InvalidOperationException">
  640. /// The collection is read-only.
  641. /// </exception>
  642. /// <exception cref="ArgumentNullException">
  643. /// <paramref name="cookie"/> is <see langword="null"/>.
  644. /// </exception>
  645. public bool Remove (Cookie cookie)
  646. {
  647. if (_readOnly) {
  648. var msg = "The collection is read-only.";
  649. throw new InvalidOperationException (msg);
  650. }
  651. if (cookie == null)
  652. throw new ArgumentNullException ("cookie");
  653. var idx = search (cookie);
  654. if (idx == -1)
  655. return false;
  656. _list.RemoveAt (idx);
  657. return true;
  658. }
  659. #endregion
  660. #region Explicit Interface Implementations
  661. /// <summary>
  662. /// Gets the enumerator that iterates through the collection.
  663. /// </summary>
  664. /// <returns>
  665. /// An <see cref="IEnumerator"/> instance that can be used to iterate
  666. /// through the collection.
  667. /// </returns>
  668. IEnumerator IEnumerable.GetEnumerator ()
  669. {
  670. return _list.GetEnumerator ();
  671. }
  672. #endregion
  673. }
  674. }