Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

PushCertificateStore.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. /*
  2. * Copyright (C) 2015, Google Inc.
  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.transport;
  44. import static java.nio.charset.StandardCharsets.UTF_8;
  45. import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
  46. import static org.eclipse.jgit.lib.Constants.OBJ_COMMIT;
  47. import static org.eclipse.jgit.lib.FileMode.TYPE_FILE;
  48. import java.io.BufferedReader;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.io.InputStreamReader;
  52. import java.io.Reader;
  53. import java.text.MessageFormat;
  54. import java.util.ArrayList;
  55. import java.util.Collection;
  56. import java.util.Collections;
  57. import java.util.Comparator;
  58. import java.util.HashMap;
  59. import java.util.Iterator;
  60. import java.util.List;
  61. import java.util.Map;
  62. import java.util.NoSuchElementException;
  63. import org.eclipse.jgit.dircache.DirCache;
  64. import org.eclipse.jgit.dircache.DirCacheBuilder;
  65. import org.eclipse.jgit.dircache.DirCacheEditor;
  66. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  67. import org.eclipse.jgit.dircache.DirCacheEntry;
  68. import org.eclipse.jgit.internal.JGitText;
  69. import org.eclipse.jgit.lib.BatchRefUpdate;
  70. import org.eclipse.jgit.lib.CommitBuilder;
  71. import org.eclipse.jgit.lib.Constants;
  72. import org.eclipse.jgit.lib.FileMode;
  73. import org.eclipse.jgit.lib.ObjectId;
  74. import org.eclipse.jgit.lib.ObjectInserter;
  75. import org.eclipse.jgit.lib.ObjectLoader;
  76. import org.eclipse.jgit.lib.ObjectReader;
  77. import org.eclipse.jgit.lib.PersonIdent;
  78. import org.eclipse.jgit.lib.Ref;
  79. import org.eclipse.jgit.lib.RefUpdate;
  80. import org.eclipse.jgit.lib.Repository;
  81. import org.eclipse.jgit.revwalk.RevCommit;
  82. import org.eclipse.jgit.revwalk.RevWalk;
  83. import org.eclipse.jgit.treewalk.TreeWalk;
  84. import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
  85. import org.eclipse.jgit.treewalk.filter.PathFilter;
  86. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  87. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  88. /**
  89. * Storage for recorded push certificates.
  90. * <p>
  91. * Push certificates are stored in a special ref {@code refs/meta/push-certs}.
  92. * The filenames in the tree are ref names followed by the special suffix
  93. * <code>@{cert}</code>, and the contents are the latest push cert affecting
  94. * that ref. The special suffix allows storing certificates for both refs/foo
  95. * and refs/foo/bar in case those both existed at some point.
  96. *
  97. * @since 4.1
  98. */
  99. public class PushCertificateStore implements AutoCloseable {
  100. /** Ref name storing push certificates. */
  101. static final String REF_NAME =
  102. Constants.R_REFS + "meta/push-certs"; //$NON-NLS-1$
  103. private static class PendingCert {
  104. private PushCertificate cert;
  105. private PersonIdent ident;
  106. private Collection<ReceiveCommand> matching;
  107. private PendingCert(PushCertificate cert, PersonIdent ident,
  108. Collection<ReceiveCommand> matching) {
  109. this.cert = cert;
  110. this.ident = ident;
  111. this.matching = matching;
  112. }
  113. }
  114. private final Repository db;
  115. private final List<PendingCert> pending;
  116. private ObjectReader reader;
  117. private RevCommit commit;
  118. /**
  119. * Create a new store backed by the given repository.
  120. *
  121. * @param db
  122. * the repository.
  123. */
  124. public PushCertificateStore(Repository db) {
  125. this.db = db;
  126. pending = new ArrayList<>();
  127. }
  128. /**
  129. * Close resources opened by this store.
  130. * <p>
  131. * If {@link #get(String)} was called, closes the cached object reader created
  132. * by that method. Does not close the underlying repository.
  133. */
  134. public void close() {
  135. if (reader != null) {
  136. reader.close();
  137. reader = null;
  138. commit = null;
  139. }
  140. }
  141. /**
  142. * Get latest push certificate associated with a ref.
  143. * <p>
  144. * Lazily opens {@code refs/meta/push-certs} and reads from the repository as
  145. * necessary. The state is cached between calls to {@code get}; to reread the,
  146. * call {@link #close()} first.
  147. *
  148. * @param refName
  149. * the ref name to get the certificate for.
  150. * @return last certificate affecting the ref, or null if no cert was recorded
  151. * for the last update to this ref.
  152. * @throws IOException
  153. * if a problem occurred reading the repository.
  154. */
  155. public PushCertificate get(String refName) throws IOException {
  156. if (reader == null) {
  157. load();
  158. }
  159. try (TreeWalk tw = newTreeWalk(refName)) {
  160. return read(tw);
  161. }
  162. }
  163. /**
  164. * Iterate over all push certificates affecting a ref.
  165. * <p>
  166. * Only includes push certificates actually stored in the tree; see class
  167. * Javadoc for conditions where this might not include all push certs ever
  168. * seen for this ref.
  169. * <p>
  170. * The returned iterable may be iterated multiple times, and push certs will
  171. * be re-read from the current state of the store on each call to {@link
  172. * Iterable#iterator()}. However, method calls on the returned iterator may
  173. * fail if {@code save} or {@code close} is called on the enclosing store
  174. * during iteration.
  175. *
  176. * @param refName
  177. * the ref name to get certificates for.
  178. * @return iterable over certificates; must be fully iterated in order to
  179. * close resources.
  180. */
  181. public Iterable<PushCertificate> getAll(final String refName) {
  182. return new Iterable<PushCertificate>() {
  183. @Override
  184. public Iterator<PushCertificate> iterator() {
  185. return new Iterator<PushCertificate>() {
  186. private final String path = pathName(refName);
  187. private PushCertificate next;
  188. private RevWalk rw;
  189. {
  190. try {
  191. if (reader == null) {
  192. load();
  193. }
  194. if (commit != null) {
  195. rw = new RevWalk(reader);
  196. rw.setTreeFilter(AndTreeFilter.create(
  197. PathFilterGroup.create(
  198. Collections.singleton(PathFilter.create(path))),
  199. TreeFilter.ANY_DIFF));
  200. rw.setRewriteParents(false);
  201. rw.markStart(rw.parseCommit(commit));
  202. } else {
  203. rw = null;
  204. }
  205. } catch (IOException e) {
  206. throw new RuntimeException(e);
  207. }
  208. }
  209. @Override
  210. public boolean hasNext() {
  211. try {
  212. if (next == null) {
  213. if (rw == null) {
  214. return false;
  215. }
  216. try {
  217. RevCommit c = rw.next();
  218. if (c != null) {
  219. try (TreeWalk tw = TreeWalk.forPath(
  220. rw.getObjectReader(), path, c.getTree())) {
  221. next = read(tw);
  222. }
  223. } else {
  224. next = null;
  225. }
  226. } catch (IOException e) {
  227. throw new RuntimeException(e);
  228. }
  229. }
  230. return next != null;
  231. } finally {
  232. if (next == null && rw != null) {
  233. rw.close();
  234. rw = null;
  235. }
  236. }
  237. }
  238. @Override
  239. public PushCertificate next() {
  240. hasNext();
  241. PushCertificate n = next;
  242. if (n == null) {
  243. throw new NoSuchElementException();
  244. }
  245. next = null;
  246. return n;
  247. }
  248. @Override
  249. public void remove() {
  250. throw new UnsupportedOperationException();
  251. }
  252. };
  253. }
  254. };
  255. }
  256. private void load() throws IOException {
  257. close();
  258. reader = db.newObjectReader();
  259. Ref ref = db.getRefDatabase().exactRef(REF_NAME);
  260. if (ref == null) {
  261. // No ref, same as empty.
  262. return;
  263. }
  264. try (RevWalk rw = new RevWalk(reader)) {
  265. commit = rw.parseCommit(ref.getObjectId());
  266. }
  267. }
  268. private static PushCertificate read(TreeWalk tw) throws IOException {
  269. if (tw == null || (tw.getRawMode(0) & TYPE_FILE) != TYPE_FILE) {
  270. return null;
  271. }
  272. ObjectLoader loader =
  273. tw.getObjectReader().open(tw.getObjectId(0), OBJ_BLOB);
  274. try (InputStream in = loader.openStream();
  275. Reader r = new BufferedReader(new InputStreamReader(in, UTF_8))) {
  276. return PushCertificateParser.fromReader(r);
  277. }
  278. }
  279. /**
  280. * Put a certificate to be saved to the store.
  281. * <p>
  282. * Writes the contents of this certificate for each ref mentioned. It is up to
  283. * the caller to ensure this certificate accurately represents the state of
  284. * the ref.
  285. * <p>
  286. * Pending certificates added to this method are not returned by {@link
  287. * #get(String)} and {@link #getAll(String)} until after calling {@link
  288. * #save()}.
  289. *
  290. * @param cert
  291. * certificate to store.
  292. * @param ident
  293. * identity for the commit that stores this certificate. Pending
  294. * certificates are sorted by identity timestamp during {@link
  295. * #save()}.
  296. */
  297. public void put(PushCertificate cert, PersonIdent ident) {
  298. put(cert, ident, null);
  299. }
  300. /**
  301. * Put a certificate to be saved to the store, matching a set of commands.
  302. * <p>
  303. * Like {@link #put(PushCertificate, PersonIdent)}, except a value is only
  304. * stored for a push certificate if there is a corresponding command in the
  305. * list that exactly matches the old/new values mentioned in the push
  306. * certificate.
  307. * <p>
  308. * Pending certificates added to this method are not returned by {@link
  309. * #get(String)} and {@link #getAll(String)} until after calling {@link
  310. * #save()}.
  311. *
  312. * @param cert
  313. * certificate to store.
  314. * @param ident
  315. * identity for the commit that stores this certificate. Pending
  316. * certificates are sorted by identity timestamp during {@link
  317. * #save()}.
  318. * @param matching
  319. * only store certs for the refs listed in this list whose values
  320. * match the commands in the cert.
  321. */
  322. public void put(PushCertificate cert, PersonIdent ident,
  323. Collection<ReceiveCommand> matching) {
  324. pending.add(new PendingCert(cert, ident, matching));
  325. }
  326. /**
  327. * Save pending certificates to the store.
  328. * <p>
  329. * One commit is created per certificate added with {@link
  330. * #put(PushCertificate, PersonIdent)}, in order of identity timestamps, and
  331. * a single ref update is performed.
  332. * <p>
  333. * The pending list is cleared if and only the ref update fails, which allows
  334. * for easy retries in case of lock failure.
  335. *
  336. * @return the result of attempting to update the ref.
  337. * @throws IOException
  338. * if there was an error reading from or writing to the
  339. * repository.
  340. */
  341. public RefUpdate.Result save() throws IOException {
  342. ObjectId newId = write();
  343. if (newId == null) {
  344. return RefUpdate.Result.NO_CHANGE;
  345. }
  346. try (ObjectInserter inserter = db.newObjectInserter()) {
  347. RefUpdate.Result result = updateRef(newId);
  348. switch (result) {
  349. case FAST_FORWARD:
  350. case NEW:
  351. case NO_CHANGE:
  352. pending.clear();
  353. break;
  354. default:
  355. break;
  356. }
  357. return result;
  358. } finally {
  359. close();
  360. }
  361. }
  362. /**
  363. * Save pending certificates to the store in an existing batch ref update.
  364. * <p>
  365. * One commit is created per certificate added with {@link
  366. * #put(PushCertificate, PersonIdent)}, in order of identity timestamps, all
  367. * commits are flushed, and a single command is added to the batch.
  368. * <p>
  369. * The cached ref value and pending list are <em>not</em> cleared. If the ref
  370. * update succeeds, the caller is responsible for calling {@link #close()}
  371. * and/or {@link #clear()}.
  372. *
  373. * @param batch
  374. * update to save to.
  375. * @return whether a command was added to the batch.
  376. * @throws IOException
  377. * if there was an error reading from or writing to the
  378. * repository.
  379. */
  380. public boolean save(BatchRefUpdate batch) throws IOException {
  381. ObjectId newId = write();
  382. if (newId == null || newId.equals(commit)) {
  383. return false;
  384. }
  385. batch.addCommand(new ReceiveCommand(
  386. commit != null ? commit : ObjectId.zeroId(), newId, REF_NAME));
  387. return true;
  388. }
  389. /**
  390. * Clear pending certificates added with {@link #put(PushCertificate,
  391. * PersonIdent)}.
  392. */
  393. public void clear() {
  394. pending.clear();
  395. }
  396. private ObjectId write() throws IOException {
  397. if (pending.isEmpty()) {
  398. return null;
  399. }
  400. if (reader == null) {
  401. load();
  402. }
  403. sortPending(pending);
  404. ObjectId curr = commit;
  405. DirCache dc = newDirCache();
  406. try (ObjectInserter inserter = db.newObjectInserter()) {
  407. for (PendingCert pc : pending) {
  408. curr = saveCert(inserter, dc, pc, curr);
  409. }
  410. inserter.flush();
  411. return curr;
  412. }
  413. }
  414. private static void sortPending(List<PendingCert> pending) {
  415. Collections.sort(pending, new Comparator<PendingCert>() {
  416. @Override
  417. public int compare(PendingCert a, PendingCert b) {
  418. return Long.signum(
  419. a.ident.getWhen().getTime() - b.ident.getWhen().getTime());
  420. }
  421. });
  422. }
  423. private DirCache newDirCache() throws IOException {
  424. DirCache dc = DirCache.newInCore();
  425. if (commit != null) {
  426. DirCacheBuilder b = dc.builder();
  427. b.addTree(new byte[0], DirCacheEntry.STAGE_0, reader, commit.getTree());
  428. b.finish();
  429. }
  430. return dc;
  431. }
  432. private ObjectId saveCert(ObjectInserter inserter, DirCache dc,
  433. PendingCert pc, ObjectId curr) throws IOException {
  434. Map<String, ReceiveCommand> byRef;
  435. if (pc.matching != null) {
  436. byRef = new HashMap<>();
  437. for (ReceiveCommand cmd : pc.matching) {
  438. if (byRef.put(cmd.getRefName(), cmd) != null) {
  439. throw new IllegalStateException();
  440. }
  441. }
  442. } else {
  443. byRef = null;
  444. }
  445. DirCacheEditor editor = dc.editor();
  446. String certText = pc.cert.toText() + pc.cert.getSignature();
  447. final ObjectId certId = inserter.insert(OBJ_BLOB, certText.getBytes(UTF_8));
  448. boolean any = false;
  449. for (ReceiveCommand cmd : pc.cert.getCommands()) {
  450. if (byRef != null && !commandsEqual(cmd, byRef.get(cmd.getRefName()))) {
  451. continue;
  452. }
  453. any = true;
  454. editor.add(new PathEdit(pathName(cmd.getRefName())) {
  455. @Override
  456. public void apply(DirCacheEntry ent) {
  457. ent.setFileMode(FileMode.REGULAR_FILE);
  458. ent.setObjectId(certId);
  459. }
  460. });
  461. }
  462. if (!any) {
  463. return curr;
  464. }
  465. editor.finish();
  466. CommitBuilder cb = new CommitBuilder();
  467. cb.setAuthor(pc.ident);
  468. cb.setCommitter(pc.ident);
  469. cb.setTreeId(dc.writeTree(inserter));
  470. if (curr != null) {
  471. cb.setParentId(curr);
  472. } else {
  473. cb.setParentIds(Collections.<ObjectId> emptyList());
  474. }
  475. cb.setMessage(buildMessage(pc.cert));
  476. return inserter.insert(OBJ_COMMIT, cb.build());
  477. }
  478. private static boolean commandsEqual(ReceiveCommand c1, ReceiveCommand c2) {
  479. if (c1 == null || c2 == null) {
  480. return c1 == c2;
  481. }
  482. return c1.getRefName().equals(c2.getRefName())
  483. && c1.getOldId().equals(c2.getOldId())
  484. && c1.getNewId().equals(c2.getNewId());
  485. }
  486. private RefUpdate.Result updateRef(ObjectId newId) throws IOException {
  487. RefUpdate ru = db.updateRef(REF_NAME);
  488. ru.setExpectedOldObjectId(commit != null ? commit : ObjectId.zeroId());
  489. ru.setNewObjectId(newId);
  490. ru.setRefLogIdent(pending.get(pending.size() - 1).ident);
  491. ru.setRefLogMessage(JGitText.get().storePushCertReflog, false);
  492. try (RevWalk rw = new RevWalk(reader)) {
  493. return ru.update(rw);
  494. }
  495. }
  496. private TreeWalk newTreeWalk(String refName) throws IOException {
  497. if (commit == null) {
  498. return null;
  499. }
  500. return TreeWalk.forPath(reader, pathName(refName), commit.getTree());
  501. }
  502. private static String pathName(String refName) {
  503. return refName + "@{cert}"; //$NON-NLS-1$
  504. }
  505. private static String buildMessage(PushCertificate cert) {
  506. StringBuilder sb = new StringBuilder();
  507. if (cert.getCommands().size() == 1) {
  508. sb.append(MessageFormat.format(
  509. JGitText.get().storePushCertOneRef,
  510. cert.getCommands().get(0).getRefName()));
  511. } else {
  512. sb.append(MessageFormat.format(
  513. JGitText.get().storePushCertMultipleRefs,
  514. Integer.valueOf(cert.getCommands().size())));
  515. }
  516. return sb.append('\n').toString();
  517. }
  518. }