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.

TransportHttp.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.transport;
  45. import static org.eclipse.jgit.util.HttpSupport.ENCODING_GZIP;
  46. import static org.eclipse.jgit.util.HttpSupport.HDR_ACCEPT;
  47. import static org.eclipse.jgit.util.HttpSupport.HDR_ACCEPT_ENCODING;
  48. import static org.eclipse.jgit.util.HttpSupport.HDR_CONTENT_ENCODING;
  49. import static org.eclipse.jgit.util.HttpSupport.HDR_CONTENT_TYPE;
  50. import static org.eclipse.jgit.util.HttpSupport.HDR_PRAGMA;
  51. import static org.eclipse.jgit.util.HttpSupport.HDR_USER_AGENT;
  52. import static org.eclipse.jgit.util.HttpSupport.METHOD_POST;
  53. import java.io.BufferedReader;
  54. import java.io.ByteArrayInputStream;
  55. import java.io.FileNotFoundException;
  56. import java.io.IOException;
  57. import java.io.InputStream;
  58. import java.io.InputStreamReader;
  59. import java.io.OutputStream;
  60. import java.net.HttpURLConnection;
  61. import java.net.MalformedURLException;
  62. import java.net.Proxy;
  63. import java.net.ProxySelector;
  64. import java.net.URL;
  65. import java.util.ArrayList;
  66. import java.util.Collection;
  67. import java.util.Map;
  68. import java.util.Set;
  69. import java.util.TreeMap;
  70. import java.util.zip.GZIPInputStream;
  71. import java.util.zip.GZIPOutputStream;
  72. import org.eclipse.jgit.errors.NoRemoteRepositoryException;
  73. import org.eclipse.jgit.errors.NotSupportedException;
  74. import org.eclipse.jgit.errors.PackProtocolException;
  75. import org.eclipse.jgit.errors.TransportException;
  76. import org.eclipse.jgit.lib.Config;
  77. import org.eclipse.jgit.lib.Constants;
  78. import org.eclipse.jgit.lib.ObjectId;
  79. import org.eclipse.jgit.lib.ObjectIdRef;
  80. import org.eclipse.jgit.lib.ProgressMonitor;
  81. import org.eclipse.jgit.lib.Ref;
  82. import org.eclipse.jgit.lib.RefDirectory;
  83. import org.eclipse.jgit.lib.Repository;
  84. import org.eclipse.jgit.lib.SymbolicRef;
  85. import org.eclipse.jgit.lib.Config.SectionParser;
  86. import org.eclipse.jgit.util.HttpSupport;
  87. import org.eclipse.jgit.util.IO;
  88. import org.eclipse.jgit.util.RawParseUtils;
  89. import org.eclipse.jgit.util.TemporaryBuffer;
  90. import org.eclipse.jgit.util.io.DisabledOutputStream;
  91. import org.eclipse.jgit.util.io.UnionInputStream;
  92. /**
  93. * Transport over HTTP and FTP protocols.
  94. * <p>
  95. * If the transport is using HTTP and the remote HTTP service is Git-aware
  96. * (speaks the "smart-http protocol") this client will automatically take
  97. * advantage of the additional Git-specific HTTP extensions. If the remote
  98. * service does not support these extensions, the client will degrade to direct
  99. * file fetching.
  100. * <p>
  101. * If the remote (server side) repository does not have the specialized Git
  102. * support, object files are retrieved directly through standard HTTP GET (or
  103. * binary FTP GET) requests. This make it easy to serve a Git repository through
  104. * a standard web host provider that does not offer specific support for Git.
  105. *
  106. * @see WalkFetchConnection
  107. */
  108. public class TransportHttp extends HttpTransport implements WalkTransport,
  109. PackTransport {
  110. private static final String SVC_UPLOAD_PACK = "git-upload-pack";
  111. private static final String SVC_RECEIVE_PACK = "git-receive-pack";
  112. private static final String userAgent = computeUserAgent();
  113. static boolean canHandle(final URIish uri) {
  114. if (!uri.isRemote())
  115. return false;
  116. final String s = uri.getScheme();
  117. return "http".equals(s) || "https".equals(s) || "ftp".equals(s);
  118. }
  119. private static String computeUserAgent() {
  120. String version;
  121. final Package pkg = TransportHttp.class.getPackage();
  122. if (pkg != null && pkg.getImplementationVersion() != null) {
  123. version = pkg.getImplementationVersion();
  124. } else {
  125. version = "unknown"; //$NON-NLS-1$
  126. }
  127. return "JGit/" + version; //$NON-NLS-1$
  128. }
  129. private static final Config.SectionParser<HttpConfig> HTTP_KEY = new SectionParser<HttpConfig>() {
  130. public HttpConfig parse(final Config cfg) {
  131. return new HttpConfig(cfg);
  132. }
  133. };
  134. private static class HttpConfig {
  135. final int postBuffer;
  136. HttpConfig(final Config rc) {
  137. postBuffer = rc.getInt("http", "postbuffer", 1 * 1024 * 1024);
  138. }
  139. }
  140. private final URL baseUrl;
  141. private final URL objectsUrl;
  142. private final HttpConfig http;
  143. private final ProxySelector proxySelector;
  144. private boolean useSmartHttp = true;
  145. TransportHttp(final Repository local, final URIish uri)
  146. throws NotSupportedException {
  147. super(local, uri);
  148. try {
  149. String uriString = uri.toString();
  150. if (!uriString.endsWith("/"))
  151. uriString += "/";
  152. baseUrl = new URL(uriString);
  153. objectsUrl = new URL(baseUrl, "objects/");
  154. } catch (MalformedURLException e) {
  155. throw new NotSupportedException("Invalid URL " + uri, e);
  156. }
  157. http = local.getConfig().get(HTTP_KEY);
  158. proxySelector = ProxySelector.getDefault();
  159. }
  160. /**
  161. * Toggle whether or not smart HTTP transport should be used.
  162. * <p>
  163. * This flag exists primarily to support backwards compatibility testing
  164. * within a testing framework, there is no need to modify it in most
  165. * applications.
  166. *
  167. * @param on
  168. * if {@code true} (default), smart HTTP is enabled.
  169. */
  170. public void setUseSmartHttp(final boolean on) {
  171. useSmartHttp = on;
  172. }
  173. @Override
  174. public FetchConnection openFetch() throws TransportException,
  175. NotSupportedException {
  176. final String service = SVC_UPLOAD_PACK;
  177. try {
  178. final HttpURLConnection c = connect(service);
  179. final InputStream in = openInputStream(c);
  180. try {
  181. if (isSmartHttp(c, service)) {
  182. readSmartHeaders(in, service);
  183. return new SmartHttpFetchConnection(in);
  184. } else {
  185. // Assume this server doesn't support smart HTTP fetch
  186. // and fall back on dumb object walking.
  187. //
  188. return newDumbConnection(in);
  189. }
  190. } finally {
  191. in.close();
  192. }
  193. } catch (NotSupportedException err) {
  194. throw err;
  195. } catch (TransportException err) {
  196. throw err;
  197. } catch (IOException err) {
  198. throw new TransportException(uri, "error reading info/refs", err);
  199. }
  200. }
  201. private FetchConnection newDumbConnection(InputStream in)
  202. throws IOException, PackProtocolException {
  203. HttpObjectDB d = new HttpObjectDB(objectsUrl);
  204. BufferedReader br = toBufferedReader(in);
  205. Map<String, Ref> refs;
  206. try {
  207. refs = d.readAdvertisedImpl(br);
  208. } finally {
  209. br.close();
  210. }
  211. if (!refs.containsKey(Constants.HEAD)) {
  212. // If HEAD was not published in the info/refs file (it usually
  213. // is not there) download HEAD by itself as a loose file and do
  214. // the resolution by hand.
  215. //
  216. HttpURLConnection conn = httpOpen(new URL(baseUrl, Constants.HEAD));
  217. int status = HttpSupport.response(conn);
  218. switch (status) {
  219. case HttpURLConnection.HTTP_OK: {
  220. br = toBufferedReader(openInputStream(conn));
  221. try {
  222. String line = br.readLine();
  223. if (line != null && line.startsWith(RefDirectory.SYMREF)) {
  224. String target = line.substring(RefDirectory.SYMREF.length());
  225. Ref r = refs.get(target);
  226. if (r == null)
  227. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  228. r = new SymbolicRef(Constants.HEAD, r);
  229. refs.put(r.getName(), r);
  230. } else if (line != null && ObjectId.isId(line)) {
  231. Ref r = new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK,
  232. Constants.HEAD, ObjectId.fromString(line));
  233. refs.put(r.getName(), r);
  234. }
  235. } finally {
  236. br.close();
  237. }
  238. break;
  239. }
  240. case HttpURLConnection.HTTP_NOT_FOUND:
  241. break;
  242. default:
  243. throw new TransportException(uri, "cannot read HEAD: " + status
  244. + " " + conn.getResponseMessage());
  245. }
  246. }
  247. WalkFetchConnection wfc = new WalkFetchConnection(this, d);
  248. wfc.available(refs);
  249. return wfc;
  250. }
  251. private BufferedReader toBufferedReader(InputStream in) {
  252. return new BufferedReader(new InputStreamReader(in, Constants.CHARSET));
  253. }
  254. @Override
  255. public PushConnection openPush() throws NotSupportedException,
  256. TransportException {
  257. final String service = SVC_RECEIVE_PACK;
  258. try {
  259. final HttpURLConnection c = connect(service);
  260. final InputStream in = openInputStream(c);
  261. try {
  262. if (isSmartHttp(c, service)) {
  263. readSmartHeaders(in, service);
  264. return new SmartHttpPushConnection(in);
  265. } else if (!useSmartHttp) {
  266. final String msg = "smart HTTP push disabled";
  267. throw new NotSupportedException(msg);
  268. } else {
  269. final String msg = "remote does not support smart HTTP push";
  270. throw new NotSupportedException(msg);
  271. }
  272. } finally {
  273. in.close();
  274. }
  275. } catch (NotSupportedException err) {
  276. throw err;
  277. } catch (TransportException err) {
  278. throw err;
  279. } catch (IOException err) {
  280. throw new TransportException(uri, "error reading info/refs", err);
  281. }
  282. }
  283. @Override
  284. public void close() {
  285. // No explicit connections are maintained.
  286. }
  287. private HttpURLConnection connect(final String service)
  288. throws TransportException, NotSupportedException {
  289. final URL u;
  290. try {
  291. final StringBuilder b = new StringBuilder();
  292. b.append(baseUrl);
  293. if (b.charAt(b.length() - 1) != '/')
  294. b.append('/');
  295. b.append(Constants.INFO_REFS);
  296. if (useSmartHttp) {
  297. b.append(b.indexOf("?") < 0 ? '?' : '&');
  298. b.append("service=");
  299. b.append(service);
  300. }
  301. u = new URL(b.toString());
  302. } catch (MalformedURLException e) {
  303. throw new NotSupportedException("Invalid URL " + uri, e);
  304. }
  305. try {
  306. final HttpURLConnection conn = httpOpen(u);
  307. if (useSmartHttp) {
  308. String expType = "application/x-" + service + "-advertisement";
  309. conn.setRequestProperty(HDR_ACCEPT, expType + ", */*");
  310. } else {
  311. conn.setRequestProperty(HDR_ACCEPT, "*/*");
  312. }
  313. final int status = HttpSupport.response(conn);
  314. switch (status) {
  315. case HttpURLConnection.HTTP_OK:
  316. return conn;
  317. case HttpURLConnection.HTTP_NOT_FOUND:
  318. throw new NoRemoteRepositoryException(uri, u + " not found");
  319. case HttpURLConnection.HTTP_FORBIDDEN:
  320. throw new TransportException(uri, service + " not permitted");
  321. default:
  322. String err = status + " " + conn.getResponseMessage();
  323. throw new TransportException(uri, err);
  324. }
  325. } catch (NotSupportedException e) {
  326. throw e;
  327. } catch (TransportException e) {
  328. throw e;
  329. } catch (IOException e) {
  330. throw new TransportException(uri, "cannot open " + service, e);
  331. }
  332. }
  333. final HttpURLConnection httpOpen(final URL u) throws IOException {
  334. final Proxy proxy = HttpSupport.proxyFor(proxySelector, u);
  335. HttpURLConnection conn = (HttpURLConnection) u.openConnection(proxy);
  336. conn.setUseCaches(false);
  337. conn.setRequestProperty(HDR_ACCEPT_ENCODING, ENCODING_GZIP);
  338. conn.setRequestProperty(HDR_PRAGMA, "no-cache");//$NON-NLS-1$
  339. conn.setRequestProperty(HDR_USER_AGENT, userAgent);
  340. return conn;
  341. }
  342. final InputStream openInputStream(HttpURLConnection conn)
  343. throws IOException {
  344. InputStream input = conn.getInputStream();
  345. if (ENCODING_GZIP.equals(conn.getHeaderField(HDR_CONTENT_ENCODING)))
  346. input = new GZIPInputStream(input);
  347. return input;
  348. }
  349. IOException wrongContentType(String expType, String actType) {
  350. final String why = "expected Content-Type " + expType
  351. + "; received Content-Type " + actType;
  352. return new TransportException(uri, why);
  353. }
  354. private boolean isSmartHttp(final HttpURLConnection c, final String service) {
  355. final String expType = "application/x-" + service + "-advertisement";
  356. final String actType = c.getContentType();
  357. return expType.equals(actType);
  358. }
  359. private void readSmartHeaders(final InputStream in, final String service)
  360. throws IOException {
  361. // A smart reply will have a '#' after the first 4 bytes, but
  362. // a dumb reply cannot contain a '#' until after byte 41. Do a
  363. // quick check to make sure its a smart reply before we parse
  364. // as a pkt-line stream.
  365. //
  366. final byte[] magic = new byte[5];
  367. IO.readFully(in, magic, 0, magic.length);
  368. if (magic[4] != '#') {
  369. throw new TransportException(uri, "expected pkt-line with"
  370. + " '# service=', got '" + RawParseUtils.decode(magic)
  371. + "'");
  372. }
  373. final PacketLineIn pckIn = new PacketLineIn(new UnionInputStream(
  374. new ByteArrayInputStream(magic), in));
  375. final String exp = "# service=" + service;
  376. final String act = pckIn.readString();
  377. if (!exp.equals(act)) {
  378. throw new TransportException(uri, "expected '" + exp + "', got '"
  379. + act + "'");
  380. }
  381. while (pckIn.readString() != PacketLineIn.END) {
  382. // for now, ignore the remaining header lines
  383. }
  384. }
  385. class HttpObjectDB extends WalkRemoteObjectDatabase {
  386. private final URL objectsUrl;
  387. HttpObjectDB(final URL b) {
  388. objectsUrl = b;
  389. }
  390. @Override
  391. URIish getURI() {
  392. return new URIish(objectsUrl);
  393. }
  394. @Override
  395. Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
  396. try {
  397. return readAlternates(INFO_HTTP_ALTERNATES);
  398. } catch (FileNotFoundException err) {
  399. // Fall through.
  400. }
  401. try {
  402. return readAlternates(INFO_ALTERNATES);
  403. } catch (FileNotFoundException err) {
  404. // Fall through.
  405. }
  406. return null;
  407. }
  408. @Override
  409. WalkRemoteObjectDatabase openAlternate(final String location)
  410. throws IOException {
  411. return new HttpObjectDB(new URL(objectsUrl, location));
  412. }
  413. @Override
  414. Collection<String> getPackNames() throws IOException {
  415. final Collection<String> packs = new ArrayList<String>();
  416. try {
  417. final BufferedReader br = openReader(INFO_PACKS);
  418. try {
  419. for (;;) {
  420. final String s = br.readLine();
  421. if (s == null || s.length() == 0)
  422. break;
  423. if (!s.startsWith("P pack-") || !s.endsWith(".pack"))
  424. throw invalidAdvertisement(s);
  425. packs.add(s.substring(2));
  426. }
  427. return packs;
  428. } finally {
  429. br.close();
  430. }
  431. } catch (FileNotFoundException err) {
  432. return packs;
  433. }
  434. }
  435. @Override
  436. FileStream open(final String path) throws IOException {
  437. final URL base = objectsUrl;
  438. final URL u = new URL(base, path);
  439. final HttpURLConnection c = httpOpen(u);
  440. switch (HttpSupport.response(c)) {
  441. case HttpURLConnection.HTTP_OK:
  442. final InputStream in = openInputStream(c);
  443. final int len = c.getContentLength();
  444. return new FileStream(in, len);
  445. case HttpURLConnection.HTTP_NOT_FOUND:
  446. throw new FileNotFoundException(u.toString());
  447. default:
  448. throw new IOException(u.toString() + ": "
  449. + HttpSupport.response(c) + " "
  450. + c.getResponseMessage());
  451. }
  452. }
  453. Map<String, Ref> readAdvertisedImpl(final BufferedReader br)
  454. throws IOException, PackProtocolException {
  455. final TreeMap<String, Ref> avail = new TreeMap<String, Ref>();
  456. for (;;) {
  457. String line = br.readLine();
  458. if (line == null)
  459. break;
  460. final int tab = line.indexOf('\t');
  461. if (tab < 0)
  462. throw invalidAdvertisement(line);
  463. String name;
  464. final ObjectId id;
  465. name = line.substring(tab + 1);
  466. id = ObjectId.fromString(line.substring(0, tab));
  467. if (name.endsWith("^{}")) {
  468. name = name.substring(0, name.length() - 3);
  469. final Ref prior = avail.get(name);
  470. if (prior == null)
  471. throw outOfOrderAdvertisement(name);
  472. if (prior.getPeeledObjectId() != null)
  473. throw duplicateAdvertisement(name + "^{}");
  474. avail.put(name, new ObjectIdRef.PeeledTag(
  475. Ref.Storage.NETWORK, name,
  476. prior.getObjectId(), id));
  477. } else {
  478. Ref prior = avail.put(name, new ObjectIdRef.PeeledNonTag(
  479. Ref.Storage.NETWORK, name, id));
  480. if (prior != null)
  481. throw duplicateAdvertisement(name);
  482. }
  483. }
  484. return avail;
  485. }
  486. private PackProtocolException outOfOrderAdvertisement(final String n) {
  487. return new PackProtocolException("advertisement of " + n
  488. + "^{} came before " + n);
  489. }
  490. private PackProtocolException invalidAdvertisement(final String n) {
  491. return new PackProtocolException("invalid advertisement of " + n);
  492. }
  493. private PackProtocolException duplicateAdvertisement(final String n) {
  494. return new PackProtocolException("duplicate advertisements of " + n);
  495. }
  496. @Override
  497. void close() {
  498. // We do not maintain persistent connections.
  499. }
  500. }
  501. class SmartHttpFetchConnection extends BasePackFetchConnection {
  502. SmartHttpFetchConnection(final InputStream advertisement)
  503. throws TransportException {
  504. super(TransportHttp.this);
  505. statelessRPC = true;
  506. init(advertisement, DisabledOutputStream.INSTANCE);
  507. outNeedsEnd = false;
  508. readAdvertisedRefs();
  509. }
  510. @Override
  511. protected void doFetch(final ProgressMonitor monitor,
  512. final Collection<Ref> want, final Set<ObjectId> have)
  513. throws TransportException {
  514. final Service svc = new Service(SVC_UPLOAD_PACK);
  515. init(svc.in, svc.out);
  516. super.doFetch(monitor, want, have);
  517. }
  518. }
  519. class SmartHttpPushConnection extends BasePackPushConnection {
  520. SmartHttpPushConnection(final InputStream advertisement)
  521. throws TransportException {
  522. super(TransportHttp.this);
  523. statelessRPC = true;
  524. init(advertisement, DisabledOutputStream.INSTANCE);
  525. outNeedsEnd = false;
  526. readAdvertisedRefs();
  527. }
  528. protected void doPush(final ProgressMonitor monitor,
  529. final Map<String, RemoteRefUpdate> refUpdates)
  530. throws TransportException {
  531. final Service svc = new Service(SVC_RECEIVE_PACK);
  532. init(svc.in, svc.out);
  533. super.doPush(monitor, refUpdates);
  534. }
  535. }
  536. /**
  537. * State required to speak multiple HTTP requests with the remote.
  538. * <p>
  539. * A service wrapper provides a normal looking InputStream and OutputStream
  540. * pair which are connected via HTTP to the named remote service. Writing to
  541. * the OutputStream is buffered until either the buffer overflows, or
  542. * reading from the InputStream occurs. If overflow occurs HTTP/1.1 and its
  543. * chunked transfer encoding is used to stream the request data to the
  544. * remote service. If the entire request fits in the memory buffer, the
  545. * older HTTP/1.0 standard and a fixed content length is used instead.
  546. * <p>
  547. * It is an error to attempt to read without there being outstanding data
  548. * ready for transmission on the OutputStream.
  549. * <p>
  550. * No state is preserved between write-read request pairs. The caller is
  551. * responsible for replaying state vector information as part of the request
  552. * data written to the OutputStream. Any session HTTP cookies may or may not
  553. * be preserved between requests, it is left up to the JVM's implementation
  554. * of the HTTP client.
  555. */
  556. class Service {
  557. private final String serviceName;
  558. private final String requestType;
  559. private final String responseType;
  560. private final HttpExecuteStream execute;
  561. final UnionInputStream in;
  562. final HttpOutputStream out;
  563. HttpURLConnection conn;
  564. Service(final String serviceName) {
  565. this.serviceName = serviceName;
  566. this.requestType = "application/x-" + serviceName + "-request";
  567. this.responseType = "application/x-" + serviceName + "-result";
  568. this.execute = new HttpExecuteStream();
  569. this.in = new UnionInputStream(execute);
  570. this.out = new HttpOutputStream();
  571. }
  572. void openStream() throws IOException {
  573. conn = httpOpen(new URL(baseUrl, serviceName));
  574. conn.setRequestMethod(METHOD_POST);
  575. conn.setInstanceFollowRedirects(false);
  576. conn.setDoOutput(true);
  577. conn.setRequestProperty(HDR_CONTENT_TYPE, requestType);
  578. conn.setRequestProperty(HDR_ACCEPT, responseType);
  579. }
  580. void execute() throws IOException {
  581. out.close();
  582. if (conn == null) {
  583. // Output hasn't started yet, because everything fit into
  584. // our request buffer. Send with a Content-Length header.
  585. //
  586. if (out.length() == 0) {
  587. throw new TransportException(uri, "Starting read stage"
  588. + " without written request data pending"
  589. + " is not supported");
  590. }
  591. // Try to compress the content, but only if that is smaller.
  592. TemporaryBuffer buf = new TemporaryBuffer.Heap(http.postBuffer);
  593. try {
  594. GZIPOutputStream gzip = new GZIPOutputStream(buf);
  595. out.writeTo(gzip, null);
  596. gzip.close();
  597. if (out.length() < buf.length())
  598. buf = out;
  599. } catch (IOException err) {
  600. // Most likely caused by overflowing the buffer, meaning
  601. // its larger if it were compressed. Don't compress.
  602. buf = out;
  603. }
  604. openStream();
  605. if (buf != out)
  606. conn.setRequestProperty(HDR_CONTENT_ENCODING, ENCODING_GZIP);
  607. conn.setFixedLengthStreamingMode((int) buf.length());
  608. final OutputStream httpOut = conn.getOutputStream();
  609. try {
  610. buf.writeTo(httpOut, null);
  611. } finally {
  612. httpOut.close();
  613. }
  614. }
  615. out.reset();
  616. final int status = HttpSupport.response(conn);
  617. if (status != HttpURLConnection.HTTP_OK) {
  618. throw new TransportException(uri, status + " "
  619. + conn.getResponseMessage());
  620. }
  621. final String contentType = conn.getContentType();
  622. if (!responseType.equals(contentType)) {
  623. conn.getInputStream().close();
  624. throw wrongContentType(responseType, contentType);
  625. }
  626. in.add(openInputStream(conn));
  627. in.add(execute);
  628. conn = null;
  629. }
  630. class HttpOutputStream extends TemporaryBuffer {
  631. HttpOutputStream() {
  632. super(http.postBuffer);
  633. }
  634. @Override
  635. protected OutputStream overflow() throws IOException {
  636. openStream();
  637. conn.setChunkedStreamingMode(0);
  638. return conn.getOutputStream();
  639. }
  640. }
  641. class HttpExecuteStream extends InputStream {
  642. public int available() throws IOException {
  643. execute();
  644. return 0;
  645. }
  646. public int read() throws IOException {
  647. execute();
  648. return -1;
  649. }
  650. public int read(byte[] b, int off, int len) throws IOException {
  651. execute();
  652. return -1;
  653. }
  654. public long skip(long n) throws IOException {
  655. execute();
  656. return 0;
  657. }
  658. }
  659. }
  660. }