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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  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. * Copyright (C) 2017, Thomas Wolf <thomas.wolf@paranor.ch>
  6. * and other copyright owners as documented in the project's IP log.
  7. *
  8. * This program and the accompanying materials are made available
  9. * under the terms of the Eclipse Distribution License v1.0 which
  10. * accompanies this distribution, is reproduced below, and is
  11. * available at http://www.eclipse.org/org/documents/edl-v10.php
  12. *
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or
  16. * without modification, are permitted provided that the following
  17. * conditions are met:
  18. *
  19. * - Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. *
  22. * - Redistributions in binary form must reproduce the above
  23. * copyright notice, this list of conditions and the following
  24. * disclaimer in the documentation and/or other materials provided
  25. * with the distribution.
  26. *
  27. * - Neither the name of the Eclipse Foundation, Inc. nor the
  28. * names of its contributors may be used to endorse or promote
  29. * products derived from this software without specific prior
  30. * written permission.
  31. *
  32. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  33. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  34. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  37. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  38. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  39. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  40. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  41. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  42. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  43. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  44. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. */
  46. package org.eclipse.jgit.transport;
  47. import static java.nio.charset.StandardCharsets.UTF_8;
  48. import static org.eclipse.jgit.lib.Constants.HEAD;
  49. import static org.eclipse.jgit.util.HttpSupport.ENCODING_GZIP;
  50. import static org.eclipse.jgit.util.HttpSupport.ENCODING_X_GZIP;
  51. import static org.eclipse.jgit.util.HttpSupport.HDR_ACCEPT;
  52. import static org.eclipse.jgit.util.HttpSupport.HDR_ACCEPT_ENCODING;
  53. import static org.eclipse.jgit.util.HttpSupport.HDR_CONTENT_ENCODING;
  54. import static org.eclipse.jgit.util.HttpSupport.HDR_CONTENT_TYPE;
  55. import static org.eclipse.jgit.util.HttpSupport.HDR_LOCATION;
  56. import static org.eclipse.jgit.util.HttpSupport.HDR_PRAGMA;
  57. import static org.eclipse.jgit.util.HttpSupport.HDR_USER_AGENT;
  58. import static org.eclipse.jgit.util.HttpSupport.HDR_WWW_AUTHENTICATE;
  59. import static org.eclipse.jgit.util.HttpSupport.METHOD_GET;
  60. import static org.eclipse.jgit.util.HttpSupport.METHOD_POST;
  61. import java.io.BufferedReader;
  62. import java.io.ByteArrayInputStream;
  63. import java.io.FileNotFoundException;
  64. import java.io.IOException;
  65. import java.io.InputStream;
  66. import java.io.InputStreamReader;
  67. import java.io.OutputStream;
  68. import java.net.MalformedURLException;
  69. import java.net.Proxy;
  70. import java.net.ProxySelector;
  71. import java.net.URISyntaxException;
  72. import java.net.URL;
  73. import java.security.cert.CertPathBuilderException;
  74. import java.security.cert.CertPathValidatorException;
  75. import java.security.cert.CertificateException;
  76. import java.text.MessageFormat;
  77. import java.util.ArrayList;
  78. import java.util.Arrays;
  79. import java.util.Collection;
  80. import java.util.Collections;
  81. import java.util.EnumSet;
  82. import java.util.HashSet;
  83. import java.util.LinkedHashSet;
  84. import java.util.Locale;
  85. import java.util.Map;
  86. import java.util.Set;
  87. import java.util.TreeMap;
  88. import java.util.zip.GZIPInputStream;
  89. import java.util.zip.GZIPOutputStream;
  90. import javax.net.ssl.SSLHandshakeException;
  91. import org.eclipse.jgit.errors.ConfigInvalidException;
  92. import org.eclipse.jgit.errors.NoRemoteRepositoryException;
  93. import org.eclipse.jgit.errors.NotSupportedException;
  94. import org.eclipse.jgit.errors.PackProtocolException;
  95. import org.eclipse.jgit.errors.TransportException;
  96. import org.eclipse.jgit.internal.JGitText;
  97. import org.eclipse.jgit.internal.storage.file.RefDirectory;
  98. import org.eclipse.jgit.lib.Constants;
  99. import org.eclipse.jgit.lib.ObjectId;
  100. import org.eclipse.jgit.lib.ObjectIdRef;
  101. import org.eclipse.jgit.lib.ProgressMonitor;
  102. import org.eclipse.jgit.lib.Ref;
  103. import org.eclipse.jgit.lib.Repository;
  104. import org.eclipse.jgit.lib.StoredConfig;
  105. import org.eclipse.jgit.lib.SymbolicRef;
  106. import org.eclipse.jgit.storage.file.FileBasedConfig;
  107. import org.eclipse.jgit.transport.HttpAuthMethod.Type;
  108. import org.eclipse.jgit.transport.HttpConfig.HttpRedirectMode;
  109. import org.eclipse.jgit.transport.http.HttpConnection;
  110. import org.eclipse.jgit.util.FS;
  111. import org.eclipse.jgit.util.HttpSupport;
  112. import org.eclipse.jgit.util.IO;
  113. import org.eclipse.jgit.util.RawParseUtils;
  114. import org.eclipse.jgit.util.SystemReader;
  115. import org.eclipse.jgit.util.TemporaryBuffer;
  116. import org.eclipse.jgit.util.io.DisabledOutputStream;
  117. import org.eclipse.jgit.util.io.UnionInputStream;
  118. import org.slf4j.Logger;
  119. import org.slf4j.LoggerFactory;
  120. /**
  121. * Transport over HTTP and FTP protocols.
  122. * <p>
  123. * If the transport is using HTTP and the remote HTTP service is Git-aware
  124. * (speaks the "smart-http protocol") this client will automatically take
  125. * advantage of the additional Git-specific HTTP extensions. If the remote
  126. * service does not support these extensions, the client will degrade to direct
  127. * file fetching.
  128. * <p>
  129. * If the remote (server side) repository does not have the specialized Git
  130. * support, object files are retrieved directly through standard HTTP GET (or
  131. * binary FTP GET) requests. This make it easy to serve a Git repository through
  132. * a standard web host provider that does not offer specific support for Git.
  133. *
  134. * @see WalkFetchConnection
  135. */
  136. public class TransportHttp extends HttpTransport implements WalkTransport,
  137. PackTransport {
  138. private static final Logger LOG = LoggerFactory
  139. .getLogger(TransportHttp.class);
  140. private static final String SVC_UPLOAD_PACK = "git-upload-pack"; //$NON-NLS-1$
  141. private static final String SVC_RECEIVE_PACK = "git-receive-pack"; //$NON-NLS-1$
  142. /**
  143. * Accept-Encoding header in the HTTP request
  144. * (https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
  145. *
  146. * @since 4.6
  147. */
  148. public enum AcceptEncoding {
  149. /**
  150. * Do not specify an Accept-Encoding header. In most servers this
  151. * results in the content being transmitted as-is.
  152. */
  153. UNSPECIFIED,
  154. /**
  155. * Accept gzip content encoding.
  156. */
  157. GZIP
  158. }
  159. static final TransportProtocol PROTO_HTTP = new TransportProtocol() {
  160. private final String[] schemeNames = { "http", "https" }; //$NON-NLS-1$ //$NON-NLS-2$
  161. private final Set<String> schemeSet = Collections
  162. .unmodifiableSet(new LinkedHashSet<>(Arrays
  163. .asList(schemeNames)));
  164. @Override
  165. public String getName() {
  166. return JGitText.get().transportProtoHTTP;
  167. }
  168. @Override
  169. public Set<String> getSchemes() {
  170. return schemeSet;
  171. }
  172. @Override
  173. public Set<URIishField> getRequiredFields() {
  174. return Collections.unmodifiableSet(EnumSet.of(URIishField.HOST,
  175. URIishField.PATH));
  176. }
  177. @Override
  178. public Set<URIishField> getOptionalFields() {
  179. return Collections.unmodifiableSet(EnumSet.of(URIishField.USER,
  180. URIishField.PASS, URIishField.PORT));
  181. }
  182. @Override
  183. public int getDefaultPort() {
  184. return 80;
  185. }
  186. @Override
  187. public Transport open(URIish uri, Repository local, String remoteName)
  188. throws NotSupportedException {
  189. return new TransportHttp(local, uri);
  190. }
  191. @Override
  192. public Transport open(URIish uri) throws NotSupportedException {
  193. return new TransportHttp(uri);
  194. }
  195. };
  196. static final TransportProtocol PROTO_FTP = new TransportProtocol() {
  197. @Override
  198. public String getName() {
  199. return JGitText.get().transportProtoFTP;
  200. }
  201. @Override
  202. public Set<String> getSchemes() {
  203. return Collections.singleton("ftp"); //$NON-NLS-1$
  204. }
  205. @Override
  206. public Set<URIishField> getRequiredFields() {
  207. return Collections.unmodifiableSet(EnumSet.of(URIishField.HOST,
  208. URIishField.PATH));
  209. }
  210. @Override
  211. public Set<URIishField> getOptionalFields() {
  212. return Collections.unmodifiableSet(EnumSet.of(URIishField.USER,
  213. URIishField.PASS, URIishField.PORT));
  214. }
  215. @Override
  216. public int getDefaultPort() {
  217. return 21;
  218. }
  219. @Override
  220. public Transport open(URIish uri, Repository local, String remoteName)
  221. throws NotSupportedException {
  222. return new TransportHttp(local, uri);
  223. }
  224. };
  225. /**
  226. * The current URI we're talking to. The inherited (final) field
  227. * {@link #uri} stores the original URI; {@code currentUri} may be different
  228. * after redirects.
  229. */
  230. private URIish currentUri;
  231. private URL baseUrl;
  232. private URL objectsUrl;
  233. private final HttpConfig http;
  234. private final ProxySelector proxySelector;
  235. private boolean useSmartHttp = true;
  236. private HttpAuthMethod authMethod = HttpAuthMethod.Type.NONE.method(null);
  237. private Map<String, String> headers;
  238. private boolean sslVerify;
  239. private boolean sslFailure = false;
  240. TransportHttp(Repository local, URIish uri)
  241. throws NotSupportedException {
  242. super(local, uri);
  243. setURI(uri);
  244. http = new HttpConfig(local.getConfig(), uri);
  245. proxySelector = ProxySelector.getDefault();
  246. sslVerify = http.isSslVerify();
  247. }
  248. private URL toURL(URIish urish) throws MalformedURLException {
  249. String uriString = urish.toString();
  250. if (!uriString.endsWith("/")) { //$NON-NLS-1$
  251. uriString += '/';
  252. }
  253. return new URL(uriString);
  254. }
  255. /**
  256. * Set uri a {@link org.eclipse.jgit.transport.URIish} object.
  257. *
  258. * @param uri
  259. * a {@link org.eclipse.jgit.transport.URIish} object.
  260. * @throws org.eclipse.jgit.errors.NotSupportedException
  261. * @since 4.9
  262. */
  263. protected void setURI(URIish uri) throws NotSupportedException {
  264. try {
  265. currentUri = uri;
  266. baseUrl = toURL(uri);
  267. objectsUrl = new URL(baseUrl, "objects/"); //$NON-NLS-1$
  268. } catch (MalformedURLException e) {
  269. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  270. }
  271. }
  272. /**
  273. * Create a minimal HTTP transport with default configuration values.
  274. *
  275. * @param uri
  276. * @throws NotSupportedException
  277. */
  278. TransportHttp(URIish uri) throws NotSupportedException {
  279. super(uri);
  280. setURI(uri);
  281. http = new HttpConfig(uri);
  282. proxySelector = ProxySelector.getDefault();
  283. sslVerify = http.isSslVerify();
  284. }
  285. /**
  286. * Toggle whether or not smart HTTP transport should be used.
  287. * <p>
  288. * This flag exists primarily to support backwards compatibility testing
  289. * within a testing framework, there is no need to modify it in most
  290. * applications.
  291. *
  292. * @param on
  293. * if {@code true} (default), smart HTTP is enabled.
  294. */
  295. public void setUseSmartHttp(boolean on) {
  296. useSmartHttp = on;
  297. }
  298. @SuppressWarnings("resource") // Closed by caller
  299. private FetchConnection getConnection(HttpConnection c, InputStream in,
  300. String service) throws IOException {
  301. BaseConnection f;
  302. if (isSmartHttp(c, service)) {
  303. readSmartHeaders(in, service);
  304. f = new SmartHttpFetchConnection(in);
  305. } else {
  306. // Assume this server doesn't support smart HTTP fetch
  307. // and fall back on dumb object walking.
  308. f = newDumbConnection(in);
  309. }
  310. f.setPeerUserAgent(c.getHeaderField(HttpSupport.HDR_SERVER));
  311. return (FetchConnection) f;
  312. }
  313. /** {@inheritDoc} */
  314. @Override
  315. public FetchConnection openFetch() throws TransportException,
  316. NotSupportedException {
  317. final String service = SVC_UPLOAD_PACK;
  318. try {
  319. final HttpConnection c = connect(service);
  320. try (InputStream in = openInputStream(c)) {
  321. return getConnection(c, in, service);
  322. }
  323. } catch (NotSupportedException | TransportException err) {
  324. throw err;
  325. } catch (IOException err) {
  326. throw new TransportException(uri, JGitText.get().errorReadingInfoRefs, err);
  327. }
  328. }
  329. private WalkFetchConnection newDumbConnection(InputStream in)
  330. throws IOException, PackProtocolException {
  331. HttpObjectDB d = new HttpObjectDB(objectsUrl);
  332. Map<String, Ref> refs;
  333. try (BufferedReader br = toBufferedReader(in)) {
  334. refs = d.readAdvertisedImpl(br);
  335. }
  336. if (!refs.containsKey(HEAD)) {
  337. // If HEAD was not published in the info/refs file (it usually
  338. // is not there) download HEAD by itself as a loose file and do
  339. // the resolution by hand.
  340. //
  341. HttpConnection conn = httpOpen(
  342. METHOD_GET,
  343. new URL(baseUrl, HEAD),
  344. AcceptEncoding.GZIP);
  345. int status = HttpSupport.response(conn);
  346. switch (status) {
  347. case HttpConnection.HTTP_OK: {
  348. try (BufferedReader br = toBufferedReader(
  349. openInputStream(conn))) {
  350. String line = br.readLine();
  351. if (line != null && line.startsWith(RefDirectory.SYMREF)) {
  352. String target = line.substring(RefDirectory.SYMREF.length());
  353. Ref r = refs.get(target);
  354. if (r == null)
  355. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  356. r = new SymbolicRef(HEAD, r);
  357. refs.put(r.getName(), r);
  358. } else if (line != null && ObjectId.isId(line)) {
  359. Ref r = new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK,
  360. HEAD, ObjectId.fromString(line));
  361. refs.put(r.getName(), r);
  362. }
  363. }
  364. break;
  365. }
  366. case HttpConnection.HTTP_NOT_FOUND:
  367. break;
  368. default:
  369. throw new TransportException(uri, MessageFormat.format(
  370. JGitText.get().cannotReadHEAD, Integer.valueOf(status),
  371. conn.getResponseMessage()));
  372. }
  373. }
  374. WalkFetchConnection wfc = new WalkFetchConnection(this, d);
  375. wfc.available(refs);
  376. return wfc;
  377. }
  378. private BufferedReader toBufferedReader(InputStream in) {
  379. return new BufferedReader(new InputStreamReader(in, UTF_8));
  380. }
  381. /** {@inheritDoc} */
  382. @Override
  383. public PushConnection openPush() throws NotSupportedException,
  384. TransportException {
  385. final String service = SVC_RECEIVE_PACK;
  386. try {
  387. final HttpConnection c = connect(service);
  388. try (InputStream in = openInputStream(c)) {
  389. if (isSmartHttp(c, service)) {
  390. return smartPush(service, c, in);
  391. } else if (!useSmartHttp) {
  392. final String msg = JGitText.get().smartHTTPPushDisabled;
  393. throw new NotSupportedException(msg);
  394. } else {
  395. final String msg = JGitText.get().remoteDoesNotSupportSmartHTTPPush;
  396. throw new NotSupportedException(msg);
  397. }
  398. }
  399. } catch (NotSupportedException | TransportException err) {
  400. throw err;
  401. } catch (IOException err) {
  402. throw new TransportException(uri, JGitText.get().errorReadingInfoRefs, err);
  403. }
  404. }
  405. private PushConnection smartPush(String service, HttpConnection c,
  406. InputStream in) throws IOException, TransportException {
  407. readSmartHeaders(in, service);
  408. SmartHttpPushConnection p = new SmartHttpPushConnection(in);
  409. p.setPeerUserAgent(c.getHeaderField(HttpSupport.HDR_SERVER));
  410. return p;
  411. }
  412. /** {@inheritDoc} */
  413. @Override
  414. public void close() {
  415. // No explicit connections are maintained.
  416. }
  417. /**
  418. * Set additional headers on the HTTP connection
  419. *
  420. * @param headers
  421. * a map of name:values that are to be set as headers on the HTTP
  422. * connection
  423. * @since 3.4
  424. */
  425. public void setAdditionalHeaders(Map<String, String> headers) {
  426. this.headers = headers;
  427. }
  428. private NoRemoteRepositoryException createNotFoundException(URIish u,
  429. URL url, String msg) {
  430. String text;
  431. if (msg != null && !msg.isEmpty()) {
  432. text = MessageFormat.format(JGitText.get().uriNotFoundWithMessage,
  433. url, msg);
  434. } else {
  435. text = MessageFormat.format(JGitText.get().uriNotFound, url);
  436. }
  437. return new NoRemoteRepositoryException(u, text);
  438. }
  439. private HttpConnection connect(String service)
  440. throws TransportException, NotSupportedException {
  441. URL u = getServiceURL(service);
  442. int authAttempts = 1;
  443. int redirects = 0;
  444. Collection<Type> ignoreTypes = null;
  445. for (;;) {
  446. try {
  447. final HttpConnection conn = httpOpen(METHOD_GET, u, AcceptEncoding.GZIP);
  448. if (useSmartHttp) {
  449. String exp = "application/x-" + service + "-advertisement"; //$NON-NLS-1$ //$NON-NLS-2$
  450. conn.setRequestProperty(HDR_ACCEPT, exp + ", */*"); //$NON-NLS-1$
  451. } else {
  452. conn.setRequestProperty(HDR_ACCEPT, "*/*"); //$NON-NLS-1$
  453. }
  454. final int status = HttpSupport.response(conn);
  455. switch (status) {
  456. case HttpConnection.HTTP_OK:
  457. // Check if HttpConnection did some authentication in the
  458. // background (e.g Kerberos/SPNEGO).
  459. // That may not work for streaming requests and jgit
  460. // explicit authentication would be required
  461. if (authMethod.getType() == HttpAuthMethod.Type.NONE
  462. && conn.getHeaderField(HDR_WWW_AUTHENTICATE) != null)
  463. authMethod = HttpAuthMethod.scanResponse(conn, ignoreTypes);
  464. return conn;
  465. case HttpConnection.HTTP_NOT_FOUND:
  466. throw createNotFoundException(uri, u,
  467. conn.getResponseMessage());
  468. case HttpConnection.HTTP_UNAUTHORIZED:
  469. authMethod = HttpAuthMethod.scanResponse(conn, ignoreTypes);
  470. if (authMethod.getType() == HttpAuthMethod.Type.NONE)
  471. throw new TransportException(uri, MessageFormat.format(
  472. JGitText.get().authenticationNotSupported, uri));
  473. CredentialsProvider credentialsProvider = getCredentialsProvider();
  474. if (credentialsProvider == null)
  475. throw new TransportException(uri,
  476. JGitText.get().noCredentialsProvider);
  477. if (authAttempts > 1)
  478. credentialsProvider.reset(currentUri);
  479. if (3 < authAttempts
  480. || !authMethod.authorize(currentUri,
  481. credentialsProvider)) {
  482. throw new TransportException(uri,
  483. JGitText.get().notAuthorized);
  484. }
  485. authAttempts++;
  486. continue;
  487. case HttpConnection.HTTP_FORBIDDEN:
  488. throw new TransportException(uri, MessageFormat.format(
  489. JGitText.get().serviceNotPermitted, baseUrl,
  490. service));
  491. case HttpConnection.HTTP_MOVED_PERM:
  492. case HttpConnection.HTTP_MOVED_TEMP:
  493. case HttpConnection.HTTP_SEE_OTHER:
  494. case HttpConnection.HTTP_11_MOVED_TEMP:
  495. // SEE_OTHER should actually never be sent by a git server,
  496. // and in general should occur only on POST requests. But it
  497. // doesn't hurt to accept it here as a redirect.
  498. if (http.getFollowRedirects() == HttpRedirectMode.FALSE) {
  499. throw new TransportException(uri,
  500. MessageFormat.format(
  501. JGitText.get().redirectsOff,
  502. Integer.valueOf(status)));
  503. }
  504. URIish newUri = redirect(conn.getHeaderField(HDR_LOCATION),
  505. Constants.INFO_REFS, redirects++);
  506. setURI(newUri);
  507. u = getServiceURL(service);
  508. authAttempts = 1;
  509. break;
  510. default:
  511. String err = status + " " + conn.getResponseMessage(); //$NON-NLS-1$
  512. throw new TransportException(uri, err);
  513. }
  514. } catch (NotSupportedException | TransportException e) {
  515. throw e;
  516. } catch (SSLHandshakeException e) {
  517. handleSslFailure(e);
  518. continue; // Re-try
  519. } catch (IOException e) {
  520. if (authMethod.getType() != HttpAuthMethod.Type.NONE) {
  521. if (ignoreTypes == null) {
  522. ignoreTypes = new HashSet<>();
  523. }
  524. ignoreTypes.add(authMethod.getType());
  525. // reset auth method & attempts for next authentication type
  526. authMethod = HttpAuthMethod.Type.NONE.method(null);
  527. authAttempts = 1;
  528. continue;
  529. }
  530. throw new TransportException(uri, MessageFormat.format(JGitText.get().cannotOpenService, service), e);
  531. }
  532. }
  533. }
  534. private static class CredentialItems {
  535. CredentialItem.InformationalMessage message;
  536. /** Trust the server for this git operation */
  537. CredentialItem.YesNoType now;
  538. /**
  539. * Trust the server for all git operations from this repository; may be
  540. * {@code null} if the transport was created via
  541. * {@link #TransportHttp(URIish)}.
  542. */
  543. CredentialItem.YesNoType forRepo;
  544. /** Always trust the server from now on. */
  545. CredentialItem.YesNoType always;
  546. public CredentialItem[] items() {
  547. if (forRepo == null) {
  548. return new CredentialItem[] { message, now, always };
  549. } else {
  550. return new CredentialItem[] { message, now, forRepo, always };
  551. }
  552. }
  553. }
  554. private void handleSslFailure(Throwable e) throws TransportException {
  555. if (sslFailure || !trustInsecureSslConnection(e.getCause())) {
  556. throw new TransportException(uri,
  557. MessageFormat.format(
  558. JGitText.get().sslFailureExceptionMessage,
  559. currentUri.setPass(null)),
  560. e);
  561. }
  562. sslFailure = true;
  563. }
  564. private boolean trustInsecureSslConnection(Throwable cause) {
  565. if (cause instanceof CertificateException
  566. || cause instanceof CertPathBuilderException
  567. || cause instanceof CertPathValidatorException) {
  568. // Certificate expired or revoked, PKIX path building not
  569. // possible, self-signed certificate, host does not match ...
  570. CredentialsProvider provider = getCredentialsProvider();
  571. if (provider != null) {
  572. CredentialItems trust = constructSslTrustItems(cause);
  573. CredentialItem[] items = trust.items();
  574. if (provider.supports(items)) {
  575. boolean answered = provider.get(uri, items);
  576. if (answered) {
  577. // Not canceled
  578. boolean trustNow = trust.now.getValue();
  579. boolean trustLocal = trust.forRepo != null
  580. && trust.forRepo.getValue();
  581. boolean trustAlways = trust.always.getValue();
  582. if (trustNow || trustLocal || trustAlways) {
  583. sslVerify = false;
  584. if (trustAlways) {
  585. updateSslVerifyUser(false);
  586. } else if (trustLocal) {
  587. updateSslVerify(local.getConfig(), false);
  588. }
  589. return true;
  590. }
  591. }
  592. }
  593. }
  594. }
  595. return false;
  596. }
  597. private CredentialItems constructSslTrustItems(Throwable cause) {
  598. CredentialItems items = new CredentialItems();
  599. String info = MessageFormat.format(JGitText.get().sslFailureInfo,
  600. currentUri.setPass(null));
  601. String sslMessage = cause.getLocalizedMessage();
  602. if (sslMessage == null) {
  603. sslMessage = cause.toString();
  604. }
  605. sslMessage = MessageFormat.format(JGitText.get().sslFailureCause,
  606. sslMessage);
  607. items.message = new CredentialItem.InformationalMessage(info + '\n'
  608. + sslMessage + '\n'
  609. + JGitText.get().sslFailureTrustExplanation);
  610. items.now = new CredentialItem.YesNoType(JGitText.get().sslTrustNow);
  611. if (local != null) {
  612. items.forRepo = new CredentialItem.YesNoType(
  613. MessageFormat.format(JGitText.get().sslTrustForRepo,
  614. local.getDirectory()));
  615. }
  616. items.always = new CredentialItem.YesNoType(
  617. JGitText.get().sslTrustAlways);
  618. return items;
  619. }
  620. private void updateSslVerify(StoredConfig config, boolean value) {
  621. // Since git uses the original URI for matching, we must also use the
  622. // original URI and cannot use the current URI (which might be different
  623. // after redirects).
  624. String uriPattern = uri.getScheme() + "://" + uri.getHost(); //$NON-NLS-1$
  625. int port = uri.getPort();
  626. if (port > 0) {
  627. uriPattern += ":" + port; //$NON-NLS-1$
  628. }
  629. config.setBoolean(HttpConfig.HTTP, uriPattern,
  630. HttpConfig.SSL_VERIFY_KEY, value);
  631. try {
  632. config.save();
  633. } catch (IOException e) {
  634. LOG.error(JGitText.get().sslVerifyCannotSave, e);
  635. }
  636. }
  637. private void updateSslVerifyUser(boolean value) {
  638. FileBasedConfig userConfig = SystemReader.getInstance()
  639. .openUserConfig(null, FS.DETECTED);
  640. try {
  641. userConfig.load();
  642. updateSslVerify(userConfig, value);
  643. } catch (IOException | ConfigInvalidException e) {
  644. // Log it, but otherwise ignore here.
  645. LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid,
  646. userConfig.getFile().getAbsolutePath(), e));
  647. }
  648. }
  649. private URIish redirect(String location, String checkFor, int redirects)
  650. throws TransportException {
  651. if (location == null || location.isEmpty()) {
  652. throw new TransportException(uri,
  653. MessageFormat.format(JGitText.get().redirectLocationMissing,
  654. baseUrl));
  655. }
  656. if (redirects >= http.getMaxRedirects()) {
  657. throw new TransportException(uri,
  658. MessageFormat.format(JGitText.get().redirectLimitExceeded,
  659. Integer.valueOf(http.getMaxRedirects()), baseUrl,
  660. location));
  661. }
  662. try {
  663. if (!isValidRedirect(baseUrl, location, checkFor)) {
  664. throw new TransportException(uri,
  665. MessageFormat.format(JGitText.get().redirectBlocked,
  666. baseUrl, location));
  667. }
  668. location = location.substring(0, location.indexOf(checkFor));
  669. URIish result = new URIish(location);
  670. if (LOG.isInfoEnabled()) {
  671. LOG.info(MessageFormat.format(JGitText.get().redirectHttp,
  672. uri.setPass(null),
  673. Integer.valueOf(redirects), baseUrl, result));
  674. }
  675. return result;
  676. } catch (URISyntaxException e) {
  677. throw new TransportException(uri,
  678. MessageFormat.format(JGitText.get().invalidRedirectLocation,
  679. baseUrl, location),
  680. e);
  681. }
  682. }
  683. private boolean isValidRedirect(URL current, String next, String checkFor) {
  684. // Protocols must be the same, or current is "http" and next "https". We
  685. // do not follow redirects from https back to http.
  686. String oldProtocol = current.getProtocol().toLowerCase(Locale.ROOT);
  687. int schemeEnd = next.indexOf("://"); //$NON-NLS-1$
  688. if (schemeEnd < 0) {
  689. return false;
  690. }
  691. String newProtocol = next.substring(0, schemeEnd)
  692. .toLowerCase(Locale.ROOT);
  693. if (!oldProtocol.equals(newProtocol)) {
  694. if (!"https".equals(newProtocol)) { //$NON-NLS-1$
  695. return false;
  696. }
  697. }
  698. // git allows only rewriting the root, i.e., everything before INFO_REFS
  699. // or the service name
  700. if (!next.contains(checkFor)) {
  701. return false;
  702. }
  703. // Basically we should test here that whatever follows INFO_REFS is
  704. // unchanged. But since we re-construct the query part
  705. // anyway, it doesn't matter.
  706. return true;
  707. }
  708. private URL getServiceURL(String service)
  709. throws NotSupportedException {
  710. try {
  711. final StringBuilder b = new StringBuilder();
  712. b.append(baseUrl);
  713. if (b.charAt(b.length() - 1) != '/') {
  714. b.append('/');
  715. }
  716. b.append(Constants.INFO_REFS);
  717. if (useSmartHttp) {
  718. b.append(b.indexOf("?") < 0 ? '?' : '&'); //$NON-NLS-1$
  719. b.append("service="); //$NON-NLS-1$
  720. b.append(service);
  721. }
  722. return new URL(b.toString());
  723. } catch (MalformedURLException e) {
  724. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  725. }
  726. }
  727. /**
  728. * Open an HTTP connection.
  729. *
  730. * @param method HTTP request method
  731. * @param u url of the HTTP connection
  732. * @param acceptEncoding accept-encoding header option
  733. * @return the HTTP connection
  734. * @throws java.io.IOException
  735. * @since 4.6
  736. */
  737. protected HttpConnection httpOpen(String method, URL u,
  738. AcceptEncoding acceptEncoding) throws IOException {
  739. if (method == null || u == null || acceptEncoding == null) {
  740. throw new NullPointerException();
  741. }
  742. final Proxy proxy = HttpSupport.proxyFor(proxySelector, u);
  743. HttpConnection conn = connectionFactory.create(u, proxy);
  744. if (!sslVerify && "https".equals(u.getProtocol())) { //$NON-NLS-1$
  745. HttpSupport.disableSslVerify(conn);
  746. }
  747. // We must do our own redirect handling to implement git rules and to
  748. // handle http->https redirects
  749. conn.setInstanceFollowRedirects(false);
  750. conn.setRequestMethod(method);
  751. conn.setUseCaches(false);
  752. if (acceptEncoding == AcceptEncoding.GZIP) {
  753. conn.setRequestProperty(HDR_ACCEPT_ENCODING, ENCODING_GZIP);
  754. }
  755. conn.setRequestProperty(HDR_PRAGMA, "no-cache"); //$NON-NLS-1$
  756. if (UserAgent.get() != null) {
  757. conn.setRequestProperty(HDR_USER_AGENT, UserAgent.get());
  758. }
  759. int timeOut = getTimeout();
  760. if (timeOut != -1) {
  761. int effTimeOut = timeOut * 1000;
  762. conn.setConnectTimeout(effTimeOut);
  763. conn.setReadTimeout(effTimeOut);
  764. }
  765. if (this.headers != null && !this.headers.isEmpty()) {
  766. for (Map.Entry<String, String> entry : this.headers.entrySet())
  767. conn.setRequestProperty(entry.getKey(), entry.getValue());
  768. }
  769. authMethod.configureRequest(conn);
  770. return conn;
  771. }
  772. final InputStream openInputStream(HttpConnection conn)
  773. throws IOException {
  774. InputStream input = conn.getInputStream();
  775. if (isGzipContent(conn))
  776. input = new GZIPInputStream(input);
  777. return input;
  778. }
  779. IOException wrongContentType(String expType, String actType) {
  780. final String why = MessageFormat.format(JGitText.get().expectedReceivedContentType, expType, actType);
  781. return new TransportException(uri, why);
  782. }
  783. private boolean isSmartHttp(HttpConnection c, String service) {
  784. final String expType = "application/x-" + service + "-advertisement"; //$NON-NLS-1$ //$NON-NLS-2$
  785. final String actType = c.getContentType();
  786. return expType.equals(actType);
  787. }
  788. private boolean isGzipContent(HttpConnection c) {
  789. return ENCODING_GZIP.equals(c.getHeaderField(HDR_CONTENT_ENCODING))
  790. || ENCODING_X_GZIP.equals(c.getHeaderField(HDR_CONTENT_ENCODING));
  791. }
  792. private void readSmartHeaders(InputStream in, String service)
  793. throws IOException {
  794. // A smart reply will have a '#' after the first 4 bytes, but
  795. // a dumb reply cannot contain a '#' until after byte 41. Do a
  796. // quick check to make sure its a smart reply before we parse
  797. // as a pkt-line stream.
  798. //
  799. final byte[] magic = new byte[5];
  800. IO.readFully(in, magic, 0, magic.length);
  801. if (magic[4] != '#') {
  802. throw new TransportException(uri, MessageFormat.format(
  803. JGitText.get().expectedPktLineWithService, RawParseUtils.decode(magic)));
  804. }
  805. final PacketLineIn pckIn = new PacketLineIn(new UnionInputStream(
  806. new ByteArrayInputStream(magic), in));
  807. final String exp = "# service=" + service; //$NON-NLS-1$
  808. final String act = pckIn.readString();
  809. if (!exp.equals(act)) {
  810. throw new TransportException(uri, MessageFormat.format(
  811. JGitText.get().expectedGot, exp, act));
  812. }
  813. while (pckIn.readString() != PacketLineIn.END) {
  814. // for now, ignore the remaining header lines
  815. }
  816. }
  817. class HttpObjectDB extends WalkRemoteObjectDatabase {
  818. private final URL httpObjectsUrl;
  819. HttpObjectDB(URL b) {
  820. httpObjectsUrl = b;
  821. }
  822. @Override
  823. URIish getURI() {
  824. return new URIish(httpObjectsUrl);
  825. }
  826. @Override
  827. Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
  828. try {
  829. return readAlternates(INFO_HTTP_ALTERNATES);
  830. } catch (FileNotFoundException err) {
  831. // Fall through.
  832. }
  833. try {
  834. return readAlternates(INFO_ALTERNATES);
  835. } catch (FileNotFoundException err) {
  836. // Fall through.
  837. }
  838. return null;
  839. }
  840. @Override
  841. WalkRemoteObjectDatabase openAlternate(String location)
  842. throws IOException {
  843. return new HttpObjectDB(new URL(httpObjectsUrl, location));
  844. }
  845. @Override
  846. BufferedReader openReader(String path) throws IOException {
  847. // Line oriented readable content is likely to compress well.
  848. // Request gzip encoding.
  849. InputStream is = open(path, AcceptEncoding.GZIP).in;
  850. return new BufferedReader(new InputStreamReader(is, UTF_8));
  851. }
  852. @Override
  853. Collection<String> getPackNames() throws IOException {
  854. final Collection<String> packs = new ArrayList<>();
  855. try (BufferedReader br = openReader(INFO_PACKS)) {
  856. for (;;) {
  857. final String s = br.readLine();
  858. if (s == null || s.length() == 0)
  859. break;
  860. if (!s.startsWith("P pack-") || !s.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  861. throw invalidAdvertisement(s);
  862. packs.add(s.substring(2));
  863. }
  864. return packs;
  865. } catch (FileNotFoundException err) {
  866. return packs;
  867. }
  868. }
  869. @Override
  870. FileStream open(String path) throws IOException {
  871. return open(path, AcceptEncoding.UNSPECIFIED);
  872. }
  873. FileStream open(String path, AcceptEncoding acceptEncoding)
  874. throws IOException {
  875. final URL base = httpObjectsUrl;
  876. final URL u = new URL(base, path);
  877. final HttpConnection c = httpOpen(METHOD_GET, u, acceptEncoding);
  878. switch (HttpSupport.response(c)) {
  879. case HttpConnection.HTTP_OK:
  880. final InputStream in = openInputStream(c);
  881. // If content is being gzipped and then transferred, the content
  882. // length in the header is the zipped content length, not the
  883. // actual content length.
  884. if (!isGzipContent(c)) {
  885. final int len = c.getContentLength();
  886. return new FileStream(in, len);
  887. }
  888. return new FileStream(in);
  889. case HttpConnection.HTTP_NOT_FOUND:
  890. throw new FileNotFoundException(u.toString());
  891. default:
  892. throw new IOException(u.toString() + ": " //$NON-NLS-1$
  893. + HttpSupport.response(c) + " " //$NON-NLS-1$
  894. + c.getResponseMessage());
  895. }
  896. }
  897. Map<String, Ref> readAdvertisedImpl(final BufferedReader br)
  898. throws IOException, PackProtocolException {
  899. final TreeMap<String, Ref> avail = new TreeMap<>();
  900. for (;;) {
  901. String line = br.readLine();
  902. if (line == null)
  903. break;
  904. final int tab = line.indexOf('\t');
  905. if (tab < 0)
  906. throw invalidAdvertisement(line);
  907. String name;
  908. final ObjectId id;
  909. name = line.substring(tab + 1);
  910. id = ObjectId.fromString(line.substring(0, tab));
  911. if (name.endsWith("^{}")) { //$NON-NLS-1$
  912. name = name.substring(0, name.length() - 3);
  913. final Ref prior = avail.get(name);
  914. if (prior == null)
  915. throw outOfOrderAdvertisement(name);
  916. if (prior.getPeeledObjectId() != null)
  917. throw duplicateAdvertisement(name + "^{}"); //$NON-NLS-1$
  918. avail.put(name, new ObjectIdRef.PeeledTag(
  919. Ref.Storage.NETWORK, name,
  920. prior.getObjectId(), id));
  921. } else {
  922. Ref prior = avail.put(name, new ObjectIdRef.PeeledNonTag(
  923. Ref.Storage.NETWORK, name, id));
  924. if (prior != null)
  925. throw duplicateAdvertisement(name);
  926. }
  927. }
  928. return avail;
  929. }
  930. private PackProtocolException outOfOrderAdvertisement(String n) {
  931. return new PackProtocolException(MessageFormat.format(JGitText.get().advertisementOfCameBefore, n, n));
  932. }
  933. private PackProtocolException invalidAdvertisement(String n) {
  934. return new PackProtocolException(MessageFormat.format(JGitText.get().invalidAdvertisementOf, n));
  935. }
  936. private PackProtocolException duplicateAdvertisement(String n) {
  937. return new PackProtocolException(MessageFormat.format(JGitText.get().duplicateAdvertisementsOf, n));
  938. }
  939. @Override
  940. void close() {
  941. // We do not maintain persistent connections.
  942. }
  943. }
  944. class SmartHttpFetchConnection extends BasePackFetchConnection {
  945. private MultiRequestService svc;
  946. SmartHttpFetchConnection(InputStream advertisement)
  947. throws TransportException {
  948. super(TransportHttp.this);
  949. statelessRPC = true;
  950. init(advertisement, DisabledOutputStream.INSTANCE);
  951. outNeedsEnd = false;
  952. readAdvertisedRefs();
  953. }
  954. @Override
  955. protected void doFetch(final ProgressMonitor monitor,
  956. final Collection<Ref> want, final Set<ObjectId> have,
  957. final OutputStream outputStream) throws TransportException {
  958. try {
  959. svc = new MultiRequestService(SVC_UPLOAD_PACK);
  960. init(svc.getInputStream(), svc.getOutputStream());
  961. super.doFetch(monitor, want, have, outputStream);
  962. } finally {
  963. svc = null;
  964. }
  965. }
  966. @Override
  967. protected void onReceivePack() {
  968. svc.finalRequest = true;
  969. }
  970. }
  971. class SmartHttpPushConnection extends BasePackPushConnection {
  972. SmartHttpPushConnection(InputStream advertisement)
  973. throws TransportException {
  974. super(TransportHttp.this);
  975. statelessRPC = true;
  976. init(advertisement, DisabledOutputStream.INSTANCE);
  977. outNeedsEnd = false;
  978. readAdvertisedRefs();
  979. }
  980. @Override
  981. protected void doPush(final ProgressMonitor monitor,
  982. final Map<String, RemoteRefUpdate> refUpdates,
  983. OutputStream outputStream) throws TransportException {
  984. final Service svc = new MultiRequestService(SVC_RECEIVE_PACK);
  985. init(svc.getInputStream(), svc.getOutputStream());
  986. super.doPush(monitor, refUpdates, outputStream);
  987. }
  988. }
  989. /** Basic service for sending and receiving HTTP requests. */
  990. abstract class Service {
  991. protected final String serviceName;
  992. protected final String requestType;
  993. protected final String responseType;
  994. protected HttpConnection conn;
  995. protected HttpOutputStream out;
  996. protected final HttpExecuteStream execute;
  997. final UnionInputStream in;
  998. Service(String serviceName) {
  999. this.serviceName = serviceName;
  1000. this.requestType = "application/x-" + serviceName + "-request"; //$NON-NLS-1$ //$NON-NLS-2$
  1001. this.responseType = "application/x-" + serviceName + "-result"; //$NON-NLS-1$ //$NON-NLS-2$
  1002. this.out = new HttpOutputStream();
  1003. this.execute = new HttpExecuteStream();
  1004. this.in = new UnionInputStream(execute);
  1005. }
  1006. void openStream() throws IOException {
  1007. conn = httpOpen(METHOD_POST, new URL(baseUrl, serviceName),
  1008. AcceptEncoding.GZIP);
  1009. conn.setInstanceFollowRedirects(false);
  1010. conn.setDoOutput(true);
  1011. conn.setRequestProperty(HDR_CONTENT_TYPE, requestType);
  1012. conn.setRequestProperty(HDR_ACCEPT, responseType);
  1013. }
  1014. void sendRequest() throws IOException {
  1015. // Try to compress the content, but only if that is smaller.
  1016. TemporaryBuffer buf = new TemporaryBuffer.Heap(
  1017. http.getPostBuffer());
  1018. try (GZIPOutputStream gzip = new GZIPOutputStream(buf)) {
  1019. out.writeTo(gzip, null);
  1020. if (out.length() < buf.length())
  1021. buf = out;
  1022. } catch (IOException err) {
  1023. // Most likely caused by overflowing the buffer, meaning
  1024. // its larger if it were compressed. Don't compress.
  1025. buf = out;
  1026. }
  1027. HttpAuthMethod authenticator = null;
  1028. Collection<Type> ignoreTypes = EnumSet.noneOf(Type.class);
  1029. // Counts number of repeated authentication attempts using the same
  1030. // authentication scheme
  1031. int authAttempts = 1;
  1032. int redirects = 0;
  1033. for (;;) {
  1034. try {
  1035. // The very first time we will try with the authentication
  1036. // method used on the initial GET request. This is a hint
  1037. // only; it may fail. If so, we'll then re-try with proper
  1038. // 401 handling, going through the available authentication
  1039. // schemes.
  1040. openStream();
  1041. if (buf != out) {
  1042. conn.setRequestProperty(HDR_CONTENT_ENCODING,
  1043. ENCODING_GZIP);
  1044. }
  1045. conn.setFixedLengthStreamingMode((int) buf.length());
  1046. try (OutputStream httpOut = conn.getOutputStream()) {
  1047. buf.writeTo(httpOut, null);
  1048. }
  1049. final int status = HttpSupport.response(conn);
  1050. switch (status) {
  1051. case HttpConnection.HTTP_OK:
  1052. // We're done.
  1053. return;
  1054. case HttpConnection.HTTP_NOT_FOUND:
  1055. throw createNotFoundException(uri, conn.getURL(),
  1056. conn.getResponseMessage());
  1057. case HttpConnection.HTTP_FORBIDDEN:
  1058. throw new TransportException(uri,
  1059. MessageFormat.format(
  1060. JGitText.get().serviceNotPermitted,
  1061. baseUrl, serviceName));
  1062. case HttpConnection.HTTP_MOVED_PERM:
  1063. case HttpConnection.HTTP_MOVED_TEMP:
  1064. case HttpConnection.HTTP_11_MOVED_TEMP:
  1065. // SEE_OTHER after a POST doesn't make sense for a git
  1066. // server, so we don't handle it here and thus we'll
  1067. // report an error in openResponse() later on.
  1068. if (http.getFollowRedirects() != HttpRedirectMode.TRUE) {
  1069. // Let openResponse() issue an error
  1070. return;
  1071. }
  1072. currentUri = redirect(conn.getHeaderField(HDR_LOCATION),
  1073. '/' + serviceName, redirects++);
  1074. try {
  1075. baseUrl = toURL(currentUri);
  1076. } catch (MalformedURLException e) {
  1077. throw new TransportException(uri,
  1078. MessageFormat.format(
  1079. JGitText.get().invalidRedirectLocation,
  1080. baseUrl, currentUri),
  1081. e);
  1082. }
  1083. continue;
  1084. case HttpConnection.HTTP_UNAUTHORIZED:
  1085. HttpAuthMethod nextMethod = HttpAuthMethod
  1086. .scanResponse(conn, ignoreTypes);
  1087. switch (nextMethod.getType()) {
  1088. case NONE:
  1089. throw new TransportException(uri,
  1090. MessageFormat.format(
  1091. JGitText.get().authenticationNotSupported,
  1092. conn.getURL()));
  1093. case NEGOTIATE:
  1094. // RFC 4559 states "When using the SPNEGO [...] with
  1095. // [...] POST, the authentication should be complete
  1096. // [...] before sending the user data." So in theory
  1097. // the initial GET should have been authenticated
  1098. // already. (Unless there was a redirect?)
  1099. //
  1100. // We try this only once:
  1101. ignoreTypes.add(HttpAuthMethod.Type.NEGOTIATE);
  1102. if (authenticator != null) {
  1103. ignoreTypes.add(authenticator.getType());
  1104. }
  1105. authAttempts = 1;
  1106. // We only do the Kerberos part of SPNEGO, which
  1107. // requires only one round.
  1108. break;
  1109. default:
  1110. // DIGEST or BASIC. Let's be sure we ignore
  1111. // NEGOTIATE; if it was available, we have tried it
  1112. // before.
  1113. ignoreTypes.add(HttpAuthMethod.Type.NEGOTIATE);
  1114. if (authenticator == null || authenticator
  1115. .getType() != nextMethod.getType()) {
  1116. if (authenticator != null) {
  1117. ignoreTypes.add(authenticator.getType());
  1118. }
  1119. authAttempts = 1;
  1120. }
  1121. break;
  1122. }
  1123. authMethod = nextMethod;
  1124. authenticator = nextMethod;
  1125. CredentialsProvider credentialsProvider = getCredentialsProvider();
  1126. if (credentialsProvider == null) {
  1127. throw new TransportException(uri,
  1128. JGitText.get().noCredentialsProvider);
  1129. }
  1130. if (authAttempts > 1) {
  1131. credentialsProvider.reset(currentUri);
  1132. }
  1133. if (3 < authAttempts || !authMethod
  1134. .authorize(currentUri, credentialsProvider)) {
  1135. throw new TransportException(uri,
  1136. JGitText.get().notAuthorized);
  1137. }
  1138. authAttempts++;
  1139. continue;
  1140. default:
  1141. // Just return here; openResponse() will report an
  1142. // appropriate error.
  1143. return;
  1144. }
  1145. } catch (SSLHandshakeException e) {
  1146. handleSslFailure(e);
  1147. continue; // Re-try
  1148. } catch (IOException e) {
  1149. if (authenticator == null || authMethod
  1150. .getType() != HttpAuthMethod.Type.NONE) {
  1151. // Can happen for instance if the server advertises
  1152. // Negotiate, but the client isn't configured for
  1153. // Kerberos. The first time (authenticator == null) we
  1154. // must re-try even if the authMethod was NONE: this may
  1155. // occur if the server advertised NTLM on the GET
  1156. // and the HttpConnection managed to successfully
  1157. // authenticate under the hood with NTLM. We might not
  1158. // have picked this up on the GET's 200 response.
  1159. if (authMethod.getType() != HttpAuthMethod.Type.NONE) {
  1160. ignoreTypes.add(authMethod.getType());
  1161. }
  1162. // Start over with the remaining available methods.
  1163. authMethod = HttpAuthMethod.Type.NONE.method(null);
  1164. authenticator = authMethod;
  1165. authAttempts = 1;
  1166. continue;
  1167. }
  1168. throw e;
  1169. }
  1170. }
  1171. }
  1172. void openResponse() throws IOException {
  1173. final int status = HttpSupport.response(conn);
  1174. if (status != HttpConnection.HTTP_OK) {
  1175. throw new TransportException(uri, status + " " //$NON-NLS-1$
  1176. + conn.getResponseMessage());
  1177. }
  1178. final String contentType = conn.getContentType();
  1179. if (!responseType.equals(contentType)) {
  1180. conn.getInputStream().close();
  1181. throw wrongContentType(responseType, contentType);
  1182. }
  1183. }
  1184. HttpOutputStream getOutputStream() {
  1185. return out;
  1186. }
  1187. InputStream getInputStream() {
  1188. return in;
  1189. }
  1190. abstract void execute() throws IOException;
  1191. class HttpExecuteStream extends InputStream {
  1192. @Override
  1193. public int read() throws IOException {
  1194. execute();
  1195. return -1;
  1196. }
  1197. @Override
  1198. public int read(byte[] b, int off, int len) throws IOException {
  1199. execute();
  1200. return -1;
  1201. }
  1202. @Override
  1203. public long skip(long n) throws IOException {
  1204. execute();
  1205. return 0;
  1206. }
  1207. }
  1208. class HttpOutputStream extends TemporaryBuffer {
  1209. HttpOutputStream() {
  1210. super(http.getPostBuffer());
  1211. }
  1212. @Override
  1213. protected OutputStream overflow() throws IOException {
  1214. openStream();
  1215. conn.setChunkedStreamingMode(0);
  1216. return conn.getOutputStream();
  1217. }
  1218. }
  1219. }
  1220. /**
  1221. * State required to speak multiple HTTP requests with the remote.
  1222. * <p>
  1223. * A service wrapper provides a normal looking InputStream and OutputStream
  1224. * pair which are connected via HTTP to the named remote service. Writing to
  1225. * the OutputStream is buffered until either the buffer overflows, or
  1226. * reading from the InputStream occurs. If overflow occurs HTTP/1.1 and its
  1227. * chunked transfer encoding is used to stream the request data to the
  1228. * remote service. If the entire request fits in the memory buffer, the
  1229. * older HTTP/1.0 standard and a fixed content length is used instead.
  1230. * <p>
  1231. * It is an error to attempt to read without there being outstanding data
  1232. * ready for transmission on the OutputStream.
  1233. * <p>
  1234. * No state is preserved between write-read request pairs. The caller is
  1235. * responsible for replaying state vector information as part of the request
  1236. * data written to the OutputStream. Any session HTTP cookies may or may not
  1237. * be preserved between requests, it is left up to the JVM's implementation
  1238. * of the HTTP client.
  1239. */
  1240. class MultiRequestService extends Service {
  1241. boolean finalRequest;
  1242. MultiRequestService(String serviceName) {
  1243. super(serviceName);
  1244. }
  1245. /** Keep opening send-receive pairs to the given URI. */
  1246. @Override
  1247. void execute() throws IOException {
  1248. out.close();
  1249. if (conn == null) {
  1250. if (out.length() == 0) {
  1251. // Request output hasn't started yet, but more data is being
  1252. // requested. If there is no request data buffered and the
  1253. // final request was already sent, do nothing to ensure the
  1254. // caller is shown EOF on the InputStream; otherwise an
  1255. // programming error has occurred within this module.
  1256. if (finalRequest)
  1257. return;
  1258. throw new TransportException(uri,
  1259. JGitText.get().startingReadStageWithoutWrittenRequestDataPendingIsNotSupported);
  1260. }
  1261. sendRequest();
  1262. }
  1263. out.reset();
  1264. openResponse();
  1265. in.add(openInputStream(conn));
  1266. if (!finalRequest)
  1267. in.add(execute);
  1268. conn = null;
  1269. }
  1270. }
  1271. /** Service for maintaining a single long-poll connection. */
  1272. class LongPollService extends Service {
  1273. /**
  1274. * @param serviceName
  1275. */
  1276. LongPollService(String serviceName) {
  1277. super(serviceName);
  1278. }
  1279. /** Only open one send-receive request. */
  1280. @Override
  1281. void execute() throws IOException {
  1282. out.close();
  1283. if (conn == null)
  1284. sendRequest();
  1285. openResponse();
  1286. in.add(openInputStream(conn));
  1287. }
  1288. }
  1289. }