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