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

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