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. if (getCredentialsProvider() == null)
  230. setCredentialsProvider(new NetRCCredentialsProvider());
  231. }
  232. /**
  233. * Create a minimal HTTP transport with default configuration values.
  234. *
  235. * @param uri
  236. * @throws NotSupportedException
  237. */
  238. TransportHttp(final URIish uri) throws NotSupportedException {
  239. super(uri);
  240. try {
  241. String uriString = uri.toString();
  242. if (!uriString.endsWith("/")) //$NON-NLS-1$
  243. uriString += "/"; //$NON-NLS-1$
  244. baseUrl = new URL(uriString);
  245. objectsUrl = new URL(baseUrl, "objects/"); //$NON-NLS-1$
  246. } catch (MalformedURLException e) {
  247. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  248. }
  249. http = new HttpConfig();
  250. proxySelector = ProxySelector.getDefault();
  251. }
  252. /**
  253. * Toggle whether or not smart HTTP transport should be used.
  254. * <p>
  255. * This flag exists primarily to support backwards compatibility testing
  256. * within a testing framework, there is no need to modify it in most
  257. * applications.
  258. *
  259. * @param on
  260. * if {@code true} (default), smart HTTP is enabled.
  261. */
  262. public void setUseSmartHttp(final boolean on) {
  263. useSmartHttp = on;
  264. }
  265. @Override
  266. public FetchConnection openFetch() throws TransportException,
  267. NotSupportedException {
  268. final String service = SVC_UPLOAD_PACK;
  269. try {
  270. final HttpConnection c = connect(service);
  271. final InputStream in = openInputStream(c);
  272. try {
  273. if (isSmartHttp(c, service)) {
  274. readSmartHeaders(in, service);
  275. return new SmartHttpFetchConnection(in);
  276. } else {
  277. // Assume this server doesn't support smart HTTP fetch
  278. // and fall back on dumb object walking.
  279. //
  280. return newDumbConnection(in);
  281. }
  282. } finally {
  283. in.close();
  284. }
  285. } catch (NotSupportedException err) {
  286. throw err;
  287. } catch (TransportException err) {
  288. throw err;
  289. } catch (IOException err) {
  290. throw new TransportException(uri, JGitText.get().errorReadingInfoRefs, err);
  291. }
  292. }
  293. private FetchConnection newDumbConnection(InputStream in)
  294. throws IOException, PackProtocolException {
  295. HttpObjectDB d = new HttpObjectDB(objectsUrl);
  296. BufferedReader br = toBufferedReader(in);
  297. Map<String, Ref> refs;
  298. try {
  299. refs = d.readAdvertisedImpl(br);
  300. } finally {
  301. br.close();
  302. }
  303. if (!refs.containsKey(Constants.HEAD)) {
  304. // If HEAD was not published in the info/refs file (it usually
  305. // is not there) download HEAD by itself as a loose file and do
  306. // the resolution by hand.
  307. //
  308. HttpConnection conn = httpOpen(new URL(baseUrl, Constants.HEAD));
  309. int status = HttpSupport.response(conn);
  310. switch (status) {
  311. case HttpConnection.HTTP_OK: {
  312. br = toBufferedReader(openInputStream(conn));
  313. try {
  314. String line = br.readLine();
  315. if (line != null && line.startsWith(RefDirectory.SYMREF)) {
  316. String target = line.substring(RefDirectory.SYMREF.length());
  317. Ref r = refs.get(target);
  318. if (r == null)
  319. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  320. r = new SymbolicRef(Constants.HEAD, r);
  321. refs.put(r.getName(), r);
  322. } else if (line != null && ObjectId.isId(line)) {
  323. Ref r = new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK,
  324. Constants.HEAD, ObjectId.fromString(line));
  325. refs.put(r.getName(), r);
  326. }
  327. } finally {
  328. br.close();
  329. }
  330. break;
  331. }
  332. case HttpConnection.HTTP_NOT_FOUND:
  333. break;
  334. default:
  335. throw new TransportException(uri, MessageFormat.format(
  336. JGitText.get().cannotReadHEAD, Integer.valueOf(status),
  337. conn.getResponseMessage()));
  338. }
  339. }
  340. WalkFetchConnection wfc = new WalkFetchConnection(this, d);
  341. wfc.available(refs);
  342. return wfc;
  343. }
  344. private BufferedReader toBufferedReader(InputStream in) {
  345. return new BufferedReader(new InputStreamReader(in, Constants.CHARSET));
  346. }
  347. @Override
  348. public PushConnection openPush() throws NotSupportedException,
  349. TransportException {
  350. final String service = SVC_RECEIVE_PACK;
  351. try {
  352. final HttpConnection c = connect(service);
  353. final InputStream in = openInputStream(c);
  354. try {
  355. if (isSmartHttp(c, service)) {
  356. readSmartHeaders(in, service);
  357. return new SmartHttpPushConnection(in);
  358. } else if (!useSmartHttp) {
  359. final String msg = JGitText.get().smartHTTPPushDisabled;
  360. throw new NotSupportedException(msg);
  361. } else {
  362. final String msg = JGitText.get().remoteDoesNotSupportSmartHTTPPush;
  363. throw new NotSupportedException(msg);
  364. }
  365. } finally {
  366. in.close();
  367. }
  368. } catch (NotSupportedException err) {
  369. throw err;
  370. } catch (TransportException err) {
  371. throw err;
  372. } catch (IOException err) {
  373. throw new TransportException(uri, JGitText.get().errorReadingInfoRefs, err);
  374. }
  375. }
  376. @Override
  377. public void close() {
  378. // No explicit connections are maintained.
  379. }
  380. /**
  381. * Set additional headers on the HTTP connection
  382. *
  383. * @param headers
  384. * a map of name:values that are to be set as headers on the HTTP
  385. * connection
  386. * @since 3.4
  387. */
  388. public void setAdditionalHeaders(Map<String, String> headers) {
  389. this.headers = headers;
  390. }
  391. private HttpConnection connect(final String service)
  392. throws TransportException, NotSupportedException {
  393. final URL u;
  394. try {
  395. final StringBuilder b = new StringBuilder();
  396. b.append(baseUrl);
  397. if (b.charAt(b.length() - 1) != '/')
  398. b.append('/');
  399. b.append(Constants.INFO_REFS);
  400. if (useSmartHttp) {
  401. b.append(b.indexOf("?") < 0 ? '?' : '&'); //$NON-NLS-1$
  402. b.append("service="); //$NON-NLS-1$
  403. b.append(service);
  404. }
  405. u = new URL(b.toString());
  406. } catch (MalformedURLException e) {
  407. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  408. }
  409. try {
  410. int authAttempts = 1;
  411. for (;;) {
  412. final HttpConnection conn = httpOpen(u);
  413. if (useSmartHttp) {
  414. String exp = "application/x-" + service + "-advertisement"; //$NON-NLS-1$ //$NON-NLS-2$
  415. conn.setRequestProperty(HDR_ACCEPT, exp + ", */*"); //$NON-NLS-1$
  416. } else {
  417. conn.setRequestProperty(HDR_ACCEPT, "*/*"); //$NON-NLS-1$
  418. }
  419. final int status = HttpSupport.response(conn);
  420. switch (status) {
  421. case HttpConnection.HTTP_OK:
  422. // Check if HttpConnection did some authentication in the
  423. // background (e.g Kerberos/SPNEGO).
  424. // That may not work for streaming requests and jgit
  425. // explicit authentication would be required
  426. if (authMethod.getType() == HttpAuthMethod.Type.NONE
  427. && conn.getHeaderField(HDR_WWW_AUTHENTICATE) != null)
  428. authMethod = HttpAuthMethod.scanResponse(conn);
  429. return conn;
  430. case HttpConnection.HTTP_NOT_FOUND:
  431. throw new NoRemoteRepositoryException(uri,
  432. MessageFormat.format(JGitText.get().uriNotFound, u));
  433. case HttpConnection.HTTP_UNAUTHORIZED:
  434. authMethod = HttpAuthMethod.scanResponse(conn);
  435. if (authMethod.getType() == HttpAuthMethod.Type.NONE)
  436. throw new TransportException(uri, MessageFormat.format(
  437. JGitText.get().authenticationNotSupported, uri));
  438. CredentialsProvider credentialsProvider = getCredentialsProvider();
  439. if (authAttempts > 1)
  440. credentialsProvider.reset(uri);
  441. if (3 < authAttempts
  442. || !authMethod.authorize(uri, credentialsProvider)) {
  443. throw new TransportException(uri,
  444. JGitText.get().notAuthorized);
  445. }
  446. authAttempts++;
  447. continue;
  448. case HttpConnection.HTTP_FORBIDDEN:
  449. throw new TransportException(uri, MessageFormat.format(
  450. JGitText.get().serviceNotPermitted, service));
  451. default:
  452. String err = status + " " + conn.getResponseMessage(); //$NON-NLS-1$
  453. throw new TransportException(uri, err);
  454. }
  455. }
  456. } catch (NotSupportedException e) {
  457. throw e;
  458. } catch (TransportException e) {
  459. throw e;
  460. } catch (IOException e) {
  461. throw new TransportException(uri, MessageFormat.format(JGitText.get().cannotOpenService, service), e);
  462. }
  463. }
  464. final HttpConnection httpOpen(URL u) throws IOException {
  465. return httpOpen(METHOD_GET, u);
  466. }
  467. /**
  468. * Open an HTTP connection.
  469. *
  470. * @param method
  471. * @param u
  472. * @return the connection
  473. * @throws IOException
  474. * @since 3.3
  475. */
  476. protected HttpConnection httpOpen(String method, URL u)
  477. throws IOException {
  478. final Proxy proxy = HttpSupport.proxyFor(proxySelector, u);
  479. HttpConnection conn = connectionFactory.create(u, proxy);
  480. if (!http.sslVerify && "https".equals(u.getProtocol())) { //$NON-NLS-1$
  481. disableSslVerify(conn);
  482. }
  483. conn.setRequestMethod(method);
  484. conn.setUseCaches(false);
  485. conn.setRequestProperty(HDR_ACCEPT_ENCODING, ENCODING_GZIP);
  486. conn.setRequestProperty(HDR_PRAGMA, "no-cache"); //$NON-NLS-1$
  487. conn.setRequestProperty(HDR_USER_AGENT, userAgent);
  488. int timeOut = getTimeout();
  489. if (timeOut != -1) {
  490. int effTimeOut = timeOut * 1000;
  491. conn.setConnectTimeout(effTimeOut);
  492. conn.setReadTimeout(effTimeOut);
  493. }
  494. if (this.headers != null && !this.headers.isEmpty()) {
  495. for (Map.Entry<String, String> entry : this.headers.entrySet())
  496. conn.setRequestProperty(entry.getKey(), entry.getValue());
  497. }
  498. authMethod.configureRequest(conn);
  499. return conn;
  500. }
  501. private void disableSslVerify(HttpConnection conn)
  502. throws IOException {
  503. final TrustManager[] trustAllCerts = new TrustManager[] { new DummyX509TrustManager() };
  504. try {
  505. conn.configure(null, trustAllCerts, null);
  506. conn.setHostnameVerifier(new DummyHostnameVerifier());
  507. } catch (KeyManagementException e) {
  508. throw new IOException(e.getMessage());
  509. } catch (NoSuchAlgorithmException e) {
  510. throw new IOException(e.getMessage());
  511. }
  512. }
  513. final InputStream openInputStream(HttpConnection conn)
  514. throws IOException {
  515. InputStream input = conn.getInputStream();
  516. if (ENCODING_GZIP.equals(conn.getHeaderField(HDR_CONTENT_ENCODING)))
  517. input = new GZIPInputStream(input);
  518. return input;
  519. }
  520. IOException wrongContentType(String expType, String actType) {
  521. final String why = MessageFormat.format(JGitText.get().expectedReceivedContentType, expType, actType);
  522. return new TransportException(uri, why);
  523. }
  524. private boolean isSmartHttp(final HttpConnection c, final String service) {
  525. final String expType = "application/x-" + service + "-advertisement"; //$NON-NLS-1$ //$NON-NLS-2$
  526. final String actType = c.getContentType();
  527. return expType.equals(actType);
  528. }
  529. private void readSmartHeaders(final InputStream in, final String service)
  530. throws IOException {
  531. // A smart reply will have a '#' after the first 4 bytes, but
  532. // a dumb reply cannot contain a '#' until after byte 41. Do a
  533. // quick check to make sure its a smart reply before we parse
  534. // as a pkt-line stream.
  535. //
  536. final byte[] magic = new byte[5];
  537. IO.readFully(in, magic, 0, magic.length);
  538. if (magic[4] != '#') {
  539. throw new TransportException(uri, MessageFormat.format(
  540. JGitText.get().expectedPktLineWithService, RawParseUtils.decode(magic)));
  541. }
  542. final PacketLineIn pckIn = new PacketLineIn(new UnionInputStream(
  543. new ByteArrayInputStream(magic), in));
  544. final String exp = "# service=" + service; //$NON-NLS-1$
  545. final String act = pckIn.readString();
  546. if (!exp.equals(act)) {
  547. throw new TransportException(uri, MessageFormat.format(
  548. JGitText.get().expectedGot, exp, act));
  549. }
  550. while (pckIn.readString() != PacketLineIn.END) {
  551. // for now, ignore the remaining header lines
  552. }
  553. }
  554. class HttpObjectDB extends WalkRemoteObjectDatabase {
  555. private final URL objectsUrl;
  556. HttpObjectDB(final URL b) {
  557. objectsUrl = b;
  558. }
  559. @Override
  560. URIish getURI() {
  561. return new URIish(objectsUrl);
  562. }
  563. @Override
  564. Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
  565. try {
  566. return readAlternates(INFO_HTTP_ALTERNATES);
  567. } catch (FileNotFoundException err) {
  568. // Fall through.
  569. }
  570. try {
  571. return readAlternates(INFO_ALTERNATES);
  572. } catch (FileNotFoundException err) {
  573. // Fall through.
  574. }
  575. return null;
  576. }
  577. @Override
  578. WalkRemoteObjectDatabase openAlternate(final String location)
  579. throws IOException {
  580. return new HttpObjectDB(new URL(objectsUrl, location));
  581. }
  582. @Override
  583. Collection<String> getPackNames() throws IOException {
  584. final Collection<String> packs = new ArrayList<String>();
  585. try {
  586. final BufferedReader br = openReader(INFO_PACKS);
  587. try {
  588. for (;;) {
  589. final String s = br.readLine();
  590. if (s == null || s.length() == 0)
  591. break;
  592. if (!s.startsWith("P pack-") || !s.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  593. throw invalidAdvertisement(s);
  594. packs.add(s.substring(2));
  595. }
  596. return packs;
  597. } finally {
  598. br.close();
  599. }
  600. } catch (FileNotFoundException err) {
  601. return packs;
  602. }
  603. }
  604. @Override
  605. FileStream open(final String path) throws IOException {
  606. final URL base = objectsUrl;
  607. final URL u = new URL(base, path);
  608. final HttpConnection c = httpOpen(u);
  609. switch (HttpSupport.response(c)) {
  610. case HttpConnection.HTTP_OK:
  611. final InputStream in = openInputStream(c);
  612. final int len = c.getContentLength();
  613. return new FileStream(in, len);
  614. case HttpConnection.HTTP_NOT_FOUND:
  615. throw new FileNotFoundException(u.toString());
  616. default:
  617. throw new IOException(u.toString() + ": " //$NON-NLS-1$
  618. + HttpSupport.response(c) + " " //$NON-NLS-1$
  619. + c.getResponseMessage());
  620. }
  621. }
  622. Map<String, Ref> readAdvertisedImpl(final BufferedReader br)
  623. throws IOException, PackProtocolException {
  624. final TreeMap<String, Ref> avail = new TreeMap<String, Ref>();
  625. for (;;) {
  626. String line = br.readLine();
  627. if (line == null)
  628. break;
  629. final int tab = line.indexOf('\t');
  630. if (tab < 0)
  631. throw invalidAdvertisement(line);
  632. String name;
  633. final ObjectId id;
  634. name = line.substring(tab + 1);
  635. id = ObjectId.fromString(line.substring(0, tab));
  636. if (name.endsWith("^{}")) { //$NON-NLS-1$
  637. name = name.substring(0, name.length() - 3);
  638. final Ref prior = avail.get(name);
  639. if (prior == null)
  640. throw outOfOrderAdvertisement(name);
  641. if (prior.getPeeledObjectId() != null)
  642. throw duplicateAdvertisement(name + "^{}"); //$NON-NLS-1$
  643. avail.put(name, new ObjectIdRef.PeeledTag(
  644. Ref.Storage.NETWORK, name,
  645. prior.getObjectId(), id));
  646. } else {
  647. Ref prior = avail.put(name, new ObjectIdRef.PeeledNonTag(
  648. Ref.Storage.NETWORK, name, id));
  649. if (prior != null)
  650. throw duplicateAdvertisement(name);
  651. }
  652. }
  653. return avail;
  654. }
  655. private PackProtocolException outOfOrderAdvertisement(final String n) {
  656. return new PackProtocolException(MessageFormat.format(JGitText.get().advertisementOfCameBefore, n, n));
  657. }
  658. private PackProtocolException invalidAdvertisement(final String n) {
  659. return new PackProtocolException(MessageFormat.format(JGitText.get().invalidAdvertisementOf, n));
  660. }
  661. private PackProtocolException duplicateAdvertisement(final String n) {
  662. return new PackProtocolException(MessageFormat.format(JGitText.get().duplicateAdvertisementsOf, n));
  663. }
  664. @Override
  665. void close() {
  666. // We do not maintain persistent connections.
  667. }
  668. }
  669. class SmartHttpFetchConnection extends BasePackFetchConnection {
  670. private MultiRequestService svc;
  671. SmartHttpFetchConnection(final InputStream advertisement)
  672. throws TransportException {
  673. super(TransportHttp.this);
  674. statelessRPC = true;
  675. init(advertisement, DisabledOutputStream.INSTANCE);
  676. outNeedsEnd = false;
  677. readAdvertisedRefs();
  678. }
  679. @Override
  680. protected void doFetch(final ProgressMonitor monitor,
  681. final Collection<Ref> want, final Set<ObjectId> have,
  682. final OutputStream outputStream) throws TransportException {
  683. try {
  684. svc = new MultiRequestService(SVC_UPLOAD_PACK);
  685. init(svc.getInputStream(), svc.getOutputStream());
  686. super.doFetch(monitor, want, have, outputStream);
  687. } finally {
  688. svc = null;
  689. }
  690. }
  691. @Override
  692. protected void onReceivePack() {
  693. svc.finalRequest = true;
  694. }
  695. }
  696. class SmartHttpPushConnection extends BasePackPushConnection {
  697. SmartHttpPushConnection(final InputStream advertisement)
  698. throws TransportException {
  699. super(TransportHttp.this);
  700. statelessRPC = true;
  701. init(advertisement, DisabledOutputStream.INSTANCE);
  702. outNeedsEnd = false;
  703. readAdvertisedRefs();
  704. }
  705. protected void doPush(final ProgressMonitor monitor,
  706. final Map<String, RemoteRefUpdate> refUpdates,
  707. OutputStream outputStream) throws TransportException {
  708. final Service svc = new MultiRequestService(SVC_RECEIVE_PACK);
  709. init(svc.getInputStream(), svc.getOutputStream());
  710. super.doPush(monitor, refUpdates, outputStream);
  711. }
  712. }
  713. /** Basic service for sending and receiving HTTP requests. */
  714. abstract class Service {
  715. protected final String serviceName;
  716. protected final String requestType;
  717. protected final String responseType;
  718. protected HttpConnection conn;
  719. protected HttpOutputStream out;
  720. protected final HttpExecuteStream execute;
  721. final UnionInputStream in;
  722. Service(String serviceName) {
  723. this.serviceName = serviceName;
  724. this.requestType = "application/x-" + serviceName + "-request"; //$NON-NLS-1$ //$NON-NLS-2$
  725. this.responseType = "application/x-" + serviceName + "-result"; //$NON-NLS-1$ //$NON-NLS-2$
  726. this.out = new HttpOutputStream();
  727. this.execute = new HttpExecuteStream();
  728. this.in = new UnionInputStream(execute);
  729. }
  730. void openStream() throws IOException {
  731. conn = httpOpen(METHOD_POST, new URL(baseUrl, serviceName));
  732. conn.setInstanceFollowRedirects(false);
  733. conn.setDoOutput(true);
  734. conn.setRequestProperty(HDR_CONTENT_TYPE, requestType);
  735. conn.setRequestProperty(HDR_ACCEPT, responseType);
  736. }
  737. void sendRequest() throws IOException {
  738. // Try to compress the content, but only if that is smaller.
  739. TemporaryBuffer buf = new TemporaryBuffer.Heap(http.postBuffer);
  740. try {
  741. GZIPOutputStream gzip = new GZIPOutputStream(buf);
  742. out.writeTo(gzip, null);
  743. gzip.close();
  744. if (out.length() < buf.length())
  745. buf = out;
  746. } catch (IOException err) {
  747. // Most likely caused by overflowing the buffer, meaning
  748. // its larger if it were compressed. Don't compress.
  749. buf = out;
  750. }
  751. openStream();
  752. if (buf != out)
  753. conn.setRequestProperty(HDR_CONTENT_ENCODING, ENCODING_GZIP);
  754. conn.setFixedLengthStreamingMode((int) buf.length());
  755. final OutputStream httpOut = conn.getOutputStream();
  756. try {
  757. buf.writeTo(httpOut, null);
  758. } finally {
  759. httpOut.close();
  760. }
  761. }
  762. void openResponse() throws IOException {
  763. final int status = HttpSupport.response(conn);
  764. if (status != HttpConnection.HTTP_OK) {
  765. throw new TransportException(uri, status + " " //$NON-NLS-1$
  766. + conn.getResponseMessage());
  767. }
  768. final String contentType = conn.getContentType();
  769. if (!responseType.equals(contentType)) {
  770. conn.getInputStream().close();
  771. throw wrongContentType(responseType, contentType);
  772. }
  773. }
  774. HttpOutputStream getOutputStream() {
  775. return out;
  776. }
  777. InputStream getInputStream() {
  778. return in;
  779. }
  780. abstract void execute() throws IOException;
  781. class HttpExecuteStream extends InputStream {
  782. public int read() throws IOException {
  783. execute();
  784. return -1;
  785. }
  786. public int read(byte[] b, int off, int len) throws IOException {
  787. execute();
  788. return -1;
  789. }
  790. public long skip(long n) throws IOException {
  791. execute();
  792. return 0;
  793. }
  794. }
  795. class HttpOutputStream extends TemporaryBuffer {
  796. HttpOutputStream() {
  797. super(http.postBuffer);
  798. }
  799. @Override
  800. protected OutputStream overflow() throws IOException {
  801. openStream();
  802. conn.setChunkedStreamingMode(0);
  803. return conn.getOutputStream();
  804. }
  805. }
  806. }
  807. /**
  808. * State required to speak multiple HTTP requests with the remote.
  809. * <p>
  810. * A service wrapper provides a normal looking InputStream and OutputStream
  811. * pair which are connected via HTTP to the named remote service. Writing to
  812. * the OutputStream is buffered until either the buffer overflows, or
  813. * reading from the InputStream occurs. If overflow occurs HTTP/1.1 and its
  814. * chunked transfer encoding is used to stream the request data to the
  815. * remote service. If the entire request fits in the memory buffer, the
  816. * older HTTP/1.0 standard and a fixed content length is used instead.
  817. * <p>
  818. * It is an error to attempt to read without there being outstanding data
  819. * ready for transmission on the OutputStream.
  820. * <p>
  821. * No state is preserved between write-read request pairs. The caller is
  822. * responsible for replaying state vector information as part of the request
  823. * data written to the OutputStream. Any session HTTP cookies may or may not
  824. * be preserved between requests, it is left up to the JVM's implementation
  825. * of the HTTP client.
  826. */
  827. class MultiRequestService extends Service {
  828. boolean finalRequest;
  829. MultiRequestService(final String serviceName) {
  830. super(serviceName);
  831. }
  832. /** Keep opening send-receive pairs to the given URI. */
  833. @Override
  834. void execute() throws IOException {
  835. out.close();
  836. if (conn == null) {
  837. if (out.length() == 0) {
  838. // Request output hasn't started yet, but more data is being
  839. // requested. If there is no request data buffered and the
  840. // final request was already sent, do nothing to ensure the
  841. // caller is shown EOF on the InputStream; otherwise an
  842. // programming error has occurred within this module.
  843. if (finalRequest)
  844. return;
  845. throw new TransportException(uri,
  846. JGitText.get().startingReadStageWithoutWrittenRequestDataPendingIsNotSupported);
  847. }
  848. sendRequest();
  849. }
  850. out.reset();
  851. openResponse();
  852. in.add(openInputStream(conn));
  853. if (!finalRequest)
  854. in.add(execute);
  855. conn = null;
  856. }
  857. }
  858. /** Service for maintaining a single long-poll connection. */
  859. class LongPollService extends Service {
  860. /**
  861. * @param serviceName
  862. */
  863. LongPollService(String serviceName) {
  864. super(serviceName);
  865. }
  866. /** Only open one send-receive request. */
  867. @Override
  868. void execute() throws IOException {
  869. out.close();
  870. if (conn == null)
  871. sendRequest();
  872. openResponse();
  873. in.add(openInputStream(conn));
  874. }
  875. }
  876. private static class DummyX509TrustManager implements X509TrustManager {
  877. public X509Certificate[] getAcceptedIssuers() {
  878. return null;
  879. }
  880. public void checkClientTrusted(X509Certificate[] certs, String authType) {
  881. // no check
  882. }
  883. public void checkServerTrusted(X509Certificate[] certs, String authType) {
  884. // no check
  885. }
  886. }
  887. private static class DummyHostnameVerifier implements HostnameVerifier {
  888. public boolean verify(String hostname, SSLSession session) {
  889. // always accept
  890. return true;
  891. }
  892. }
  893. }