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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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(final 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(final List<String> list) {
  125. final StringBuilder s = new StringBuilder();
  126. for (final 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(final Map<String, String> m, final 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. */
  211. public AmazonS3(final Properties props) {
  212. domain = props.getProperty(Keys.DOMAIN, "s3.amazonaws.com"); //$NON-NLS-1$
  213. publicKey = props.getProperty(Keys.ACCESS_KEY);
  214. if (publicKey == null)
  215. throw new IllegalArgumentException(JGitText.get().missingAccesskey);
  216. final String secret = props.getProperty(Keys.SECRET_KEY);
  217. if (secret == null)
  218. throw new IllegalArgumentException(JGitText.get().missingSecretkey);
  219. privateKey = new SecretKeySpec(Constants.encodeASCII(secret), HMAC);
  220. final String pacl = props.getProperty(Keys.ACL, "PRIVATE"); //$NON-NLS-1$
  221. if (StringUtils.equalsIgnoreCase("PRIVATE", pacl)) //$NON-NLS-1$
  222. acl = "private"; //$NON-NLS-1$
  223. else if (StringUtils.equalsIgnoreCase("PUBLIC", pacl)) //$NON-NLS-1$
  224. acl = "public-read"; //$NON-NLS-1$
  225. else if (StringUtils.equalsIgnoreCase("PUBLIC-READ", pacl)) //$NON-NLS-1$
  226. acl = "public-read"; //$NON-NLS-1$
  227. else if (StringUtils.equalsIgnoreCase("PUBLIC_READ", pacl)) //$NON-NLS-1$
  228. acl = "public-read"; //$NON-NLS-1$
  229. else
  230. throw new IllegalArgumentException("Invalid acl: " + pacl); //$NON-NLS-1$
  231. try {
  232. encryption = WalkEncryption.instance(props);
  233. } catch (GeneralSecurityException e) {
  234. throw new IllegalArgumentException(JGitText.get().invalidEncryption, e);
  235. }
  236. maxAttempts = Integer
  237. .parseInt(props.getProperty(Keys.HTTP_RETRY, "3")); //$NON-NLS-1$
  238. proxySelector = ProxySelector.getDefault();
  239. String tmp = props.getProperty(Keys.TMP_DIR);
  240. tmpDir = tmp != null && tmp.length() > 0 ? new File(tmp) : null;
  241. }
  242. /**
  243. * Get the content of a bucket object.
  244. *
  245. * @param bucket
  246. * name of the bucket storing the object.
  247. * @param key
  248. * key of the object within its bucket.
  249. * @return connection to stream the content of the object. The request
  250. * properties of the connection may not be modified by the caller as
  251. * the request parameters have already been signed.
  252. * @throws IOException
  253. * sending the request was not possible.
  254. */
  255. public URLConnection get(final String bucket, final String key)
  256. throws IOException {
  257. for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++) {
  258. final HttpURLConnection c = open("GET", bucket, key); //$NON-NLS-1$
  259. authorize(c);
  260. switch (HttpSupport.response(c)) {
  261. case HttpURLConnection.HTTP_OK:
  262. encryption.validate(c, X_AMZ_META);
  263. return c;
  264. case HttpURLConnection.HTTP_NOT_FOUND:
  265. throw new FileNotFoundException(key);
  266. case HttpURLConnection.HTTP_INTERNAL_ERROR:
  267. continue;
  268. default:
  269. throw error(JGitText.get().s3ActionReading, key, c);
  270. }
  271. }
  272. throw maxAttempts(JGitText.get().s3ActionReading, key);
  273. }
  274. /**
  275. * Decrypt an input stream from {@link #get(String, String)}.
  276. *
  277. * @param u
  278. * connection previously created by {@link #get(String, String)}}.
  279. * @return stream to read plain text from.
  280. * @throws IOException
  281. * decryption could not be configured.
  282. */
  283. public InputStream decrypt(final URLConnection u) throws IOException {
  284. return encryption.decrypt(u.getInputStream());
  285. }
  286. /**
  287. * List the names of keys available within a bucket.
  288. * <p>
  289. * This method is primarily meant for obtaining a "recursive directory
  290. * listing" rooted under the specified bucket and prefix location.
  291. *
  292. * @param bucket
  293. * name of the bucket whose objects should be listed.
  294. * @param prefix
  295. * common prefix to filter the results by. Must not be null.
  296. * Supplying the empty string will list all keys in the bucket.
  297. * Supplying a non-empty string will act as though a trailing '/'
  298. * appears in prefix, even if it does not.
  299. * @return list of keys starting with <code>prefix</code>, after removing
  300. * <code>prefix</code> (or <code>prefix + "/"</code>)from all
  301. * of them.
  302. * @throws IOException
  303. * sending the request was not possible, or the response XML
  304. * document could not be parsed properly.
  305. */
  306. public List<String> list(final String bucket, String prefix)
  307. throws IOException {
  308. if (prefix.length() > 0 && !prefix.endsWith("/")) //$NON-NLS-1$
  309. prefix += "/"; //$NON-NLS-1$
  310. final ListParser lp = new ListParser(bucket, prefix);
  311. do {
  312. lp.list();
  313. } while (lp.truncated);
  314. return lp.entries;
  315. }
  316. /**
  317. * Delete a single object.
  318. * <p>
  319. * Deletion always succeeds, even if the object does not exist.
  320. *
  321. * @param bucket
  322. * name of the bucket storing the object.
  323. * @param key
  324. * key of the object within its bucket.
  325. * @throws IOException
  326. * deletion failed due to communications error.
  327. */
  328. public void delete(final String bucket, final String key)
  329. throws IOException {
  330. for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++) {
  331. final HttpURLConnection c = open("DELETE", bucket, key); //$NON-NLS-1$
  332. authorize(c);
  333. switch (HttpSupport.response(c)) {
  334. case HttpURLConnection.HTTP_NO_CONTENT:
  335. return;
  336. case HttpURLConnection.HTTP_INTERNAL_ERROR:
  337. continue;
  338. default:
  339. throw error(JGitText.get().s3ActionDeletion, key, c);
  340. }
  341. }
  342. throw maxAttempts(JGitText.get().s3ActionDeletion, key);
  343. }
  344. /**
  345. * Atomically create or replace a single small object.
  346. * <p>
  347. * This form is only suitable for smaller contents, where the caller can
  348. * reasonable fit the entire thing into memory.
  349. * <p>
  350. * End-to-end data integrity is assured by internally computing the MD5
  351. * checksum of the supplied data and transmitting the checksum along with
  352. * the data itself.
  353. *
  354. * @param bucket
  355. * name of the bucket storing the object.
  356. * @param key
  357. * key of the object within its bucket.
  358. * @param data
  359. * new data content for the object. Must not be null. Zero length
  360. * array will create a zero length object.
  361. * @throws IOException
  362. * creation/updating failed due to communications error.
  363. */
  364. public void put(final String bucket, final String key, final byte[] data)
  365. throws IOException {
  366. if (encryption != WalkEncryption.NONE) {
  367. // We have to copy to produce the cipher text anyway so use
  368. // the large object code path as it supports that behavior.
  369. //
  370. final OutputStream os = beginPut(bucket, key, null, null);
  371. os.write(data);
  372. os.close();
  373. return;
  374. }
  375. final String md5str = Base64.encodeBytes(newMD5().digest(data));
  376. final String lenstr = String.valueOf(data.length);
  377. for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++) {
  378. final HttpURLConnection c = open("PUT", bucket, key); //$NON-NLS-1$
  379. c.setRequestProperty("Content-Length", lenstr); //$NON-NLS-1$
  380. c.setRequestProperty("Content-MD5", md5str); //$NON-NLS-1$
  381. c.setRequestProperty(X_AMZ_ACL, acl);
  382. authorize(c);
  383. c.setDoOutput(true);
  384. c.setFixedLengthStreamingMode(data.length);
  385. final OutputStream os = c.getOutputStream();
  386. try {
  387. os.write(data);
  388. } finally {
  389. os.close();
  390. }
  391. switch (HttpSupport.response(c)) {
  392. case HttpURLConnection.HTTP_OK:
  393. return;
  394. case HttpURLConnection.HTTP_INTERNAL_ERROR:
  395. continue;
  396. default:
  397. throw error(JGitText.get().s3ActionWriting, key, c);
  398. }
  399. }
  400. throw maxAttempts(JGitText.get().s3ActionWriting, key);
  401. }
  402. /**
  403. * Atomically create or replace a single large object.
  404. * <p>
  405. * Initially the returned output stream buffers data into memory, but if the
  406. * total number of written bytes starts to exceed an internal limit the data
  407. * is spooled to a temporary file on the local drive.
  408. * <p>
  409. * Network transmission is attempted only when <code>close()</code> gets
  410. * called at the end of output. Closing the returned stream can therefore
  411. * take significant time, especially if the written content is very large.
  412. * <p>
  413. * End-to-end data integrity is assured by internally computing the MD5
  414. * checksum of the supplied data and transmitting the checksum along with
  415. * the data itself.
  416. *
  417. * @param bucket
  418. * name of the bucket storing the object.
  419. * @param key
  420. * key of the object within its bucket.
  421. * @param monitor
  422. * (optional) progress monitor to post upload completion to
  423. * during the stream's close method.
  424. * @param monitorTask
  425. * (optional) task name to display during the close method.
  426. * @return a stream which accepts the new data, and transmits once closed.
  427. * @throws IOException
  428. * if encryption was enabled it could not be configured.
  429. */
  430. public OutputStream beginPut(final String bucket, final String key,
  431. final ProgressMonitor monitor, final String monitorTask)
  432. throws IOException {
  433. final MessageDigest md5 = newMD5();
  434. final TemporaryBuffer buffer = new TemporaryBuffer.LocalFile(tmpDir) {
  435. @Override
  436. public void close() throws IOException {
  437. super.close();
  438. try {
  439. putImpl(bucket, key, md5.digest(), this, monitor,
  440. monitorTask);
  441. } finally {
  442. destroy();
  443. }
  444. }
  445. };
  446. return encryption.encrypt(new DigestOutputStream(buffer, md5));
  447. }
  448. void putImpl(final String bucket, final String key,
  449. final byte[] csum, final TemporaryBuffer buf,
  450. ProgressMonitor monitor, String monitorTask) throws IOException {
  451. if (monitor == null)
  452. monitor = NullProgressMonitor.INSTANCE;
  453. if (monitorTask == null)
  454. monitorTask = MessageFormat.format(JGitText.get().progressMonUploading, key);
  455. final String md5str = Base64.encodeBytes(csum);
  456. final long len = buf.length();
  457. for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++) {
  458. final HttpURLConnection c = open("PUT", bucket, key); //$NON-NLS-1$
  459. c.setFixedLengthStreamingMode(len);
  460. c.setRequestProperty("Content-MD5", md5str); //$NON-NLS-1$
  461. c.setRequestProperty(X_AMZ_ACL, acl);
  462. encryption.request(c, X_AMZ_META);
  463. authorize(c);
  464. c.setDoOutput(true);
  465. monitor.beginTask(monitorTask, (int) (len / 1024));
  466. final OutputStream os = c.getOutputStream();
  467. try {
  468. buf.writeTo(os, monitor);
  469. } finally {
  470. monitor.endTask();
  471. os.close();
  472. }
  473. switch (HttpSupport.response(c)) {
  474. case HttpURLConnection.HTTP_OK:
  475. return;
  476. case HttpURLConnection.HTTP_INTERNAL_ERROR:
  477. continue;
  478. default:
  479. throw error(JGitText.get().s3ActionWriting, key, c);
  480. }
  481. }
  482. throw maxAttempts(JGitText.get().s3ActionWriting, key);
  483. }
  484. IOException error(final String action, final String key,
  485. final HttpURLConnection c) throws IOException {
  486. final IOException err = new IOException(MessageFormat.format(
  487. JGitText.get().amazonS3ActionFailed, action, key,
  488. Integer.valueOf(HttpSupport.response(c)),
  489. c.getResponseMessage()));
  490. final InputStream errorStream = c.getErrorStream();
  491. if (errorStream == null) {
  492. return err;
  493. }
  494. try {
  495. final ByteArrayOutputStream b = new ByteArrayOutputStream();
  496. byte[] buf = new byte[2048];
  497. for (;;) {
  498. final int n = errorStream.read(buf);
  499. if (n < 0) {
  500. break;
  501. }
  502. if (n > 0) {
  503. b.write(buf, 0, n);
  504. }
  505. }
  506. buf = b.toByteArray();
  507. if (buf.length > 0) {
  508. err.initCause(new IOException("\n" + new String(buf))); //$NON-NLS-1$
  509. }
  510. } finally {
  511. errorStream.close();
  512. }
  513. return err;
  514. }
  515. IOException maxAttempts(final String action, final String key) {
  516. return new IOException(MessageFormat.format(
  517. JGitText.get().amazonS3ActionFailedGivingUp, action, key,
  518. Integer.valueOf(maxAttempts)));
  519. }
  520. private HttpURLConnection open(final String method, final String bucket,
  521. final String key) throws IOException {
  522. final Map<String, String> noArgs = Collections.emptyMap();
  523. return open(method, bucket, key, noArgs);
  524. }
  525. HttpURLConnection open(final String method, final String bucket,
  526. final String key, final Map<String, String> args)
  527. throws IOException {
  528. final StringBuilder urlstr = new StringBuilder();
  529. urlstr.append("http://"); //$NON-NLS-1$
  530. urlstr.append(bucket);
  531. urlstr.append('.');
  532. urlstr.append(domain);
  533. urlstr.append('/');
  534. if (key.length() > 0)
  535. HttpSupport.encode(urlstr, key);
  536. if (!args.isEmpty()) {
  537. final Iterator<Map.Entry<String, String>> i;
  538. urlstr.append('?');
  539. i = args.entrySet().iterator();
  540. while (i.hasNext()) {
  541. final Map.Entry<String, String> e = i.next();
  542. urlstr.append(e.getKey());
  543. urlstr.append('=');
  544. HttpSupport.encode(urlstr, e.getValue());
  545. if (i.hasNext())
  546. urlstr.append('&');
  547. }
  548. }
  549. final URL url = new URL(urlstr.toString());
  550. final Proxy proxy = HttpSupport.proxyFor(proxySelector, url);
  551. final HttpURLConnection c;
  552. c = (HttpURLConnection) url.openConnection(proxy);
  553. c.setRequestMethod(method);
  554. c.setRequestProperty("User-Agent", "jgit/1.0"); //$NON-NLS-1$ //$NON-NLS-2$
  555. c.setRequestProperty("Date", httpNow()); //$NON-NLS-1$
  556. return c;
  557. }
  558. void authorize(final HttpURLConnection c) throws IOException {
  559. final Map<String, List<String>> reqHdr = c.getRequestProperties();
  560. final SortedMap<String, String> sigHdr = new TreeMap<>();
  561. for (final Map.Entry<String, List<String>> entry : reqHdr.entrySet()) {
  562. final String hdr = entry.getKey();
  563. if (isSignedHeader(hdr))
  564. sigHdr.put(StringUtils.toLowerCase(hdr), toCleanString(entry.getValue()));
  565. }
  566. final StringBuilder s = new StringBuilder();
  567. s.append(c.getRequestMethod());
  568. s.append('\n');
  569. s.append(remove(sigHdr, "content-md5")); //$NON-NLS-1$
  570. s.append('\n');
  571. s.append(remove(sigHdr, "content-type")); //$NON-NLS-1$
  572. s.append('\n');
  573. s.append(remove(sigHdr, "date")); //$NON-NLS-1$
  574. s.append('\n');
  575. for (final Map.Entry<String, String> e : sigHdr.entrySet()) {
  576. s.append(e.getKey());
  577. s.append(':');
  578. s.append(e.getValue());
  579. s.append('\n');
  580. }
  581. final String host = c.getURL().getHost();
  582. s.append('/');
  583. s.append(host.substring(0, host.length() - domain.length() - 1));
  584. s.append(c.getURL().getPath());
  585. final String sec;
  586. try {
  587. final Mac m = Mac.getInstance(HMAC);
  588. m.init(privateKey);
  589. sec = Base64.encodeBytes(m.doFinal(s.toString().getBytes(UTF_8)));
  590. } catch (NoSuchAlgorithmException e) {
  591. throw new IOException(MessageFormat.format(JGitText.get().noHMACsupport, HMAC, e.getMessage()));
  592. } catch (InvalidKeyException e) {
  593. throw new IOException(MessageFormat.format(JGitText.get().invalidKey, e.getMessage()));
  594. }
  595. c.setRequestProperty("Authorization", "AWS " + publicKey + ":" + sec); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  596. }
  597. static Properties properties(final File authFile)
  598. throws FileNotFoundException, IOException {
  599. final Properties p = new Properties();
  600. final FileInputStream in = new FileInputStream(authFile);
  601. try {
  602. p.load(in);
  603. } finally {
  604. in.close();
  605. }
  606. return p;
  607. }
  608. private final class ListParser extends DefaultHandler {
  609. final List<String> entries = new ArrayList<>();
  610. private final String bucket;
  611. private final String prefix;
  612. boolean truncated;
  613. private StringBuilder data;
  614. ListParser(final String bn, final String p) {
  615. bucket = bn;
  616. prefix = p;
  617. }
  618. void list() throws IOException {
  619. final Map<String, String> args = new TreeMap<>();
  620. if (prefix.length() > 0)
  621. args.put("prefix", prefix); //$NON-NLS-1$
  622. if (!entries.isEmpty())
  623. args.put("marker", prefix + entries.get(entries.size() - 1)); //$NON-NLS-1$
  624. for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++) {
  625. final HttpURLConnection c = open("GET", bucket, "", args); //$NON-NLS-1$ //$NON-NLS-2$
  626. authorize(c);
  627. switch (HttpSupport.response(c)) {
  628. case HttpURLConnection.HTTP_OK:
  629. truncated = false;
  630. data = null;
  631. final XMLReader xr;
  632. try {
  633. xr = XMLReaderFactory.createXMLReader();
  634. } catch (SAXException e) {
  635. throw new IOException(JGitText.get().noXMLParserAvailable);
  636. }
  637. xr.setContentHandler(this);
  638. final InputStream in = c.getInputStream();
  639. try {
  640. xr.parse(new InputSource(in));
  641. } catch (SAXException parsingError) {
  642. final IOException p;
  643. p = new IOException(MessageFormat.format(JGitText.get().errorListing, prefix));
  644. p.initCause(parsingError);
  645. throw p;
  646. } finally {
  647. in.close();
  648. }
  649. return;
  650. case HttpURLConnection.HTTP_INTERNAL_ERROR:
  651. continue;
  652. default:
  653. throw AmazonS3.this.error("Listing", prefix, c); //$NON-NLS-1$
  654. }
  655. }
  656. throw maxAttempts("Listing", prefix); //$NON-NLS-1$
  657. }
  658. @Override
  659. public void startElement(final String uri, final String name,
  660. final String qName, final Attributes attributes)
  661. throws SAXException {
  662. if ("Key".equals(name) || "IsTruncated".equals(name)) //$NON-NLS-1$ //$NON-NLS-2$
  663. data = new StringBuilder();
  664. }
  665. @Override
  666. public void ignorableWhitespace(final char[] ch, final int s,
  667. final int n) throws SAXException {
  668. if (data != null)
  669. data.append(ch, s, n);
  670. }
  671. @Override
  672. public void characters(final char[] ch, final int s, final int n)
  673. throws SAXException {
  674. if (data != null)
  675. data.append(ch, s, n);
  676. }
  677. @Override
  678. public void endElement(final String uri, final String name,
  679. final String qName) throws SAXException {
  680. if ("Key".equals(name)) //$NON-NLS-1$
  681. entries.add(data.toString().substring(prefix.length()));
  682. else if ("IsTruncated".equals(name)) //$NON-NLS-1$
  683. truncated = StringUtils.equalsIgnoreCase("true", data.toString()); //$NON-NLS-1$
  684. data = null;
  685. }
  686. }
  687. }