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.

TransportAmazonS3.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /*
  2. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.transport;
  11. import java.io.BufferedReader;
  12. import java.io.File;
  13. import java.io.FileNotFoundException;
  14. import java.io.IOException;
  15. import java.io.InputStream;
  16. import java.io.OutputStream;
  17. import java.net.URLConnection;
  18. import java.text.MessageFormat;
  19. import java.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.EnumSet;
  23. import java.util.HashSet;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Properties;
  27. import java.util.Set;
  28. import java.util.TreeMap;
  29. import org.eclipse.jgit.errors.NotSupportedException;
  30. import org.eclipse.jgit.errors.TransportException;
  31. import org.eclipse.jgit.internal.JGitText;
  32. import org.eclipse.jgit.lib.Constants;
  33. import org.eclipse.jgit.lib.ObjectId;
  34. import org.eclipse.jgit.lib.ObjectIdRef;
  35. import org.eclipse.jgit.lib.ProgressMonitor;
  36. import org.eclipse.jgit.lib.Ref;
  37. import org.eclipse.jgit.lib.Ref.Storage;
  38. import org.eclipse.jgit.lib.Repository;
  39. import org.eclipse.jgit.lib.SymbolicRef;
  40. /**
  41. * Transport over the non-Git aware Amazon S3 protocol.
  42. * <p>
  43. * This transport communicates with the Amazon S3 servers (a non-free commercial
  44. * hosting service that users must subscribe to). Some users may find transport
  45. * to and from S3 to be a useful backup service.
  46. * <p>
  47. * The transport does not require any specialized Git support on the remote
  48. * (server side) repository, as Amazon does not provide any such support.
  49. * Repository files are retrieved directly through the S3 API, which uses
  50. * extended HTTP/1.1 semantics. This make it possible to read or write Git data
  51. * from a remote repository that is stored on S3.
  52. * <p>
  53. * Unlike the HTTP variant (see
  54. * {@link org.eclipse.jgit.transport.TransportHttp}) we rely upon being able to
  55. * list objects in a bucket, as the S3 API supports this function. By listing
  56. * the bucket contents we can avoid relying on <code>objects/info/packs</code>
  57. * or <code>info/refs</code> in the remote repository.
  58. * <p>
  59. * Concurrent pushing over this transport is not supported. Multiple concurrent
  60. * push operations may cause confusion in the repository state.
  61. *
  62. * @see WalkFetchConnection
  63. * @see WalkPushConnection
  64. */
  65. public class TransportAmazonS3 extends HttpTransport implements WalkTransport {
  66. static final String S3_SCHEME = "amazon-s3"; //$NON-NLS-1$
  67. static final TransportProtocol PROTO_S3 = new TransportProtocol() {
  68. @Override
  69. public String getName() {
  70. return "Amazon S3"; //$NON-NLS-1$
  71. }
  72. @Override
  73. public Set<String> getSchemes() {
  74. return Collections.singleton(S3_SCHEME);
  75. }
  76. @Override
  77. public Set<URIishField> getRequiredFields() {
  78. return Collections.unmodifiableSet(EnumSet.of(URIishField.USER,
  79. URIishField.HOST, URIishField.PATH));
  80. }
  81. @Override
  82. public Set<URIishField> getOptionalFields() {
  83. return Collections.unmodifiableSet(EnumSet.of(URIishField.PASS));
  84. }
  85. @Override
  86. public Transport open(URIish uri, Repository local, String remoteName)
  87. throws NotSupportedException {
  88. return new TransportAmazonS3(local, uri);
  89. }
  90. };
  91. /** User information necessary to connect to S3. */
  92. final AmazonS3 s3;
  93. /** Bucket the remote repository is stored in. */
  94. final String bucket;
  95. /**
  96. * Key prefix which all objects related to the repository start with.
  97. * <p>
  98. * The prefix does not start with "/".
  99. * <p>
  100. * The prefix does not end with "/". The trailing slash is stripped during
  101. * the constructor if a trailing slash was supplied in the URIish.
  102. * <p>
  103. * All files within the remote repository start with
  104. * <code>keyPrefix + "/"</code>.
  105. */
  106. private final String keyPrefix;
  107. TransportAmazonS3(final Repository local, final URIish uri)
  108. throws NotSupportedException {
  109. super(local, uri);
  110. Properties props = loadProperties();
  111. File directory = local.getDirectory();
  112. if (!props.containsKey("tmpdir") && directory != null) //$NON-NLS-1$
  113. props.put("tmpdir", directory.getPath()); //$NON-NLS-1$
  114. s3 = new AmazonS3(props);
  115. bucket = uri.getHost();
  116. String p = uri.getPath();
  117. if (p.startsWith("/")) //$NON-NLS-1$
  118. p = p.substring(1);
  119. if (p.endsWith("/")) //$NON-NLS-1$
  120. p = p.substring(0, p.length() - 1);
  121. keyPrefix = p;
  122. }
  123. private Properties loadProperties() throws NotSupportedException {
  124. if (local.getDirectory() != null) {
  125. File propsFile = new File(local.getDirectory(), uri.getUser());
  126. if (propsFile.isFile())
  127. return loadPropertiesFile(propsFile);
  128. }
  129. File propsFile = new File(local.getFS().userHome(), uri.getUser());
  130. if (propsFile.isFile())
  131. return loadPropertiesFile(propsFile);
  132. Properties props = new Properties();
  133. String user = uri.getUser();
  134. String pass = uri.getPass();
  135. if (user != null && pass != null) {
  136. props.setProperty("accesskey", user); //$NON-NLS-1$
  137. props.setProperty("secretkey", pass); //$NON-NLS-1$
  138. } else
  139. throw new NotSupportedException(MessageFormat.format(
  140. JGitText.get().cannotReadFile, propsFile));
  141. return props;
  142. }
  143. private static Properties loadPropertiesFile(File propsFile)
  144. throws NotSupportedException {
  145. try {
  146. return AmazonS3.properties(propsFile);
  147. } catch (IOException e) {
  148. throw new NotSupportedException(MessageFormat.format(
  149. JGitText.get().cannotReadFile, propsFile), e);
  150. }
  151. }
  152. /** {@inheritDoc} */
  153. @Override
  154. public FetchConnection openFetch() throws TransportException {
  155. final DatabaseS3 c = new DatabaseS3(bucket, keyPrefix + "/objects"); //$NON-NLS-1$
  156. final WalkFetchConnection r = new WalkFetchConnection(this, c);
  157. r.available(c.readAdvertisedRefs());
  158. return r;
  159. }
  160. /** {@inheritDoc} */
  161. @Override
  162. public PushConnection openPush() throws TransportException {
  163. final DatabaseS3 c = new DatabaseS3(bucket, keyPrefix + "/objects"); //$NON-NLS-1$
  164. final WalkPushConnection r = new WalkPushConnection(this, c);
  165. r.available(c.readAdvertisedRefs());
  166. return r;
  167. }
  168. /** {@inheritDoc} */
  169. @Override
  170. public void close() {
  171. // No explicit connections are maintained.
  172. }
  173. class DatabaseS3 extends WalkRemoteObjectDatabase {
  174. private final String bucketName;
  175. private final String objectsKey;
  176. DatabaseS3(final String b, final String o) {
  177. bucketName = b;
  178. objectsKey = o;
  179. }
  180. private String resolveKey(String subpath) {
  181. if (subpath.endsWith("/")) //$NON-NLS-1$
  182. subpath = subpath.substring(0, subpath.length() - 1);
  183. String k = objectsKey;
  184. while (subpath.startsWith(ROOT_DIR)) {
  185. k = k.substring(0, k.lastIndexOf('/'));
  186. subpath = subpath.substring(3);
  187. }
  188. return k + "/" + subpath; //$NON-NLS-1$
  189. }
  190. @Override
  191. URIish getURI() {
  192. URIish u = new URIish();
  193. u = u.setScheme(S3_SCHEME);
  194. u = u.setHost(bucketName);
  195. u = u.setPath("/" + objectsKey); //$NON-NLS-1$
  196. return u;
  197. }
  198. @Override
  199. Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
  200. try {
  201. return readAlternates(Constants.INFO_ALTERNATES);
  202. } catch (FileNotFoundException err) {
  203. // Fall through.
  204. }
  205. return null;
  206. }
  207. @Override
  208. WalkRemoteObjectDatabase openAlternate(String location)
  209. throws IOException {
  210. return new DatabaseS3(bucketName, resolveKey(location));
  211. }
  212. @Override
  213. Collection<String> getPackNames() throws IOException {
  214. // s3.list returns most recently modified packs first.
  215. // These are the packs most likely to contain missing refs.
  216. final List<String> packList = s3.list(bucket, resolveKey("pack")); //$NON-NLS-1$
  217. final HashSet<String> have = new HashSet<>();
  218. have.addAll(packList);
  219. final Collection<String> packs = new ArrayList<>();
  220. for (String n : packList) {
  221. if (!n.startsWith("pack-") || !n.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  222. continue;
  223. final String in = n.substring(0, n.length() - 5) + ".idx"; //$NON-NLS-1$
  224. if (have.contains(in))
  225. packs.add(n);
  226. }
  227. return packs;
  228. }
  229. @Override
  230. FileStream open(String path) throws IOException {
  231. final URLConnection c = s3.get(bucket, resolveKey(path));
  232. final InputStream raw = c.getInputStream();
  233. final InputStream in = s3.decrypt(c);
  234. final int len = c.getContentLength();
  235. return new FileStream(in, raw == in ? len : -1);
  236. }
  237. @Override
  238. void deleteFile(String path) throws IOException {
  239. s3.delete(bucket, resolveKey(path));
  240. }
  241. @Override
  242. OutputStream writeFile(final String path,
  243. final ProgressMonitor monitor, final String monitorTask)
  244. throws IOException {
  245. return s3.beginPut(bucket, resolveKey(path), monitor, monitorTask);
  246. }
  247. @Override
  248. void writeFile(String path, byte[] data) throws IOException {
  249. s3.put(bucket, resolveKey(path), data);
  250. }
  251. Map<String, Ref> readAdvertisedRefs() throws TransportException {
  252. final TreeMap<String, Ref> avail = new TreeMap<>();
  253. readPackedRefs(avail);
  254. readLooseRefs(avail);
  255. readRef(avail, Constants.HEAD);
  256. return avail;
  257. }
  258. private void readLooseRefs(TreeMap<String, Ref> avail)
  259. throws TransportException {
  260. try {
  261. for (final String n : s3.list(bucket, resolveKey(ROOT_DIR
  262. + "refs"))) //$NON-NLS-1$
  263. readRef(avail, "refs/" + n); //$NON-NLS-1$
  264. } catch (IOException e) {
  265. throw new TransportException(getURI(), JGitText.get().cannotListRefs, e);
  266. }
  267. }
  268. private Ref readRef(TreeMap<String, Ref> avail, String rn)
  269. throws TransportException {
  270. final String s;
  271. String ref = ROOT_DIR + rn;
  272. try {
  273. try (BufferedReader br = openReader(ref)) {
  274. s = br.readLine();
  275. }
  276. } catch (FileNotFoundException noRef) {
  277. return null;
  278. } catch (IOException err) {
  279. throw new TransportException(getURI(), MessageFormat.format(
  280. JGitText.get().transportExceptionReadRef, ref), err);
  281. }
  282. if (s == null)
  283. throw new TransportException(getURI(), MessageFormat.format(JGitText.get().transportExceptionEmptyRef, rn));
  284. if (s.startsWith("ref: ")) { //$NON-NLS-1$
  285. final String target = s.substring("ref: ".length()); //$NON-NLS-1$
  286. Ref r = avail.get(target);
  287. if (r == null)
  288. r = readRef(avail, target);
  289. if (r == null)
  290. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  291. r = new SymbolicRef(rn, r);
  292. avail.put(r.getName(), r);
  293. return r;
  294. }
  295. if (ObjectId.isId(s)) {
  296. final Ref r = new ObjectIdRef.Unpeeled(loose(avail.get(rn)),
  297. rn, ObjectId.fromString(s));
  298. avail.put(r.getName(), r);
  299. return r;
  300. }
  301. throw new TransportException(getURI(), MessageFormat.format(JGitText.get().transportExceptionBadRef, rn, s));
  302. }
  303. private Storage loose(Ref r) {
  304. if (r != null && r.getStorage() == Storage.PACKED)
  305. return Storage.LOOSE_PACKED;
  306. return Storage.LOOSE;
  307. }
  308. @Override
  309. void close() {
  310. // We do not maintain persistent connections.
  311. }
  312. }
  313. }