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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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. 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 final Config.SectionParser<HttpConfig> HTTP_KEY = new SectionParser<HttpConfig>() {
  182. public HttpConfig parse(final Config cfg) {
  183. return new HttpConfig(cfg);
  184. }
  185. };
  186. private static class HttpConfig {
  187. final int postBuffer;
  188. final boolean sslVerify;
  189. HttpConfig(final Config rc) {
  190. postBuffer = rc.getInt("http", "postbuffer", 1 * 1024 * 1024); //$NON-NLS-1$ //$NON-NLS-2$
  191. sslVerify = rc.getBoolean("http", "sslVerify", true); //$NON-NLS-1$ //$NON-NLS-2$
  192. }
  193. private HttpConfig() {
  194. this(new Config());
  195. }
  196. }
  197. private final URL baseUrl;
  198. private final URL objectsUrl;
  199. private final HttpConfig http;
  200. private final ProxySelector proxySelector;
  201. private boolean useSmartHttp = true;
  202. private HttpAuthMethod authMethod = HttpAuthMethod.Type.NONE.method(null);
  203. private Map<String, String> headers;
  204. TransportHttp(final Repository local, final URIish uri)
  205. throws NotSupportedException {
  206. super(local, uri);
  207. try {
  208. String uriString = uri.toString();
  209. if (!uriString.endsWith("/")) //$NON-NLS-1$
  210. uriString += "/"; //$NON-NLS-1$
  211. baseUrl = new URL(uriString);
  212. objectsUrl = new URL(baseUrl, "objects/"); //$NON-NLS-1$
  213. } catch (MalformedURLException e) {
  214. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  215. }
  216. http = local.getConfig().get(HTTP_KEY);
  217. proxySelector = ProxySelector.getDefault();
  218. }
  219. /**
  220. * Create a minimal HTTP transport with default configuration values.
  221. *
  222. * @param uri
  223. * @throws NotSupportedException
  224. */
  225. TransportHttp(final URIish uri) throws NotSupportedException {
  226. super(uri);
  227. try {
  228. String uriString = uri.toString();
  229. if (!uriString.endsWith("/")) //$NON-NLS-1$
  230. uriString += "/"; //$NON-NLS-1$
  231. baseUrl = new URL(uriString);
  232. objectsUrl = new URL(baseUrl, "objects/"); //$NON-NLS-1$
  233. } catch (MalformedURLException e) {
  234. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  235. }
  236. http = new HttpConfig();
  237. proxySelector = ProxySelector.getDefault();
  238. }
  239. /**
  240. * Toggle whether or not smart HTTP transport should be used.
  241. * <p>
  242. * This flag exists primarily to support backwards compatibility testing
  243. * within a testing framework, there is no need to modify it in most
  244. * applications.
  245. *
  246. * @param on
  247. * if {@code true} (default), smart HTTP is enabled.
  248. */
  249. public void setUseSmartHttp(final boolean on) {
  250. useSmartHttp = on;
  251. }
  252. @Override
  253. public FetchConnection openFetch() throws TransportException,
  254. NotSupportedException {
  255. final String service = SVC_UPLOAD_PACK;
  256. try {
  257. final HttpConnection c = connect(service);
  258. final InputStream in = openInputStream(c);
  259. try {
  260. BaseConnection f;
  261. if (isSmartHttp(c, service)) {
  262. readSmartHeaders(in, service);
  263. f = new SmartHttpFetchConnection(in);
  264. } else {
  265. // Assume this server doesn't support smart HTTP fetch
  266. // and fall back on dumb object walking.
  267. f = newDumbConnection(in);
  268. }
  269. f.setPeerUserAgent(c.getHeaderField(HttpSupport.HDR_SERVER));
  270. return (FetchConnection) f;
  271. } finally {
  272. in.close();
  273. }
  274. } catch (NotSupportedException err) {
  275. throw err;
  276. } catch (TransportException err) {
  277. throw err;
  278. } catch (IOException err) {
  279. throw new TransportException(uri, JGitText.get().errorReadingInfoRefs, err);
  280. }
  281. }
  282. private WalkFetchConnection newDumbConnection(InputStream in)
  283. throws IOException, PackProtocolException {
  284. HttpObjectDB d = new HttpObjectDB(objectsUrl);
  285. BufferedReader br = toBufferedReader(in);
  286. Map<String, Ref> refs;
  287. try {
  288. refs = d.readAdvertisedImpl(br);
  289. } finally {
  290. br.close();
  291. }
  292. if (!refs.containsKey(Constants.HEAD)) {
  293. // If HEAD was not published in the info/refs file (it usually
  294. // is not there) download HEAD by itself as a loose file and do
  295. // the resolution by hand.
  296. //
  297. HttpConnection conn = httpOpen(new URL(baseUrl, Constants.HEAD));
  298. int status = HttpSupport.response(conn);
  299. switch (status) {
  300. case HttpConnection.HTTP_OK: {
  301. br = toBufferedReader(openInputStream(conn));
  302. try {
  303. String line = br.readLine();
  304. if (line != null && line.startsWith(RefDirectory.SYMREF)) {
  305. String target = line.substring(RefDirectory.SYMREF.length());
  306. Ref r = refs.get(target);
  307. if (r == null)
  308. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  309. r = new SymbolicRef(Constants.HEAD, r);
  310. refs.put(r.getName(), r);
  311. } else if (line != null && ObjectId.isId(line)) {
  312. Ref r = new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK,
  313. Constants.HEAD, ObjectId.fromString(line));
  314. refs.put(r.getName(), r);
  315. }
  316. } finally {
  317. br.close();
  318. }
  319. break;
  320. }
  321. case HttpConnection.HTTP_NOT_FOUND:
  322. break;
  323. default:
  324. throw new TransportException(uri, MessageFormat.format(
  325. JGitText.get().cannotReadHEAD, Integer.valueOf(status),
  326. conn.getResponseMessage()));
  327. }
  328. }
  329. WalkFetchConnection wfc = new WalkFetchConnection(this, d);
  330. wfc.available(refs);
  331. return wfc;
  332. }
  333. private BufferedReader toBufferedReader(InputStream in) {
  334. return new BufferedReader(new InputStreamReader(in, Constants.CHARSET));
  335. }
  336. @Override
  337. public PushConnection openPush() throws NotSupportedException,
  338. TransportException {
  339. final String service = SVC_RECEIVE_PACK;
  340. try {
  341. final HttpConnection c = connect(service);
  342. final InputStream in = openInputStream(c);
  343. try {
  344. if (isSmartHttp(c, service)) {
  345. return smartPush(service, c, in);
  346. } else if (!useSmartHttp) {
  347. final String msg = JGitText.get().smartHTTPPushDisabled;
  348. throw new NotSupportedException(msg);
  349. } else {
  350. final String msg = JGitText.get().remoteDoesNotSupportSmartHTTPPush;
  351. throw new NotSupportedException(msg);
  352. }
  353. } finally {
  354. in.close();
  355. }
  356. } catch (NotSupportedException err) {
  357. throw err;
  358. } catch (TransportException err) {
  359. throw err;
  360. } catch (IOException err) {
  361. throw new TransportException(uri, JGitText.get().errorReadingInfoRefs, err);
  362. }
  363. }
  364. private PushConnection smartPush(String service, HttpConnection c,
  365. InputStream in) throws IOException, TransportException {
  366. readSmartHeaders(in, service);
  367. SmartHttpPushConnection p = new SmartHttpPushConnection(in);
  368. p.setPeerUserAgent(c.getHeaderField(HttpSupport.HDR_SERVER));
  369. return p;
  370. }
  371. @Override
  372. public void close() {
  373. // No explicit connections are maintained.
  374. }
  375. /**
  376. * Set additional headers on the HTTP connection
  377. *
  378. * @param headers
  379. * a map of name:values that are to be set as headers on the HTTP
  380. * connection
  381. * @since 3.4
  382. */
  383. public void setAdditionalHeaders(Map<String, String> headers) {
  384. this.headers = headers;
  385. }
  386. private HttpConnection connect(final String service)
  387. throws TransportException, NotSupportedException {
  388. final URL u;
  389. try {
  390. final StringBuilder b = new StringBuilder();
  391. b.append(baseUrl);
  392. if (b.charAt(b.length() - 1) != '/')
  393. b.append('/');
  394. b.append(Constants.INFO_REFS);
  395. if (useSmartHttp) {
  396. b.append(b.indexOf("?") < 0 ? '?' : '&'); //$NON-NLS-1$
  397. b.append("service="); //$NON-NLS-1$
  398. b.append(service);
  399. }
  400. u = new URL(b.toString());
  401. } catch (MalformedURLException e) {
  402. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  403. }
  404. try {
  405. int authAttempts = 1;
  406. for (;;) {
  407. final HttpConnection conn = httpOpen(u);
  408. if (useSmartHttp) {
  409. String exp = "application/x-" + service + "-advertisement"; //$NON-NLS-1$ //$NON-NLS-2$
  410. conn.setRequestProperty(HDR_ACCEPT, exp + ", */*"); //$NON-NLS-1$
  411. } else {
  412. conn.setRequestProperty(HDR_ACCEPT, "*/*"); //$NON-NLS-1$
  413. }
  414. final int status = HttpSupport.response(conn);
  415. switch (status) {
  416. case HttpConnection.HTTP_OK:
  417. // Check if HttpConnection did some authentication in the
  418. // background (e.g Kerberos/SPNEGO).
  419. // That may not work for streaming requests and jgit
  420. // explicit authentication would be required
  421. if (authMethod.getType() == HttpAuthMethod.Type.NONE
  422. && conn.getHeaderField(HDR_WWW_AUTHENTICATE) != null)
  423. authMethod = HttpAuthMethod.scanResponse(conn);
  424. return conn;
  425. case HttpConnection.HTTP_NOT_FOUND:
  426. throw new NoRemoteRepositoryException(uri,
  427. MessageFormat.format(JGitText.get().uriNotFound, u));
  428. case HttpConnection.HTTP_UNAUTHORIZED:
  429. authMethod = HttpAuthMethod.scanResponse(conn);
  430. if (authMethod.getType() == HttpAuthMethod.Type.NONE)
  431. throw new TransportException(uri, MessageFormat.format(
  432. JGitText.get().authenticationNotSupported, uri));
  433. CredentialsProvider credentialsProvider = getCredentialsProvider();
  434. if (credentialsProvider == null)
  435. throw new TransportException(uri,
  436. JGitText.get().noCredentialsProvider);
  437. if (authAttempts > 1)
  438. credentialsProvider.reset(uri);
  439. if (3 < authAttempts
  440. || !authMethod.authorize(uri, credentialsProvider)) {
  441. throw new TransportException(uri,
  442. JGitText.get().notAuthorized);
  443. }
  444. authAttempts++;
  445. continue;
  446. case HttpConnection.HTTP_FORBIDDEN:
  447. throw new TransportException(uri, MessageFormat.format(
  448. JGitText.get().serviceNotPermitted, service));
  449. default:
  450. String err = status + " " + conn.getResponseMessage(); //$NON-NLS-1$
  451. throw new TransportException(uri, err);
  452. }
  453. }
  454. } catch (NotSupportedException e) {
  455. throw e;
  456. } catch (TransportException e) {
  457. throw e;
  458. } catch (IOException e) {
  459. throw new TransportException(uri, MessageFormat.format(JGitText.get().cannotOpenService, service), e);
  460. }
  461. }
  462. final HttpConnection httpOpen(URL u) throws IOException {
  463. return httpOpen(METHOD_GET, u);
  464. }
  465. /**
  466. * Open an HTTP connection.
  467. *
  468. * @param method
  469. * @param u
  470. * @return the connection
  471. * @throws IOException
  472. * @since 3.3
  473. */
  474. protected HttpConnection httpOpen(String method, URL u)
  475. throws IOException {
  476. final Proxy proxy = HttpSupport.proxyFor(proxySelector, u);
  477. HttpConnection conn = connectionFactory.create(u, proxy);
  478. if (!http.sslVerify && "https".equals(u.getProtocol())) { //$NON-NLS-1$
  479. disableSslVerify(conn);
  480. }
  481. conn.setRequestMethod(method);
  482. conn.setUseCaches(false);
  483. conn.setRequestProperty(HDR_ACCEPT_ENCODING, ENCODING_GZIP);
  484. conn.setRequestProperty(HDR_PRAGMA, "no-cache"); //$NON-NLS-1$
  485. if (UserAgent.get() != null) {
  486. conn.setRequestProperty(HDR_USER_AGENT, UserAgent.get());
  487. }
  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 httpObjectsUrl;
  556. HttpObjectDB(final URL b) {
  557. httpObjectsUrl = b;
  558. }
  559. @Override
  560. URIish getURI() {
  561. return new URIish(httpObjectsUrl);
  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(httpObjectsUrl, 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 = httpObjectsUrl;
  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. }