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 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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_GET;
  53. import static org.eclipse.jgit.util.HttpSupport.METHOD_POST;
  54. import java.io.BufferedReader;
  55. import java.io.ByteArrayInputStream;
  56. import java.io.FileNotFoundException;
  57. import java.io.IOException;
  58. import java.io.InputStream;
  59. import java.io.InputStreamReader;
  60. import java.io.OutputStream;
  61. import java.net.HttpURLConnection;
  62. import java.net.MalformedURLException;
  63. import java.net.Proxy;
  64. import java.net.ProxySelector;
  65. import java.net.URL;
  66. import java.net.URLConnection;
  67. import java.security.KeyManagementException;
  68. import java.security.NoSuchAlgorithmException;
  69. import java.security.cert.X509Certificate;
  70. import java.text.MessageFormat;
  71. import java.util.ArrayList;
  72. import java.util.Arrays;
  73. import java.util.Collection;
  74. import java.util.Collections;
  75. import java.util.EnumSet;
  76. import java.util.LinkedHashSet;
  77. import java.util.Map;
  78. import java.util.Set;
  79. import java.util.TreeMap;
  80. import java.util.zip.GZIPInputStream;
  81. import java.util.zip.GZIPOutputStream;
  82. import javax.net.ssl.HttpsURLConnection;
  83. import javax.net.ssl.SSLContext;
  84. import javax.net.ssl.TrustManager;
  85. import javax.net.ssl.X509TrustManager;
  86. import org.eclipse.jgit.errors.NoRemoteRepositoryException;
  87. import org.eclipse.jgit.errors.NotSupportedException;
  88. import org.eclipse.jgit.errors.PackProtocolException;
  89. import org.eclipse.jgit.errors.TransportException;
  90. import org.eclipse.jgit.internal.JGitText;
  91. import org.eclipse.jgit.lib.Config;
  92. import org.eclipse.jgit.lib.Config.SectionParser;
  93. import org.eclipse.jgit.lib.Constants;
  94. import org.eclipse.jgit.lib.ObjectId;
  95. import org.eclipse.jgit.lib.ObjectIdRef;
  96. import org.eclipse.jgit.lib.ProgressMonitor;
  97. import org.eclipse.jgit.lib.Ref;
  98. import org.eclipse.jgit.lib.Repository;
  99. import org.eclipse.jgit.lib.SymbolicRef;
  100. import org.eclipse.jgit.storage.file.RefDirectory;
  101. import org.eclipse.jgit.util.HttpSupport;
  102. import org.eclipse.jgit.util.IO;
  103. import org.eclipse.jgit.util.RawParseUtils;
  104. import org.eclipse.jgit.util.TemporaryBuffer;
  105. import org.eclipse.jgit.util.io.DisabledOutputStream;
  106. import org.eclipse.jgit.util.io.UnionInputStream;
  107. /**
  108. * Transport over HTTP and FTP protocols.
  109. * <p>
  110. * If the transport is using HTTP and the remote HTTP service is Git-aware
  111. * (speaks the "smart-http protocol") this client will automatically take
  112. * advantage of the additional Git-specific HTTP extensions. If the remote
  113. * service does not support these extensions, the client will degrade to direct
  114. * file fetching.
  115. * <p>
  116. * If the remote (server side) repository does not have the specialized Git
  117. * support, object files are retrieved directly through standard HTTP GET (or
  118. * binary FTP GET) requests. This make it easy to serve a Git repository through
  119. * a standard web host provider that does not offer specific support for Git.
  120. *
  121. * @see WalkFetchConnection
  122. */
  123. public class TransportHttp extends HttpTransport implements WalkTransport,
  124. PackTransport {
  125. private static final String SVC_UPLOAD_PACK = "git-upload-pack"; //$NON-NLS-1$
  126. private static final String SVC_RECEIVE_PACK = "git-receive-pack"; //$NON-NLS-1$
  127. private static final String userAgent = computeUserAgent();
  128. static final TransportProtocol PROTO_HTTP = new TransportProtocol() {
  129. private final String[] schemeNames = { "http", "https" }; //$NON-NLS-1$ //$NON-NLS-2$
  130. private final Set<String> schemeSet = Collections
  131. .unmodifiableSet(new LinkedHashSet<String>(Arrays
  132. .asList(schemeNames)));
  133. public String getName() {
  134. return JGitText.get().transportProtoHTTP;
  135. }
  136. public Set<String> getSchemes() {
  137. return schemeSet;
  138. }
  139. public Set<URIishField> getRequiredFields() {
  140. return Collections.unmodifiableSet(EnumSet.of(URIishField.HOST,
  141. URIishField.PATH));
  142. }
  143. public Set<URIishField> getOptionalFields() {
  144. return Collections.unmodifiableSet(EnumSet.of(URIishField.USER,
  145. URIishField.PASS, URIishField.PORT));
  146. }
  147. public int getDefaultPort() {
  148. return 80;
  149. }
  150. public Transport open(URIish uri, Repository local, String remoteName)
  151. throws NotSupportedException {
  152. return new TransportHttp(local, uri);
  153. }
  154. public Transport open(URIish uri) throws NotSupportedException {
  155. return new TransportHttp(uri);
  156. }
  157. };
  158. static final TransportProtocol PROTO_FTP = new TransportProtocol() {
  159. public String getName() {
  160. return JGitText.get().transportProtoFTP;
  161. }
  162. public Set<String> getSchemes() {
  163. return Collections.singleton("ftp"); //$NON-NLS-1$
  164. }
  165. public Set<URIishField> getRequiredFields() {
  166. return Collections.unmodifiableSet(EnumSet.of(URIishField.HOST,
  167. URIishField.PATH));
  168. }
  169. public Set<URIishField> getOptionalFields() {
  170. return Collections.unmodifiableSet(EnumSet.of(URIishField.USER,
  171. URIishField.PASS, URIishField.PORT));
  172. }
  173. public int getDefaultPort() {
  174. return 21;
  175. }
  176. public Transport open(URIish uri, Repository local, String remoteName)
  177. throws NotSupportedException {
  178. return new TransportHttp(local, uri);
  179. }
  180. };
  181. private static String computeUserAgent() {
  182. String version;
  183. final Package pkg = TransportHttp.class.getPackage();
  184. if (pkg != null && pkg.getImplementationVersion() != null) {
  185. version = pkg.getImplementationVersion();
  186. } else {
  187. version = "unknown"; //$NON-NLS-1$
  188. }
  189. return "JGit/" + version; //$NON-NLS-1$
  190. }
  191. private static final Config.SectionParser<HttpConfig> HTTP_KEY = new SectionParser<HttpConfig>() {
  192. public HttpConfig parse(final Config cfg) {
  193. return new HttpConfig(cfg);
  194. }
  195. };
  196. private static class HttpConfig {
  197. final int postBuffer;
  198. final boolean sslVerify;
  199. HttpConfig(final Config rc) {
  200. postBuffer = rc.getInt("http", "postbuffer", 1 * 1024 * 1024); //$NON-NLS-1$ //$NON-NLS-2$
  201. sslVerify = rc.getBoolean("http", "sslVerify", true);
  202. }
  203. private HttpConfig() {
  204. this(new Config());
  205. }
  206. }
  207. private final URL baseUrl;
  208. private final URL objectsUrl;
  209. private final HttpConfig http;
  210. private final ProxySelector proxySelector;
  211. private boolean useSmartHttp = true;
  212. private HttpAuthMethod authMethod = HttpAuthMethod.NONE;
  213. TransportHttp(final Repository local, final URIish uri)
  214. throws NotSupportedException {
  215. super(local, uri);
  216. try {
  217. String uriString = uri.toString();
  218. if (!uriString.endsWith("/")) //$NON-NLS-1$
  219. uriString += "/"; //$NON-NLS-1$
  220. baseUrl = new URL(uriString);
  221. objectsUrl = new URL(baseUrl, "objects/"); //$NON-NLS-1$
  222. } catch (MalformedURLException e) {
  223. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  224. }
  225. http = local.getConfig().get(HTTP_KEY);
  226. proxySelector = ProxySelector.getDefault();
  227. }
  228. /**
  229. * Create a minimal HTTP transport with default configuration values.
  230. *
  231. * @param uri
  232. * @throws NotSupportedException
  233. */
  234. TransportHttp(final URIish uri) throws NotSupportedException {
  235. super(uri);
  236. try {
  237. String uriString = uri.toString();
  238. if (!uriString.endsWith("/")) //$NON-NLS-1$
  239. uriString += "/"; //$NON-NLS-1$
  240. baseUrl = new URL(uriString);
  241. objectsUrl = new URL(baseUrl, "objects/"); //$NON-NLS-1$
  242. } catch (MalformedURLException e) {
  243. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  244. }
  245. http = new HttpConfig();
  246. proxySelector = ProxySelector.getDefault();
  247. }
  248. /**
  249. * Toggle whether or not smart HTTP transport should be used.
  250. * <p>
  251. * This flag exists primarily to support backwards compatibility testing
  252. * within a testing framework, there is no need to modify it in most
  253. * applications.
  254. *
  255. * @param on
  256. * if {@code true} (default), smart HTTP is enabled.
  257. */
  258. public void setUseSmartHttp(final boolean on) {
  259. useSmartHttp = on;
  260. }
  261. @Override
  262. public FetchConnection openFetch() throws TransportException,
  263. NotSupportedException {
  264. final String service = SVC_UPLOAD_PACK;
  265. try {
  266. final HttpURLConnection c = connect(service);
  267. final InputStream in = openInputStream(c);
  268. try {
  269. if (isSmartHttp(c, service)) {
  270. readSmartHeaders(in, service);
  271. return new SmartHttpFetchConnection(in);
  272. } else {
  273. // Assume this server doesn't support smart HTTP fetch
  274. // and fall back on dumb object walking.
  275. //
  276. return newDumbConnection(in);
  277. }
  278. } finally {
  279. in.close();
  280. }
  281. } catch (NotSupportedException err) {
  282. throw err;
  283. } catch (TransportException err) {
  284. throw err;
  285. } catch (IOException err) {
  286. throw new TransportException(uri, JGitText.get().errorReadingInfoRefs, err);
  287. }
  288. }
  289. private FetchConnection newDumbConnection(InputStream in)
  290. throws IOException, PackProtocolException {
  291. HttpObjectDB d = new HttpObjectDB(objectsUrl);
  292. BufferedReader br = toBufferedReader(in);
  293. Map<String, Ref> refs;
  294. try {
  295. refs = d.readAdvertisedImpl(br);
  296. } finally {
  297. br.close();
  298. }
  299. if (!refs.containsKey(Constants.HEAD)) {
  300. // If HEAD was not published in the info/refs file (it usually
  301. // is not there) download HEAD by itself as a loose file and do
  302. // the resolution by hand.
  303. //
  304. HttpURLConnection conn = httpOpen(new URL(baseUrl, Constants.HEAD));
  305. int status = HttpSupport.response(conn);
  306. switch (status) {
  307. case HttpURLConnection.HTTP_OK: {
  308. br = toBufferedReader(openInputStream(conn));
  309. try {
  310. String line = br.readLine();
  311. if (line != null && line.startsWith(RefDirectory.SYMREF)) {
  312. String target = line.substring(RefDirectory.SYMREF.length());
  313. Ref r = refs.get(target);
  314. if (r == null)
  315. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  316. r = new SymbolicRef(Constants.HEAD, r);
  317. refs.put(r.getName(), r);
  318. } else if (line != null && ObjectId.isId(line)) {
  319. Ref r = new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK,
  320. Constants.HEAD, ObjectId.fromString(line));
  321. refs.put(r.getName(), r);
  322. }
  323. } finally {
  324. br.close();
  325. }
  326. break;
  327. }
  328. case HttpURLConnection.HTTP_NOT_FOUND:
  329. break;
  330. default:
  331. throw new TransportException(uri, MessageFormat.format(
  332. JGitText.get().cannotReadHEAD, Integer.valueOf(status),
  333. conn.getResponseMessage()));
  334. }
  335. }
  336. WalkFetchConnection wfc = new WalkFetchConnection(this, d);
  337. wfc.available(refs);
  338. return wfc;
  339. }
  340. private BufferedReader toBufferedReader(InputStream in) {
  341. return new BufferedReader(new InputStreamReader(in, Constants.CHARSET));
  342. }
  343. @Override
  344. public PushConnection openPush() throws NotSupportedException,
  345. TransportException {
  346. final String service = SVC_RECEIVE_PACK;
  347. try {
  348. final HttpURLConnection c = connect(service);
  349. final InputStream in = openInputStream(c);
  350. try {
  351. if (isSmartHttp(c, service)) {
  352. readSmartHeaders(in, service);
  353. return new SmartHttpPushConnection(in);
  354. } else if (!useSmartHttp) {
  355. final String msg = JGitText.get().smartHTTPPushDisabled;
  356. throw new NotSupportedException(msg);
  357. } else {
  358. final String msg = JGitText.get().remoteDoesNotSupportSmartHTTPPush;
  359. throw new NotSupportedException(msg);
  360. }
  361. } finally {
  362. in.close();
  363. }
  364. } catch (NotSupportedException err) {
  365. throw err;
  366. } catch (TransportException err) {
  367. throw err;
  368. } catch (IOException err) {
  369. throw new TransportException(uri, JGitText.get().errorReadingInfoRefs, err);
  370. }
  371. }
  372. @Override
  373. public void close() {
  374. // No explicit connections are maintained.
  375. }
  376. private HttpURLConnection connect(final String service)
  377. throws TransportException, NotSupportedException {
  378. final URL u;
  379. try {
  380. final StringBuilder b = new StringBuilder();
  381. b.append(baseUrl);
  382. if (b.charAt(b.length() - 1) != '/')
  383. b.append('/');
  384. b.append(Constants.INFO_REFS);
  385. if (useSmartHttp) {
  386. b.append(b.indexOf("?") < 0 ? '?' : '&'); //$NON-NLS-1$
  387. b.append("service="); //$NON-NLS-1$
  388. b.append(service);
  389. }
  390. u = new URL(b.toString());
  391. } catch (MalformedURLException e) {
  392. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  393. }
  394. try {
  395. int authAttempts = 1;
  396. for (;;) {
  397. final HttpURLConnection conn = httpOpen(u);
  398. if (useSmartHttp) {
  399. String exp = "application/x-" + service + "-advertisement"; //$NON-NLS-1$ //$NON-NLS-2$
  400. conn.setRequestProperty(HDR_ACCEPT, exp + ", */*"); //$NON-NLS-1$
  401. } else {
  402. conn.setRequestProperty(HDR_ACCEPT, "*/*"); //$NON-NLS-1$
  403. }
  404. final int status = HttpSupport.response(conn);
  405. switch (status) {
  406. case HttpURLConnection.HTTP_OK:
  407. return conn;
  408. case HttpURLConnection.HTTP_NOT_FOUND:
  409. throw new NoRemoteRepositoryException(uri,
  410. MessageFormat.format(JGitText.get().uriNotFound, u));
  411. case HttpURLConnection.HTTP_UNAUTHORIZED:
  412. authMethod = HttpAuthMethod.scanResponse(conn);
  413. if (authMethod == HttpAuthMethod.NONE)
  414. throw new TransportException(uri, MessageFormat.format(
  415. JGitText.get().authenticationNotSupported, uri));
  416. if (1 < authAttempts
  417. || !authMethod.authorize(uri,
  418. getCredentialsProvider())) {
  419. throw new TransportException(uri,
  420. JGitText.get().notAuthorized);
  421. }
  422. authAttempts++;
  423. continue;
  424. case HttpURLConnection.HTTP_FORBIDDEN:
  425. throw new TransportException(uri, MessageFormat.format(
  426. JGitText.get().serviceNotPermitted, service));
  427. default:
  428. String err = status + " " + conn.getResponseMessage(); //$NON-NLS-1$
  429. throw new TransportException(uri, err);
  430. }
  431. }
  432. } catch (NotSupportedException e) {
  433. throw e;
  434. } catch (TransportException e) {
  435. throw e;
  436. } catch (IOException e) {
  437. throw new TransportException(uri, MessageFormat.format(JGitText.get().cannotOpenService, service), e);
  438. }
  439. }
  440. final HttpURLConnection httpOpen(URL u) throws IOException {
  441. return httpOpen(METHOD_GET, u);
  442. }
  443. final HttpURLConnection httpOpen(String method, URL u) throws IOException {
  444. final Proxy proxy = HttpSupport.proxyFor(proxySelector, u);
  445. HttpURLConnection conn = (HttpURLConnection) u.openConnection(proxy);
  446. if (!http.sslVerify && "https".equals(u.getProtocol())) {
  447. disableSslVerify(conn);
  448. }
  449. conn.setRequestMethod(method);
  450. conn.setUseCaches(false);
  451. conn.setRequestProperty(HDR_ACCEPT_ENCODING, ENCODING_GZIP);
  452. conn.setRequestProperty(HDR_PRAGMA, "no-cache"); //$NON-NLS-1$
  453. conn.setRequestProperty(HDR_USER_AGENT, userAgent);
  454. int timeOut = getTimeout();
  455. if (timeOut != -1) {
  456. int effTimeOut = timeOut * 1000;
  457. conn.setConnectTimeout(effTimeOut);
  458. conn.setReadTimeout(effTimeOut);
  459. }
  460. authMethod.configureRequest(conn);
  461. return conn;
  462. }
  463. private void disableSslVerify(URLConnection conn)
  464. throws IOException {
  465. final TrustManager[] trustAllCerts = new TrustManager[] { new DummyX509TrustManager() };
  466. try {
  467. SSLContext ctx = SSLContext.getInstance("SSL");
  468. ctx.init(null, trustAllCerts, null);
  469. final HttpsURLConnection sslConn = (HttpsURLConnection) conn;
  470. sslConn.setSSLSocketFactory(ctx.getSocketFactory());
  471. } catch (KeyManagementException e) {
  472. throw new IOException(e.getMessage());
  473. } catch (NoSuchAlgorithmException e) {
  474. throw new IOException(e.getMessage());
  475. }
  476. }
  477. final InputStream openInputStream(HttpURLConnection conn)
  478. throws IOException {
  479. InputStream input = conn.getInputStream();
  480. if (ENCODING_GZIP.equals(conn.getHeaderField(HDR_CONTENT_ENCODING)))
  481. input = new GZIPInputStream(input);
  482. return input;
  483. }
  484. IOException wrongContentType(String expType, String actType) {
  485. final String why = MessageFormat.format(JGitText.get().expectedReceivedContentType, expType, actType);
  486. return new TransportException(uri, why);
  487. }
  488. private boolean isSmartHttp(final HttpURLConnection c, final String service) {
  489. final String expType = "application/x-" + service + "-advertisement"; //$NON-NLS-1$ //$NON-NLS-2$
  490. final String actType = c.getContentType();
  491. return expType.equals(actType);
  492. }
  493. private void readSmartHeaders(final InputStream in, final String service)
  494. throws IOException {
  495. // A smart reply will have a '#' after the first 4 bytes, but
  496. // a dumb reply cannot contain a '#' until after byte 41. Do a
  497. // quick check to make sure its a smart reply before we parse
  498. // as a pkt-line stream.
  499. //
  500. final byte[] magic = new byte[5];
  501. IO.readFully(in, magic, 0, magic.length);
  502. if (magic[4] != '#') {
  503. throw new TransportException(uri, MessageFormat.format(
  504. JGitText.get().expectedPktLineWithService, RawParseUtils.decode(magic)));
  505. }
  506. final PacketLineIn pckIn = new PacketLineIn(new UnionInputStream(
  507. new ByteArrayInputStream(magic), in));
  508. final String exp = "# service=" + service; //$NON-NLS-1$
  509. final String act = pckIn.readString();
  510. if (!exp.equals(act)) {
  511. throw new TransportException(uri, MessageFormat.format(
  512. JGitText.get().expectedGot, exp, act));
  513. }
  514. while (pckIn.readString() != PacketLineIn.END) {
  515. // for now, ignore the remaining header lines
  516. }
  517. }
  518. class HttpObjectDB extends WalkRemoteObjectDatabase {
  519. private final URL objectsUrl;
  520. HttpObjectDB(final URL b) {
  521. objectsUrl = b;
  522. }
  523. @Override
  524. URIish getURI() {
  525. return new URIish(objectsUrl);
  526. }
  527. @Override
  528. Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
  529. try {
  530. return readAlternates(INFO_HTTP_ALTERNATES);
  531. } catch (FileNotFoundException err) {
  532. // Fall through.
  533. }
  534. try {
  535. return readAlternates(INFO_ALTERNATES);
  536. } catch (FileNotFoundException err) {
  537. // Fall through.
  538. }
  539. return null;
  540. }
  541. @Override
  542. WalkRemoteObjectDatabase openAlternate(final String location)
  543. throws IOException {
  544. return new HttpObjectDB(new URL(objectsUrl, location));
  545. }
  546. @Override
  547. Collection<String> getPackNames() throws IOException {
  548. final Collection<String> packs = new ArrayList<String>();
  549. try {
  550. final BufferedReader br = openReader(INFO_PACKS);
  551. try {
  552. for (;;) {
  553. final String s = br.readLine();
  554. if (s == null || s.length() == 0)
  555. break;
  556. if (!s.startsWith("P pack-") || !s.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  557. throw invalidAdvertisement(s);
  558. packs.add(s.substring(2));
  559. }
  560. return packs;
  561. } finally {
  562. br.close();
  563. }
  564. } catch (FileNotFoundException err) {
  565. return packs;
  566. }
  567. }
  568. @Override
  569. FileStream open(final String path) throws IOException {
  570. final URL base = objectsUrl;
  571. final URL u = new URL(base, path);
  572. final HttpURLConnection c = httpOpen(u);
  573. switch (HttpSupport.response(c)) {
  574. case HttpURLConnection.HTTP_OK:
  575. final InputStream in = openInputStream(c);
  576. final int len = c.getContentLength();
  577. return new FileStream(in, len);
  578. case HttpURLConnection.HTTP_NOT_FOUND:
  579. throw new FileNotFoundException(u.toString());
  580. default:
  581. throw new IOException(u.toString() + ": " //$NON-NLS-1$
  582. + HttpSupport.response(c) + " " //$NON-NLS-1$
  583. + c.getResponseMessage());
  584. }
  585. }
  586. Map<String, Ref> readAdvertisedImpl(final BufferedReader br)
  587. throws IOException, PackProtocolException {
  588. final TreeMap<String, Ref> avail = new TreeMap<String, Ref>();
  589. for (;;) {
  590. String line = br.readLine();
  591. if (line == null)
  592. break;
  593. final int tab = line.indexOf('\t');
  594. if (tab < 0)
  595. throw invalidAdvertisement(line);
  596. String name;
  597. final ObjectId id;
  598. name = line.substring(tab + 1);
  599. id = ObjectId.fromString(line.substring(0, tab));
  600. if (name.endsWith("^{}")) { //$NON-NLS-1$
  601. name = name.substring(0, name.length() - 3);
  602. final Ref prior = avail.get(name);
  603. if (prior == null)
  604. throw outOfOrderAdvertisement(name);
  605. if (prior.getPeeledObjectId() != null)
  606. throw duplicateAdvertisement(name + "^{}"); //$NON-NLS-1$
  607. avail.put(name, new ObjectIdRef.PeeledTag(
  608. Ref.Storage.NETWORK, name,
  609. prior.getObjectId(), id));
  610. } else {
  611. Ref prior = avail.put(name, new ObjectIdRef.PeeledNonTag(
  612. Ref.Storage.NETWORK, name, id));
  613. if (prior != null)
  614. throw duplicateAdvertisement(name);
  615. }
  616. }
  617. return avail;
  618. }
  619. private PackProtocolException outOfOrderAdvertisement(final String n) {
  620. return new PackProtocolException(MessageFormat.format(JGitText.get().advertisementOfCameBefore, n, n));
  621. }
  622. private PackProtocolException invalidAdvertisement(final String n) {
  623. return new PackProtocolException(MessageFormat.format(JGitText.get().invalidAdvertisementOf, n));
  624. }
  625. private PackProtocolException duplicateAdvertisement(final String n) {
  626. return new PackProtocolException(MessageFormat.format(JGitText.get().duplicateAdvertisementsOf, n));
  627. }
  628. @Override
  629. void close() {
  630. // We do not maintain persistent connections.
  631. }
  632. }
  633. class SmartHttpFetchConnection extends BasePackFetchConnection {
  634. private MultiRequestService svc;
  635. SmartHttpFetchConnection(final InputStream advertisement)
  636. throws TransportException {
  637. super(TransportHttp.this);
  638. statelessRPC = true;
  639. init(advertisement, DisabledOutputStream.INSTANCE);
  640. outNeedsEnd = false;
  641. readAdvertisedRefs();
  642. }
  643. @Override
  644. protected void doFetch(final ProgressMonitor monitor,
  645. final Collection<Ref> want, final Set<ObjectId> have)
  646. throws TransportException {
  647. try {
  648. svc = new MultiRequestService(SVC_UPLOAD_PACK);
  649. init(svc.getInputStream(), svc.getOutputStream());
  650. super.doFetch(monitor, want, have);
  651. } finally {
  652. svc = null;
  653. }
  654. }
  655. @Override
  656. protected void onReceivePack() {
  657. svc.finalRequest = true;
  658. }
  659. }
  660. class SmartHttpPushConnection extends BasePackPushConnection {
  661. SmartHttpPushConnection(final InputStream advertisement)
  662. throws TransportException {
  663. super(TransportHttp.this);
  664. statelessRPC = true;
  665. init(advertisement, DisabledOutputStream.INSTANCE);
  666. outNeedsEnd = false;
  667. readAdvertisedRefs();
  668. }
  669. protected void doPush(final ProgressMonitor monitor,
  670. final Map<String, RemoteRefUpdate> refUpdates)
  671. throws TransportException {
  672. final Service svc = new MultiRequestService(SVC_RECEIVE_PACK);
  673. init(svc.getInputStream(), svc.getOutputStream());
  674. super.doPush(monitor, refUpdates);
  675. }
  676. }
  677. /** Basic service for sending and receiving HTTP requests. */
  678. abstract class Service {
  679. protected final String serviceName;
  680. protected final String requestType;
  681. protected final String responseType;
  682. protected HttpURLConnection conn;
  683. protected HttpOutputStream out;
  684. protected final HttpExecuteStream execute;
  685. final UnionInputStream in;
  686. Service(String serviceName) {
  687. this.serviceName = serviceName;
  688. this.requestType = "application/x-" + serviceName + "-request"; //$NON-NLS-1$ //$NON-NLS-2$
  689. this.responseType = "application/x-" + serviceName + "-result"; //$NON-NLS-1$ //$NON-NLS-2$
  690. this.out = new HttpOutputStream();
  691. this.execute = new HttpExecuteStream();
  692. this.in = new UnionInputStream(execute);
  693. }
  694. void openStream() throws IOException {
  695. conn = httpOpen(METHOD_POST, new URL(baseUrl, serviceName));
  696. conn.setInstanceFollowRedirects(false);
  697. conn.setDoOutput(true);
  698. conn.setRequestProperty(HDR_CONTENT_TYPE, requestType);
  699. conn.setRequestProperty(HDR_ACCEPT, responseType);
  700. }
  701. void sendRequest() throws IOException {
  702. // Try to compress the content, but only if that is smaller.
  703. TemporaryBuffer buf = new TemporaryBuffer.Heap(http.postBuffer);
  704. try {
  705. GZIPOutputStream gzip = new GZIPOutputStream(buf);
  706. out.writeTo(gzip, null);
  707. gzip.close();
  708. if (out.length() < buf.length())
  709. buf = out;
  710. } catch (IOException err) {
  711. // Most likely caused by overflowing the buffer, meaning
  712. // its larger if it were compressed. Don't compress.
  713. buf = out;
  714. }
  715. openStream();
  716. if (buf != out)
  717. conn.setRequestProperty(HDR_CONTENT_ENCODING, ENCODING_GZIP);
  718. conn.setFixedLengthStreamingMode((int) buf.length());
  719. final OutputStream httpOut = conn.getOutputStream();
  720. try {
  721. buf.writeTo(httpOut, null);
  722. } finally {
  723. httpOut.close();
  724. }
  725. }
  726. void openResponse() throws IOException {
  727. final int status = HttpSupport.response(conn);
  728. if (status != HttpURLConnection.HTTP_OK) {
  729. throw new TransportException(uri, status + " " //$NON-NLS-1$
  730. + conn.getResponseMessage());
  731. }
  732. final String contentType = conn.getContentType();
  733. if (!responseType.equals(contentType)) {
  734. conn.getInputStream().close();
  735. throw wrongContentType(responseType, contentType);
  736. }
  737. }
  738. HttpOutputStream getOutputStream() {
  739. return out;
  740. }
  741. InputStream getInputStream() {
  742. return in;
  743. }
  744. abstract void execute() throws IOException;
  745. class HttpExecuteStream extends InputStream {
  746. public int read() throws IOException {
  747. execute();
  748. return -1;
  749. }
  750. public int read(byte[] b, int off, int len) throws IOException {
  751. execute();
  752. return -1;
  753. }
  754. public long skip(long n) throws IOException {
  755. execute();
  756. return 0;
  757. }
  758. }
  759. class HttpOutputStream extends TemporaryBuffer {
  760. HttpOutputStream() {
  761. super(http.postBuffer);
  762. }
  763. @Override
  764. protected OutputStream overflow() throws IOException {
  765. openStream();
  766. conn.setChunkedStreamingMode(0);
  767. return conn.getOutputStream();
  768. }
  769. }
  770. }
  771. /**
  772. * State required to speak multiple HTTP requests with the remote.
  773. * <p>
  774. * A service wrapper provides a normal looking InputStream and OutputStream
  775. * pair which are connected via HTTP to the named remote service. Writing to
  776. * the OutputStream is buffered until either the buffer overflows, or
  777. * reading from the InputStream occurs. If overflow occurs HTTP/1.1 and its
  778. * chunked transfer encoding is used to stream the request data to the
  779. * remote service. If the entire request fits in the memory buffer, the
  780. * older HTTP/1.0 standard and a fixed content length is used instead.
  781. * <p>
  782. * It is an error to attempt to read without there being outstanding data
  783. * ready for transmission on the OutputStream.
  784. * <p>
  785. * No state is preserved between write-read request pairs. The caller is
  786. * responsible for replaying state vector information as part of the request
  787. * data written to the OutputStream. Any session HTTP cookies may or may not
  788. * be preserved between requests, it is left up to the JVM's implementation
  789. * of the HTTP client.
  790. */
  791. class MultiRequestService extends Service {
  792. boolean finalRequest;
  793. MultiRequestService(final String serviceName) {
  794. super(serviceName);
  795. }
  796. /** Keep opening send-receive pairs to the given URI. */
  797. @Override
  798. void execute() throws IOException {
  799. out.close();
  800. if (conn == null) {
  801. if (out.length() == 0) {
  802. // Request output hasn't started yet, but more data is being
  803. // requested. If there is no request data buffered and the
  804. // final request was already sent, do nothing to ensure the
  805. // caller is shown EOF on the InputStream; otherwise an
  806. // programming error has occurred within this module.
  807. if (finalRequest)
  808. return;
  809. throw new TransportException(uri,
  810. JGitText.get().startingReadStageWithoutWrittenRequestDataPendingIsNotSupported);
  811. }
  812. sendRequest();
  813. }
  814. out.reset();
  815. openResponse();
  816. in.add(openInputStream(conn));
  817. if (!finalRequest)
  818. in.add(execute);
  819. conn = null;
  820. }
  821. }
  822. /** Service for maintaining a single long-poll connection. */
  823. class LongPollService extends Service {
  824. /**
  825. * @param serviceName
  826. */
  827. LongPollService(String serviceName) {
  828. super(serviceName);
  829. }
  830. /** Only open one send-receive request. */
  831. @Override
  832. void execute() throws IOException {
  833. out.close();
  834. if (conn == null)
  835. sendRequest();
  836. openResponse();
  837. in.add(openInputStream(conn));
  838. }
  839. }
  840. private static class DummyX509TrustManager implements X509TrustManager {
  841. public X509Certificate[] getAcceptedIssuers() {
  842. return null;
  843. }
  844. public void checkClientTrusted(X509Certificate[] certs, String authType) {
  845. // no check
  846. }
  847. public void checkServerTrusted(X509Certificate[] certs, String authType) {
  848. // no check
  849. }
  850. }
  851. }