You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

NetscapeCookieFile.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /*
  2. * Copyright (C) 2018, Konrad Windszus <konrad_w@gmx.de>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.internal.transport.http;
  44. import java.io.BufferedReader;
  45. import java.io.ByteArrayOutputStream;
  46. import java.io.File;
  47. import java.io.FileNotFoundException;
  48. import java.io.IOException;
  49. import java.io.OutputStreamWriter;
  50. import java.io.StringReader;
  51. import java.io.Writer;
  52. import java.net.HttpCookie;
  53. import java.net.URL;
  54. import java.nio.charset.StandardCharsets;
  55. import java.nio.file.Path;
  56. import java.text.MessageFormat;
  57. import java.util.Arrays;
  58. import java.util.Collection;
  59. import java.util.Date;
  60. import java.util.LinkedHashSet;
  61. import java.util.Set;
  62. import org.eclipse.jgit.annotations.NonNull;
  63. import org.eclipse.jgit.annotations.Nullable;
  64. import org.eclipse.jgit.internal.JGitText;
  65. import org.eclipse.jgit.internal.storage.file.FileSnapshot;
  66. import org.eclipse.jgit.internal.storage.file.LockFile;
  67. import org.eclipse.jgit.lib.Constants;
  68. import org.eclipse.jgit.storage.file.FileBasedConfig;
  69. import org.eclipse.jgit.util.FileUtils;
  70. import org.eclipse.jgit.util.IO;
  71. import org.eclipse.jgit.util.RawParseUtils;
  72. import org.slf4j.Logger;
  73. import org.slf4j.LoggerFactory;
  74. /**
  75. * Wraps all cookies persisted in a <strong>Netscape Cookie File Format</strong>
  76. * being referenced via the git config <a href=
  77. * "https://git-scm.com/docs/git-config#git-config-httpcookieFile">http.cookieFile</a>.
  78. * <p>
  79. * It will only load the cookies lazily, i.e. before calling
  80. * {@link #getCookies(boolean)} the file is not evaluated. This class also
  81. * allows persisting cookies in that file format.
  82. * <p>
  83. * In general this class is not thread-safe. So any consumer needs to take care
  84. * of synchronization!
  85. *
  86. * @see <a href="http://www.cookiecentral.com/faq/#3.5">Netscape Cookie File
  87. * Format</a>
  88. * @see <a href=
  89. * "https://unix.stackexchange.com/questions/36531/format-of-cookies-when-using-wget">Cookie
  90. * format for wget</a>
  91. * @see <a href=
  92. * "https://github.com/curl/curl/blob/07ebaf837843124ee670e5b8c218b80b92e06e47/lib/cookie.c#L745">libcurl
  93. * Cookie file parsing</a>
  94. * @see <a href=
  95. * "https://github.com/curl/curl/blob/07ebaf837843124ee670e5b8c218b80b92e06e47/lib/cookie.c#L1417">libcurl
  96. * Cookie file writing</a>
  97. * @see NetscapeCookieFileCache
  98. */
  99. public final class NetscapeCookieFile {
  100. private static final String HTTP_ONLY_PREAMBLE = "#HttpOnly_"; //$NON-NLS-1$
  101. private static final String COLUMN_SEPARATOR = "\t"; //$NON-NLS-1$
  102. private static final String LINE_SEPARATOR = "\n"; //$NON-NLS-1$
  103. /**
  104. * Maximum number of retries to acquire the lock for writing to the
  105. * underlying file.
  106. */
  107. private static final int LOCK_ACQUIRE_MAX_RETRY_COUNT = 4;
  108. /**
  109. * Sleep time in milliseconds between retries to acquire the lock for
  110. * writing to the underlying file.
  111. */
  112. private static final int LOCK_ACQUIRE_RETRY_SLEEP = 500;
  113. private final Path path;
  114. private FileSnapshot snapshot;
  115. private byte[] hash;
  116. final Date creationDate;
  117. private Set<HttpCookie> cookies = null;
  118. private static final Logger LOG = LoggerFactory
  119. .getLogger(NetscapeCookieFile.class);
  120. /**
  121. * @param path
  122. * where to find the cookie file
  123. */
  124. public NetscapeCookieFile(Path path) {
  125. this(path, new Date());
  126. }
  127. NetscapeCookieFile(Path path, Date creationDate) {
  128. this.path = path;
  129. this.snapshot = FileSnapshot.DIRTY;
  130. this.creationDate = creationDate;
  131. }
  132. /**
  133. * Path to the underlying cookie file.
  134. *
  135. * @return the path
  136. */
  137. public Path getPath() {
  138. return path;
  139. }
  140. /**
  141. * Return all cookies from the underlying cookie file.
  142. *
  143. * @param refresh
  144. * if {@code true} updates the list from the underlying cookie
  145. * file if it has been modified since the last read otherwise
  146. * returns the current transient state. In case the cookie file
  147. * has never been read before will always read from the
  148. * underlying file disregarding the value of this parameter.
  149. * @return all cookies (may contain session cookies as well). This does not
  150. * return a copy of the list but rather the original one. Every
  151. * addition to the returned list can afterwards be persisted via
  152. * {@link #write(URL)}. Errors in the underlying file will not lead
  153. * to exceptions but rather to an empty set being returned and the
  154. * underlying error being logged.
  155. */
  156. public Set<HttpCookie> getCookies(boolean refresh) {
  157. if (cookies == null || refresh) {
  158. try {
  159. byte[] in = getFileContentIfModified();
  160. Set<HttpCookie> newCookies = parseCookieFile(in, creationDate);
  161. if (cookies != null) {
  162. cookies = mergeCookies(newCookies, cookies);
  163. } else {
  164. cookies = newCookies;
  165. }
  166. return cookies;
  167. } catch (IOException | IllegalArgumentException e) {
  168. LOG.warn(
  169. MessageFormat.format(
  170. JGitText.get().couldNotReadCookieFile, path),
  171. e);
  172. if (cookies == null) {
  173. cookies = new LinkedHashSet<>();
  174. }
  175. }
  176. }
  177. return cookies;
  178. }
  179. /**
  180. * Parses the given file and extracts all cookie information from it.
  181. *
  182. * @param input
  183. * the file content to parse
  184. * @param creationDate
  185. * the date for the creation of the cookies (used to calculate
  186. * the maxAge based on the expiration date given within the file)
  187. * @return the set of parsed cookies from the given file (even expired
  188. * ones). If there is more than one cookie with the same name in
  189. * this file the last one overwrites the first one!
  190. * @throws IOException
  191. * if the given file could not be read for some reason
  192. * @throws IllegalArgumentException
  193. * if the given file does not have a proper format
  194. */
  195. private static Set<HttpCookie> parseCookieFile(@NonNull byte[] input,
  196. @NonNull Date creationDate)
  197. throws IOException, IllegalArgumentException {
  198. String decoded = RawParseUtils.decode(StandardCharsets.US_ASCII, input);
  199. Set<HttpCookie> cookies = new LinkedHashSet<>();
  200. try (BufferedReader reader = new BufferedReader(
  201. new StringReader(decoded))) {
  202. String line;
  203. while ((line = reader.readLine()) != null) {
  204. HttpCookie cookie = parseLine(line, creationDate);
  205. if (cookie != null) {
  206. cookies.add(cookie);
  207. }
  208. }
  209. }
  210. return cookies;
  211. }
  212. private static HttpCookie parseLine(@NonNull String line,
  213. @NonNull Date creationDate) {
  214. if (line.isEmpty() || (line.startsWith("#") //$NON-NLS-1$
  215. && !line.startsWith(HTTP_ONLY_PREAMBLE))) {
  216. return null;
  217. }
  218. String[] cookieLineParts = line.split(COLUMN_SEPARATOR, 7);
  219. if (cookieLineParts == null) {
  220. throw new IllegalArgumentException(MessageFormat
  221. .format(JGitText.get().couldNotFindTabInLine, line));
  222. }
  223. if (cookieLineParts.length < 7) {
  224. throw new IllegalArgumentException(MessageFormat.format(
  225. JGitText.get().couldNotFindSixTabsInLine,
  226. Integer.valueOf(cookieLineParts.length), line));
  227. }
  228. String name = cookieLineParts[5];
  229. String value = cookieLineParts[6];
  230. HttpCookie cookie = new HttpCookie(name, value);
  231. String domain = cookieLineParts[0];
  232. if (domain.startsWith(HTTP_ONLY_PREAMBLE)) {
  233. cookie.setHttpOnly(true);
  234. domain = domain.substring(HTTP_ONLY_PREAMBLE.length());
  235. }
  236. // strip off leading "."
  237. // (https://tools.ietf.org/html/rfc6265#section-5.2.3)
  238. if (domain.startsWith(".")) { //$NON-NLS-1$
  239. domain = domain.substring(1);
  240. }
  241. cookie.setDomain(domain);
  242. // domain evaluation as boolean flag not considered (i.e. always assumed
  243. // to be true)
  244. cookie.setPath(cookieLineParts[2]);
  245. cookie.setSecure(Boolean.parseBoolean(cookieLineParts[3]));
  246. long expires = Long.parseLong(cookieLineParts[4]);
  247. long maxAge = (expires - creationDate.getTime()) / 1000;
  248. if (maxAge <= 0) {
  249. return null; // skip expired cookies
  250. }
  251. cookie.setMaxAge(maxAge);
  252. return cookie;
  253. }
  254. /**
  255. * Read the underying file and return its content but only in case it has
  256. * been modified since the last access.
  257. * <p>
  258. * Internally calculates the hash and maintains {@link FileSnapshot}s to
  259. * prevent issues described as <a href=
  260. * "https://github.com/git/git/blob/master/Documentation/technical/racy-git.txt">"Racy
  261. * Git problem"</a>. Inspired by {@link FileBasedConfig#load()}.
  262. *
  263. * @return the file contents in case the file has been modified since the
  264. * last access, otherwise {@code null}
  265. * @throws IOException
  266. * if the file is not found or cannot be read
  267. */
  268. private byte[] getFileContentIfModified() throws IOException {
  269. final int maxStaleRetries = 5;
  270. int retries = 0;
  271. File file = getPath().toFile();
  272. if (!file.exists()) {
  273. LOG.warn(MessageFormat.format(JGitText.get().missingCookieFile,
  274. file.getAbsolutePath()));
  275. return new byte[0];
  276. }
  277. while (true) {
  278. final FileSnapshot oldSnapshot = snapshot;
  279. final FileSnapshot newSnapshot = FileSnapshot.save(file);
  280. try {
  281. final byte[] in = IO.readFully(file);
  282. byte[] newHash = hash(in);
  283. if (Arrays.equals(hash, newHash)) {
  284. if (oldSnapshot.equals(newSnapshot)) {
  285. oldSnapshot.setClean(newSnapshot);
  286. } else {
  287. snapshot = newSnapshot;
  288. }
  289. } else {
  290. snapshot = newSnapshot;
  291. hash = newHash;
  292. }
  293. return in;
  294. } catch (FileNotFoundException e) {
  295. throw e;
  296. } catch (IOException e) {
  297. if (FileUtils.isStaleFileHandle(e)
  298. && retries < maxStaleRetries) {
  299. if (LOG.isDebugEnabled()) {
  300. LOG.debug(MessageFormat.format(
  301. JGitText.get().configHandleIsStale,
  302. Integer.valueOf(retries)), e);
  303. }
  304. retries++;
  305. continue;
  306. }
  307. throw new IOException(MessageFormat
  308. .format(JGitText.get().cannotReadFile, getPath()), e);
  309. }
  310. }
  311. }
  312. private static byte[] hash(final byte[] in) {
  313. return Constants.newMessageDigest().digest(in);
  314. }
  315. /**
  316. * Writes all the cookies being maintained in the set being returned by
  317. * {@link #getCookies(boolean)} to the underlying file.
  318. * <p>
  319. * Session-cookies will not be persisted.
  320. *
  321. * @param url
  322. * url for which to write the cookies (important to derive
  323. * default values for non-explicitly set attributes)
  324. * @throws IOException
  325. * if the underlying cookie file could not be read or written or
  326. * a problem with the lock file
  327. * @throws InterruptedException
  328. * if the thread is interrupted while waiting for the lock
  329. */
  330. public void write(URL url) throws IOException, InterruptedException {
  331. try {
  332. byte[] cookieFileContent = getFileContentIfModified();
  333. if (cookieFileContent != null) {
  334. LOG.debug("Reading the underlying cookie file '{}' " //$NON-NLS-1$
  335. + "as it has been modified since " //$NON-NLS-1$
  336. + "the last access", //$NON-NLS-1$
  337. path);
  338. // reread new changes if necessary
  339. Set<HttpCookie> cookiesFromFile = NetscapeCookieFile
  340. .parseCookieFile(cookieFileContent, creationDate);
  341. this.cookies = mergeCookies(cookiesFromFile, cookies);
  342. }
  343. } catch (FileNotFoundException e) {
  344. // ignore if file previously did not exist yet!
  345. }
  346. ByteArrayOutputStream output = new ByteArrayOutputStream();
  347. try (Writer writer = new OutputStreamWriter(output,
  348. StandardCharsets.US_ASCII)) {
  349. write(writer, cookies, url, creationDate);
  350. }
  351. LockFile lockFile = new LockFile(path.toFile());
  352. for (int retryCount = 0; retryCount < LOCK_ACQUIRE_MAX_RETRY_COUNT; retryCount++) {
  353. if (lockFile.lock()) {
  354. try {
  355. lockFile.setNeedSnapshot(true);
  356. lockFile.write(output.toByteArray());
  357. if (!lockFile.commit()) {
  358. throw new IOException(MessageFormat.format(
  359. JGitText.get().cannotCommitWriteTo, path));
  360. }
  361. } finally {
  362. lockFile.unlock();
  363. }
  364. return;
  365. }
  366. Thread.sleep(LOCK_ACQUIRE_RETRY_SLEEP);
  367. }
  368. throw new IOException(
  369. MessageFormat.format(JGitText.get().cannotLock, lockFile));
  370. }
  371. /**
  372. * Writes the given cookies to the file in the Netscape Cookie File Format
  373. * (also used by curl).
  374. *
  375. * @param writer
  376. * the writer to use to persist the cookies
  377. * @param cookies
  378. * the cookies to write into the file
  379. * @param url
  380. * the url for which to write the cookie (to derive the default
  381. * values for certain cookie attributes)
  382. * @param creationDate
  383. * the date when the cookie has been created. Important for
  384. * calculation the cookie expiration time (calculated from
  385. * cookie's maxAge and this creation time)
  386. * @throws IOException
  387. * if an I/O error occurs
  388. */
  389. static void write(@NonNull Writer writer,
  390. @NonNull Collection<HttpCookie> cookies, @NonNull URL url,
  391. @NonNull Date creationDate) throws IOException {
  392. for (HttpCookie cookie : cookies) {
  393. writeCookie(writer, cookie, url, creationDate);
  394. }
  395. }
  396. private static void writeCookie(@NonNull Writer writer,
  397. @NonNull HttpCookie cookie, @NonNull URL url,
  398. @NonNull Date creationDate) throws IOException {
  399. if (cookie.getMaxAge() <= 0) {
  400. return; // skip expired cookies
  401. }
  402. String domain = ""; //$NON-NLS-1$
  403. if (cookie.isHttpOnly()) {
  404. domain = HTTP_ONLY_PREAMBLE;
  405. }
  406. if (cookie.getDomain() != null) {
  407. domain += cookie.getDomain();
  408. } else {
  409. domain += url.getHost();
  410. }
  411. writer.write(domain);
  412. writer.write(COLUMN_SEPARATOR);
  413. writer.write("TRUE"); //$NON-NLS-1$
  414. writer.write(COLUMN_SEPARATOR);
  415. String path = cookie.getPath();
  416. if (path == null) {
  417. path = url.getPath();
  418. }
  419. writer.write(path);
  420. writer.write(COLUMN_SEPARATOR);
  421. writer.write(Boolean.toString(cookie.getSecure()).toUpperCase());
  422. writer.write(COLUMN_SEPARATOR);
  423. final String expirationDate;
  424. // whenCreated field is not accessible in HttpCookie
  425. expirationDate = String
  426. .valueOf(creationDate.getTime() + (cookie.getMaxAge() * 1000));
  427. writer.write(expirationDate);
  428. writer.write(COLUMN_SEPARATOR);
  429. writer.write(cookie.getName());
  430. writer.write(COLUMN_SEPARATOR);
  431. writer.write(cookie.getValue());
  432. writer.write(LINE_SEPARATOR);
  433. }
  434. /**
  435. * Merge the given sets in the following way. All cookies from
  436. * {@code cookies1} and {@code cookies2} are contained in the resulting set
  437. * which have unique names. If there is a duplicate entry for one name only
  438. * the entry from set {@code cookies1} ends up in the resulting set.
  439. *
  440. * @param cookies1
  441. * first set of cookies
  442. * @param cookies2
  443. * second set of cookies
  444. *
  445. * @return the merged cookies
  446. */
  447. static Set<HttpCookie> mergeCookies(Set<HttpCookie> cookies1,
  448. @Nullable Set<HttpCookie> cookies2) {
  449. Set<HttpCookie> mergedCookies = new LinkedHashSet<>(cookies1);
  450. if (cookies2 != null) {
  451. mergedCookies.addAll(cookies2);
  452. }
  453. return mergedCookies;
  454. }
  455. }