Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

AmazonS3.java 25KB

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