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.

AmazonS3.java 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. /*
  2. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  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 java.io.ByteArrayOutputStream;
  46. import java.io.File;
  47. import java.io.FileInputStream;
  48. import java.io.FileNotFoundException;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.io.OutputStream;
  52. import java.net.HttpURLConnection;
  53. import java.net.Proxy;
  54. import java.net.ProxySelector;
  55. import java.net.URL;
  56. import java.net.URLConnection;
  57. import java.security.DigestOutputStream;
  58. import java.security.GeneralSecurityException;
  59. import java.security.InvalidKeyException;
  60. import java.security.MessageDigest;
  61. import java.security.NoSuchAlgorithmException;
  62. import java.text.MessageFormat;
  63. import java.text.SimpleDateFormat;
  64. import java.util.ArrayList;
  65. import java.util.Collections;
  66. import java.util.Date;
  67. import java.util.HashSet;
  68. import java.util.Iterator;
  69. import java.util.List;
  70. import java.util.Locale;
  71. import java.util.Map;
  72. import java.util.Properties;
  73. import java.util.Set;
  74. import java.util.SortedMap;
  75. import java.util.TimeZone;
  76. import java.util.TreeMap;
  77. import javax.crypto.Mac;
  78. import javax.crypto.spec.SecretKeySpec;
  79. import org.eclipse.jgit.internal.JGitText;
  80. import org.eclipse.jgit.lib.Constants;
  81. import org.eclipse.jgit.lib.NullProgressMonitor;
  82. import org.eclipse.jgit.lib.ProgressMonitor;
  83. import org.eclipse.jgit.util.Base64;
  84. import org.eclipse.jgit.util.HttpSupport;
  85. import org.eclipse.jgit.util.StringUtils;
  86. import org.eclipse.jgit.util.TemporaryBuffer;
  87. import org.xml.sax.Attributes;
  88. import org.xml.sax.InputSource;
  89. import org.xml.sax.SAXException;
  90. import org.xml.sax.XMLReader;
  91. import org.xml.sax.helpers.DefaultHandler;
  92. import org.xml.sax.helpers.XMLReaderFactory;
  93. /**
  94. * A simple HTTP REST client for the Amazon S3 service.
  95. * <p>
  96. * This client uses the REST API to communicate with the Amazon S3 servers and
  97. * read or write content through a bucket that the user has access to. It is a
  98. * very lightweight implementation of the S3 API and therefore does not have all
  99. * of the bells and whistles of popular client implementations.
  100. * <p>
  101. * Authentication is always performed using the user's AWSAccessKeyId and their
  102. * private AWSSecretAccessKey.
  103. * <p>
  104. * Optional client-side encryption may be enabled if requested. The format is
  105. * compatible with <a href="http://jets3t.s3.amazonaws.com/index.html">jets3t</a>,
  106. * a popular Java based Amazon S3 client library. Enabling encryption can hide
  107. * sensitive data from the operators of the S3 service.
  108. */
  109. public class AmazonS3 {
  110. private static final Set<String> SIGNED_HEADERS;
  111. private static final String HMAC = "HmacSHA1"; //$NON-NLS-1$
  112. private static final String X_AMZ_ACL = "x-amz-acl"; //$NON-NLS-1$
  113. private static final String X_AMZ_META = "x-amz-meta-"; //$NON-NLS-1$
  114. static {
  115. SIGNED_HEADERS = new HashSet<>();
  116. SIGNED_HEADERS.add("content-type"); //$NON-NLS-1$
  117. SIGNED_HEADERS.add("content-md5"); //$NON-NLS-1$
  118. SIGNED_HEADERS.add("date"); //$NON-NLS-1$
  119. }
  120. private static boolean isSignedHeader(String name) {
  121. final String nameLC = StringUtils.toLowerCase(name);
  122. return SIGNED_HEADERS.contains(nameLC) || nameLC.startsWith("x-amz-"); //$NON-NLS-1$
  123. }
  124. private static String toCleanString(List<String> list) {
  125. final StringBuilder s = new StringBuilder();
  126. for (String v : list) {
  127. if (s.length() > 0)
  128. s.append(',');
  129. s.append(v.replaceAll("\n", "").trim()); //$NON-NLS-1$ //$NON-NLS-2$
  130. }
  131. return s.toString();
  132. }
  133. private static String remove(Map<String, String> m, String k) {
  134. final String r = m.remove(k);
  135. return r != null ? r : ""; //$NON-NLS-1$
  136. }
  137. private static String httpNow() {
  138. final String tz = "GMT"; //$NON-NLS-1$
  139. final SimpleDateFormat fmt;
  140. fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US); //$NON-NLS-1$
  141. fmt.setTimeZone(TimeZone.getTimeZone(tz));
  142. return fmt.format(new Date()) + " " + tz; //$NON-NLS-1$
  143. }
  144. private static MessageDigest newMD5() {
  145. try {
  146. return MessageDigest.getInstance("MD5"); //$NON-NLS-1$
  147. } catch (NoSuchAlgorithmException e) {
  148. throw new RuntimeException(JGitText.get().JRELacksMD5Implementation, e);
  149. }
  150. }
  151. /** AWSAccessKeyId, public string that identifies the user's account. */
  152. private final String publicKey;
  153. /** Decoded form of the private AWSSecretAccessKey, to sign requests. */
  154. private final SecretKeySpec privateKey;
  155. /** Our HTTP proxy support, in case we are behind a firewall. */
  156. private final ProxySelector proxySelector;
  157. /** ACL to apply to created objects. */
  158. private final String acl;
  159. /** Maximum number of times to try an operation. */
  160. final int maxAttempts;
  161. /** Encryption algorithm, may be a null instance that provides pass-through. */
  162. private final WalkEncryption encryption;
  163. /** Directory for locally buffered content. */
  164. private final File tmpDir;
  165. /** S3 Bucket Domain. */
  166. private final String domain;
  167. /** Property names used in amazon connection configuration file. */
  168. interface Keys {
  169. String ACCESS_KEY = "accesskey"; //$NON-NLS-1$
  170. String SECRET_KEY = "secretkey"; //$NON-NLS-1$
  171. String PASSWORD = "password"; //$NON-NLS-1$
  172. String CRYPTO_ALG = "crypto.algorithm"; //$NON-NLS-1$
  173. String CRYPTO_VER = "crypto.version"; //$NON-NLS-1$
  174. String ACL = "acl"; //$NON-NLS-1$
  175. String DOMAIN = "domain"; //$NON-NLS-1$
  176. String HTTP_RETRY = "httpclient.retry-max"; //$NON-NLS-1$
  177. String TMP_DIR = "tmpdir"; //$NON-NLS-1$
  178. }
  179. /**
  180. * Create a new S3 client for the supplied user information.
  181. * <p>
  182. * The connection properties are a subset of those supported by the popular
  183. * <a href="http://jets3t.s3.amazonaws.com/index.html">jets3t</a> library.
  184. * For example:
  185. *
  186. * <pre>
  187. * # AWS Access and Secret Keys (required)
  188. * accesskey: &lt;YourAWSAccessKey&gt;
  189. * secretkey: &lt;YourAWSSecretKey&gt;
  190. *
  191. * # Access Control List setting to apply to uploads, must be one of:
  192. * # PRIVATE, PUBLIC_READ (defaults to PRIVATE).
  193. * acl: PRIVATE
  194. *
  195. * # S3 Domain
  196. * # AWS S3 Region Domain (defaults to s3.amazonaws.com)
  197. * domain: s3.amazonaws.com
  198. *
  199. * # Number of times to retry after internal error from S3.
  200. * httpclient.retry-max: 3
  201. *
  202. * # End-to-end encryption (hides content from S3 owners)
  203. * password: &lt;encryption pass-phrase&gt;
  204. * crypto.algorithm: PBEWithMD5AndDES
  205. * </pre>
  206. *
  207. * @param props
  208. * connection properties.
  209. */
  210. public AmazonS3(final Properties props) {
  211. domain = props.getProperty(Keys.DOMAIN, "s3.amazonaws.com"); //$NON-NLS-1$
  212. publicKey = props.getProperty(Keys.ACCESS_KEY);
  213. if (publicKey == null)
  214. throw new IllegalArgumentException(JGitText.get().missingAccesskey);
  215. final String secret = props.getProperty(Keys.SECRET_KEY);
  216. if (secret == null)
  217. throw new IllegalArgumentException(JGitText.get().missingSecretkey);
  218. privateKey = new SecretKeySpec(Constants.encodeASCII(secret), HMAC);
  219. final String pacl = props.getProperty(Keys.ACL, "PRIVATE"); //$NON-NLS-1$
  220. if (StringUtils.equalsIgnoreCase("PRIVATE", pacl)) //$NON-NLS-1$
  221. acl = "private"; //$NON-NLS-1$
  222. else if (StringUtils.equalsIgnoreCase("PUBLIC", pacl)) //$NON-NLS-1$
  223. acl = "public-read"; //$NON-NLS-1$
  224. else if (StringUtils.equalsIgnoreCase("PUBLIC-READ", pacl)) //$NON-NLS-1$
  225. acl = "public-read"; //$NON-NLS-1$
  226. else if (StringUtils.equalsIgnoreCase("PUBLIC_READ", pacl)) //$NON-NLS-1$
  227. acl = "public-read"; //$NON-NLS-1$
  228. else
  229. throw new IllegalArgumentException("Invalid acl: " + pacl); //$NON-NLS-1$
  230. try {
  231. encryption = WalkEncryption.instance(props);
  232. } catch (GeneralSecurityException e) {
  233. throw new IllegalArgumentException(JGitText.get().invalidEncryption, e);
  234. }
  235. maxAttempts = Integer
  236. .parseInt(props.getProperty(Keys.HTTP_RETRY, "3")); //$NON-NLS-1$
  237. proxySelector = ProxySelector.getDefault();
  238. String tmp = props.getProperty(Keys.TMP_DIR);
  239. tmpDir = tmp != null && tmp.length() > 0 ? new File(tmp) : null;
  240. }
  241. /**
  242. * Get the content of a bucket object.
  243. *
  244. * @param bucket
  245. * name of the bucket storing the object.
  246. * @param key
  247. * key of the object within its bucket.
  248. * @return connection to stream the content of the object. The request
  249. * properties of the connection may not be modified by the caller as
  250. * the request parameters have already been signed.
  251. * @throws java.io.IOException
  252. * sending the request was not possible.
  253. */
  254. public URLConnection get(String bucket, String key)
  255. throws IOException {
  256. for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++) {
  257. final HttpURLConnection c = open("GET", bucket, key); //$NON-NLS-1$
  258. authorize(c);
  259. switch (HttpSupport.response(c)) {
  260. case HttpURLConnection.HTTP_OK:
  261. encryption.validate(c, X_AMZ_META);
  262. return c;
  263. case HttpURLConnection.HTTP_NOT_FOUND:
  264. throw new FileNotFoundException(key);
  265. case HttpURLConnection.HTTP_INTERNAL_ERROR:
  266. continue;
  267. default:
  268. throw error(JGitText.get().s3ActionReading, key, c);
  269. }
  270. }
  271. throw maxAttempts(JGitText.get().s3ActionReading, key);
  272. }
  273. /**
  274. * Decrypt an input stream from {@link #get(String, String)}.
  275. *
  276. * @param u
  277. * connection previously created by {@link #get(String, String)}}.
  278. * @return stream to read plain text from.
  279. * @throws java.io.IOException
  280. * decryption could not be configured.
  281. */
  282. public InputStream decrypt(URLConnection u) throws IOException {
  283. return encryption.decrypt(u.getInputStream());
  284. }
  285. /**
  286. * List the names of keys available within a bucket.
  287. * <p>
  288. * This method is primarily meant for obtaining a "recursive directory
  289. * listing" rooted under the specified bucket and prefix location.
  290. *
  291. * @param bucket
  292. * name of the bucket whose objects should be listed.
  293. * @param prefix
  294. * common prefix to filter the results by. Must not be null.
  295. * Supplying the empty string will list all keys in the bucket.
  296. * Supplying a non-empty string will act as though a trailing '/'
  297. * appears in prefix, even if it does not.
  298. * @return list of keys starting with <code>prefix</code>, after removing
  299. * <code>prefix</code> (or <code>prefix + "/"</code>)from all
  300. * of them.
  301. * @throws java.io.IOException
  302. * sending the request was not possible, or the response XML
  303. * document could not be parsed properly.
  304. */
  305. public List<String> list(String bucket, String prefix)
  306. throws IOException {
  307. if (prefix.length() > 0 && !prefix.endsWith("/")) //$NON-NLS-1$
  308. prefix += "/"; //$NON-NLS-1$
  309. final ListParser lp = new ListParser(bucket, prefix);
  310. do {
  311. lp.list();
  312. } while (lp.truncated);
  313. return lp.entries;
  314. }
  315. /**
  316. * Delete a single object.
  317. * <p>
  318. * Deletion always succeeds, even if the object does not exist.
  319. *
  320. * @param bucket
  321. * name of the bucket storing the object.
  322. * @param key
  323. * key of the object within its bucket.
  324. * @throws java.io.IOException
  325. * deletion failed due to communications error.
  326. */
  327. public void delete(String bucket, String key)
  328. throws IOException {
  329. for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++) {
  330. final HttpURLConnection c = open("DELETE", bucket, key); //$NON-NLS-1$
  331. authorize(c);
  332. switch (HttpSupport.response(c)) {
  333. case HttpURLConnection.HTTP_NO_CONTENT:
  334. return;
  335. case HttpURLConnection.HTTP_INTERNAL_ERROR:
  336. continue;
  337. default:
  338. throw error(JGitText.get().s3ActionDeletion, key, c);
  339. }
  340. }
  341. throw maxAttempts(JGitText.get().s3ActionDeletion, key);
  342. }
  343. /**
  344. * Atomically create or replace a single small object.
  345. * <p>
  346. * This form is only suitable for smaller contents, where the caller can
  347. * reasonable fit the entire thing into memory.
  348. * <p>
  349. * End-to-end data integrity is assured by internally computing the MD5
  350. * checksum of the supplied data and transmitting the checksum along with
  351. * the data itself.
  352. *
  353. * @param bucket
  354. * name of the bucket storing the object.
  355. * @param key
  356. * key of the object within its bucket.
  357. * @param data
  358. * new data content for the object. Must not be null. Zero length
  359. * array will create a zero length object.
  360. * @throws java.io.IOException
  361. * creation/updating failed due to communications error.
  362. */
  363. public void put(String bucket, String key, byte[] data)
  364. throws IOException {
  365. if (encryption != WalkEncryption.NONE) {
  366. // We have to copy to produce the cipher text anyway so use
  367. // the large object code path as it supports that behavior.
  368. //
  369. try (OutputStream os = beginPut(bucket, key, null, null)) {
  370. os.write(data);
  371. }
  372. return;
  373. }
  374. final String md5str = Base64.encodeBytes(newMD5().digest(data));
  375. final String lenstr = String.valueOf(data.length);
  376. for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++) {
  377. final HttpURLConnection c = open("PUT", bucket, key); //$NON-NLS-1$
  378. c.setRequestProperty("Content-Length", lenstr); //$NON-NLS-1$
  379. c.setRequestProperty("Content-MD5", md5str); //$NON-NLS-1$
  380. c.setRequestProperty(X_AMZ_ACL, acl);
  381. authorize(c);
  382. c.setDoOutput(true);
  383. c.setFixedLengthStreamingMode(data.length);
  384. try (OutputStream os = c.getOutputStream()) {
  385. os.write(data);
  386. }
  387. switch (HttpSupport.response(c)) {
  388. case HttpURLConnection.HTTP_OK:
  389. return;
  390. case HttpURLConnection.HTTP_INTERNAL_ERROR:
  391. continue;
  392. default:
  393. throw error(JGitText.get().s3ActionWriting, key, c);
  394. }
  395. }
  396. throw maxAttempts(JGitText.get().s3ActionWriting, key);
  397. }
  398. /**
  399. * Atomically create or replace a single large object.
  400. * <p>
  401. * Initially the returned output stream buffers data into memory, but if the
  402. * total number of written bytes starts to exceed an internal limit the data
  403. * is spooled to a temporary file on the local drive.
  404. * <p>
  405. * Network transmission is attempted only when <code>close()</code> gets
  406. * called at the end of output. Closing the returned stream can therefore
  407. * take significant time, especially if the written content is very large.
  408. * <p>
  409. * End-to-end data integrity is assured by internally computing the MD5
  410. * checksum of the supplied data and transmitting the checksum along with
  411. * the data itself.
  412. *
  413. * @param bucket
  414. * name of the bucket storing the object.
  415. * @param key
  416. * key of the object within its bucket.
  417. * @param monitor
  418. * (optional) progress monitor to post upload completion to
  419. * during the stream's close method.
  420. * @param monitorTask
  421. * (optional) task name to display during the close method.
  422. * @return a stream which accepts the new data, and transmits once closed.
  423. * @throws java.io.IOException
  424. * if encryption was enabled it could not be configured.
  425. */
  426. public OutputStream beginPut(final String bucket, final String key,
  427. final ProgressMonitor monitor, final String monitorTask)
  428. throws IOException {
  429. final MessageDigest md5 = newMD5();
  430. final TemporaryBuffer buffer = new TemporaryBuffer.LocalFile(tmpDir) {
  431. @Override
  432. public void close() throws IOException {
  433. super.close();
  434. try {
  435. putImpl(bucket, key, md5.digest(), this, monitor,
  436. monitorTask);
  437. } finally {
  438. destroy();
  439. }
  440. }
  441. };
  442. return encryption.encrypt(new DigestOutputStream(buffer, md5));
  443. }
  444. void putImpl(final String bucket, final String key,
  445. final byte[] csum, final TemporaryBuffer buf,
  446. ProgressMonitor monitor, String monitorTask) throws IOException {
  447. if (monitor == null)
  448. monitor = NullProgressMonitor.INSTANCE;
  449. if (monitorTask == null)
  450. monitorTask = MessageFormat.format(JGitText.get().progressMonUploading, key);
  451. final String md5str = Base64.encodeBytes(csum);
  452. final long len = buf.length();
  453. for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++) {
  454. final HttpURLConnection c = open("PUT", bucket, key); //$NON-NLS-1$
  455. c.setFixedLengthStreamingMode(len);
  456. c.setRequestProperty("Content-MD5", md5str); //$NON-NLS-1$
  457. c.setRequestProperty(X_AMZ_ACL, acl);
  458. encryption.request(c, X_AMZ_META);
  459. authorize(c);
  460. c.setDoOutput(true);
  461. monitor.beginTask(monitorTask, (int) (len / 1024));
  462. try (OutputStream os = c.getOutputStream()) {
  463. buf.writeTo(os, monitor);
  464. } finally {
  465. monitor.endTask();
  466. }
  467. switch (HttpSupport.response(c)) {
  468. case HttpURLConnection.HTTP_OK:
  469. return;
  470. case HttpURLConnection.HTTP_INTERNAL_ERROR:
  471. continue;
  472. default:
  473. throw error(JGitText.get().s3ActionWriting, key, c);
  474. }
  475. }
  476. throw maxAttempts(JGitText.get().s3ActionWriting, key);
  477. }
  478. IOException error(final String action, final String key,
  479. final HttpURLConnection c) throws IOException {
  480. final IOException err = new IOException(MessageFormat.format(
  481. JGitText.get().amazonS3ActionFailed, action, key,
  482. Integer.valueOf(HttpSupport.response(c)),
  483. c.getResponseMessage()));
  484. if (c.getErrorStream() == null) {
  485. return err;
  486. }
  487. try (InputStream errorStream = c.getErrorStream()) {
  488. final ByteArrayOutputStream b = new ByteArrayOutputStream();
  489. byte[] buf = new byte[2048];
  490. for (;;) {
  491. final int n = errorStream.read(buf);
  492. if (n < 0) {
  493. break;
  494. }
  495. if (n > 0) {
  496. b.write(buf, 0, n);
  497. }
  498. }
  499. buf = b.toByteArray();
  500. if (buf.length > 0) {
  501. err.initCause(new IOException("\n" + new String(buf))); //$NON-NLS-1$
  502. }
  503. }
  504. return err;
  505. }
  506. IOException maxAttempts(String action, String key) {
  507. return new IOException(MessageFormat.format(
  508. JGitText.get().amazonS3ActionFailedGivingUp, action, key,
  509. Integer.valueOf(maxAttempts)));
  510. }
  511. private HttpURLConnection open(final String method, final String bucket,
  512. final String key) throws IOException {
  513. final Map<String, String> noArgs = Collections.emptyMap();
  514. return open(method, bucket, key, noArgs);
  515. }
  516. HttpURLConnection open(final String method, final String bucket,
  517. final String key, final Map<String, String> args)
  518. throws IOException {
  519. final StringBuilder urlstr = new StringBuilder();
  520. urlstr.append("http://"); //$NON-NLS-1$
  521. urlstr.append(bucket);
  522. urlstr.append('.');
  523. urlstr.append(domain);
  524. urlstr.append('/');
  525. if (key.length() > 0)
  526. HttpSupport.encode(urlstr, key);
  527. if (!args.isEmpty()) {
  528. final Iterator<Map.Entry<String, String>> i;
  529. urlstr.append('?');
  530. i = args.entrySet().iterator();
  531. while (i.hasNext()) {
  532. final Map.Entry<String, String> e = i.next();
  533. urlstr.append(e.getKey());
  534. urlstr.append('=');
  535. HttpSupport.encode(urlstr, e.getValue());
  536. if (i.hasNext())
  537. urlstr.append('&');
  538. }
  539. }
  540. final URL url = new URL(urlstr.toString());
  541. final Proxy proxy = HttpSupport.proxyFor(proxySelector, url);
  542. final HttpURLConnection c;
  543. c = (HttpURLConnection) url.openConnection(proxy);
  544. c.setRequestMethod(method);
  545. c.setRequestProperty("User-Agent", "jgit/1.0"); //$NON-NLS-1$ //$NON-NLS-2$
  546. c.setRequestProperty("Date", httpNow()); //$NON-NLS-1$
  547. return c;
  548. }
  549. void authorize(HttpURLConnection c) throws IOException {
  550. final Map<String, List<String>> reqHdr = c.getRequestProperties();
  551. final SortedMap<String, String> sigHdr = new TreeMap<>();
  552. for (Map.Entry<String, List<String>> entry : reqHdr.entrySet()) {
  553. final String hdr = entry.getKey();
  554. if (isSignedHeader(hdr))
  555. sigHdr.put(StringUtils.toLowerCase(hdr), toCleanString(entry.getValue()));
  556. }
  557. final StringBuilder s = new StringBuilder();
  558. s.append(c.getRequestMethod());
  559. s.append('\n');
  560. s.append(remove(sigHdr, "content-md5")); //$NON-NLS-1$
  561. s.append('\n');
  562. s.append(remove(sigHdr, "content-type")); //$NON-NLS-1$
  563. s.append('\n');
  564. s.append(remove(sigHdr, "date")); //$NON-NLS-1$
  565. s.append('\n');
  566. for (Map.Entry<String, String> e : sigHdr.entrySet()) {
  567. s.append(e.getKey());
  568. s.append(':');
  569. s.append(e.getValue());
  570. s.append('\n');
  571. }
  572. final String host = c.getURL().getHost();
  573. s.append('/');
  574. s.append(host.substring(0, host.length() - domain.length() - 1));
  575. s.append(c.getURL().getPath());
  576. final String sec;
  577. try {
  578. final Mac m = Mac.getInstance(HMAC);
  579. m.init(privateKey);
  580. sec = Base64.encodeBytes(m.doFinal(s.toString().getBytes(UTF_8)));
  581. } catch (NoSuchAlgorithmException e) {
  582. throw new IOException(MessageFormat.format(JGitText.get().noHMACsupport, HMAC, e.getMessage()));
  583. } catch (InvalidKeyException e) {
  584. throw new IOException(MessageFormat.format(JGitText.get().invalidKey, e.getMessage()));
  585. }
  586. c.setRequestProperty("Authorization", "AWS " + publicKey + ":" + sec); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  587. }
  588. static Properties properties(File authFile)
  589. throws FileNotFoundException, IOException {
  590. final Properties p = new Properties();
  591. try (FileInputStream in = new FileInputStream(authFile)) {
  592. p.load(in);
  593. }
  594. return p;
  595. }
  596. private final class ListParser extends DefaultHandler {
  597. final List<String> entries = new ArrayList<>();
  598. private final String bucket;
  599. private final String prefix;
  600. boolean truncated;
  601. private StringBuilder data;
  602. ListParser(String bn, String p) {
  603. bucket = bn;
  604. prefix = p;
  605. }
  606. void list() throws IOException {
  607. final Map<String, String> args = new TreeMap<>();
  608. if (prefix.length() > 0)
  609. args.put("prefix", prefix); //$NON-NLS-1$
  610. if (!entries.isEmpty())
  611. args.put("marker", prefix + entries.get(entries.size() - 1)); //$NON-NLS-1$
  612. for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++) {
  613. final HttpURLConnection c = open("GET", bucket, "", args); //$NON-NLS-1$ //$NON-NLS-2$
  614. authorize(c);
  615. switch (HttpSupport.response(c)) {
  616. case HttpURLConnection.HTTP_OK:
  617. truncated = false;
  618. data = null;
  619. final XMLReader xr;
  620. try {
  621. xr = XMLReaderFactory.createXMLReader();
  622. } catch (SAXException e) {
  623. throw new IOException(JGitText.get().noXMLParserAvailable);
  624. }
  625. xr.setContentHandler(this);
  626. try (InputStream in = c.getInputStream()) {
  627. xr.parse(new InputSource(in));
  628. } catch (SAXException parsingError) {
  629. throw new IOException(
  630. MessageFormat.format(
  631. JGitText.get().errorListing, prefix),
  632. parsingError);
  633. }
  634. return;
  635. case HttpURLConnection.HTTP_INTERNAL_ERROR:
  636. continue;
  637. default:
  638. throw AmazonS3.this.error("Listing", prefix, c); //$NON-NLS-1$
  639. }
  640. }
  641. throw maxAttempts("Listing", prefix); //$NON-NLS-1$
  642. }
  643. @Override
  644. public void startElement(final String uri, final String name,
  645. final String qName, final Attributes attributes)
  646. throws SAXException {
  647. if ("Key".equals(name) || "IsTruncated".equals(name)) //$NON-NLS-1$ //$NON-NLS-2$
  648. data = new StringBuilder();
  649. }
  650. @Override
  651. public void ignorableWhitespace(final char[] ch, final int s,
  652. final int n) throws SAXException {
  653. if (data != null)
  654. data.append(ch, s, n);
  655. }
  656. @Override
  657. public void characters(char[] ch, int s, int n)
  658. throws SAXException {
  659. if (data != null)
  660. data.append(ch, s, n);
  661. }
  662. @Override
  663. public void endElement(final String uri, final String name,
  664. final String qName) throws SAXException {
  665. if ("Key".equals(name)) //$NON-NLS-1$
  666. entries.add(data.toString().substring(prefix.length()));
  667. else if ("IsTruncated".equals(name)) //$NON-NLS-1$
  668. truncated = StringUtils.equalsIgnoreCase("true", data.toString()); //$NON-NLS-1$
  669. data = null;
  670. }
  671. }
  672. }