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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  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 org.eclipse.jgit.lib.Constants.HEAD;
  48. import static org.eclipse.jgit.util.HttpSupport.ENCODING_GZIP;
  49. import static org.eclipse.jgit.util.HttpSupport.ENCODING_X_GZIP;
  50. import static org.eclipse.jgit.util.HttpSupport.HDR_ACCEPT;
  51. import static org.eclipse.jgit.util.HttpSupport.HDR_ACCEPT_ENCODING;
  52. import static org.eclipse.jgit.util.HttpSupport.HDR_CONTENT_ENCODING;
  53. import static org.eclipse.jgit.util.HttpSupport.HDR_CONTENT_TYPE;
  54. import static org.eclipse.jgit.util.HttpSupport.HDR_LOCATION;
  55. import static org.eclipse.jgit.util.HttpSupport.HDR_PRAGMA;
  56. import static org.eclipse.jgit.util.HttpSupport.HDR_USER_AGENT;
  57. import static org.eclipse.jgit.util.HttpSupport.HDR_WWW_AUTHENTICATE;
  58. import static org.eclipse.jgit.util.HttpSupport.METHOD_GET;
  59. import static org.eclipse.jgit.util.HttpSupport.METHOD_POST;
  60. import java.io.BufferedReader;
  61. import java.io.ByteArrayInputStream;
  62. import java.io.FileNotFoundException;
  63. import java.io.IOException;
  64. import java.io.InputStream;
  65. import java.io.InputStreamReader;
  66. import java.io.OutputStream;
  67. import java.net.MalformedURLException;
  68. import java.net.Proxy;
  69. import java.net.ProxySelector;
  70. import java.net.URISyntaxException;
  71. import java.net.URL;
  72. import java.security.cert.CertPathBuilderException;
  73. import java.security.cert.CertPathValidatorException;
  74. import java.security.cert.CertificateException;
  75. import java.text.MessageFormat;
  76. import java.util.ArrayList;
  77. import java.util.Arrays;
  78. import java.util.Collection;
  79. import java.util.Collections;
  80. import java.util.EnumSet;
  81. import java.util.HashSet;
  82. import java.util.LinkedHashSet;
  83. import java.util.Locale;
  84. import java.util.Map;
  85. import java.util.Set;
  86. import java.util.TreeMap;
  87. import java.util.zip.GZIPInputStream;
  88. import java.util.zip.GZIPOutputStream;
  89. import javax.net.ssl.SSLHandshakeException;
  90. import org.eclipse.jgit.errors.ConfigInvalidException;
  91. import org.eclipse.jgit.errors.NoRemoteRepositoryException;
  92. import org.eclipse.jgit.errors.NotSupportedException;
  93. import org.eclipse.jgit.errors.PackProtocolException;
  94. import org.eclipse.jgit.errors.TransportException;
  95. import org.eclipse.jgit.internal.JGitText;
  96. import org.eclipse.jgit.internal.storage.file.RefDirectory;
  97. import org.eclipse.jgit.lib.Constants;
  98. import org.eclipse.jgit.lib.ObjectId;
  99. import org.eclipse.jgit.lib.ObjectIdRef;
  100. import org.eclipse.jgit.lib.ProgressMonitor;
  101. import org.eclipse.jgit.lib.Ref;
  102. import org.eclipse.jgit.lib.Repository;
  103. import org.eclipse.jgit.lib.StoredConfig;
  104. import org.eclipse.jgit.lib.SymbolicRef;
  105. import org.eclipse.jgit.storage.file.FileBasedConfig;
  106. import org.eclipse.jgit.transport.HttpAuthMethod.Type;
  107. import org.eclipse.jgit.transport.HttpConfig.HttpRedirectMode;
  108. import org.eclipse.jgit.transport.http.HttpConnection;
  109. import org.eclipse.jgit.util.FS;
  110. import org.eclipse.jgit.util.HttpSupport;
  111. import org.eclipse.jgit.util.IO;
  112. import org.eclipse.jgit.util.RawParseUtils;
  113. import org.eclipse.jgit.util.SystemReader;
  114. import org.eclipse.jgit.util.TemporaryBuffer;
  115. import org.eclipse.jgit.util.io.DisabledOutputStream;
  116. import org.eclipse.jgit.util.io.UnionInputStream;
  117. import org.slf4j.Logger;
  118. import org.slf4j.LoggerFactory;
  119. /**
  120. * Transport over HTTP and FTP protocols.
  121. * <p>
  122. * If the transport is using HTTP and the remote HTTP service is Git-aware
  123. * (speaks the "smart-http protocol") this client will automatically take
  124. * advantage of the additional Git-specific HTTP extensions. If the remote
  125. * service does not support these extensions, the client will degrade to direct
  126. * file fetching.
  127. * <p>
  128. * If the remote (server side) repository does not have the specialized Git
  129. * support, object files are retrieved directly through standard HTTP GET (or
  130. * binary FTP GET) requests. This make it easy to serve a Git repository through
  131. * a standard web host provider that does not offer specific support for Git.
  132. *
  133. * @see WalkFetchConnection
  134. */
  135. public class TransportHttp extends HttpTransport implements WalkTransport,
  136. PackTransport {
  137. private static final Logger LOG = LoggerFactory
  138. .getLogger(TransportHttp.class);
  139. private static final String SVC_UPLOAD_PACK = "git-upload-pack"; //$NON-NLS-1$
  140. private static final String SVC_RECEIVE_PACK = "git-receive-pack"; //$NON-NLS-1$
  141. /**
  142. * Accept-Encoding header in the HTTP request
  143. * (https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
  144. *
  145. * @since 4.6
  146. */
  147. public enum AcceptEncoding {
  148. /**
  149. * Do not specify an Accept-Encoding header. In most servers this
  150. * results in the content being transmitted as-is.
  151. */
  152. UNSPECIFIED,
  153. /**
  154. * Accept gzip content encoding.
  155. */
  156. GZIP
  157. }
  158. static final TransportProtocol PROTO_HTTP = new TransportProtocol() {
  159. private final String[] schemeNames = { "http", "https" }; //$NON-NLS-1$ //$NON-NLS-2$
  160. private final Set<String> schemeSet = Collections
  161. .unmodifiableSet(new LinkedHashSet<>(Arrays
  162. .asList(schemeNames)));
  163. @Override
  164. public String getName() {
  165. return JGitText.get().transportProtoHTTP;
  166. }
  167. @Override
  168. public Set<String> getSchemes() {
  169. return schemeSet;
  170. }
  171. @Override
  172. public Set<URIishField> getRequiredFields() {
  173. return Collections.unmodifiableSet(EnumSet.of(URIishField.HOST,
  174. URIishField.PATH));
  175. }
  176. @Override
  177. public Set<URIishField> getOptionalFields() {
  178. return Collections.unmodifiableSet(EnumSet.of(URIishField.USER,
  179. URIishField.PASS, URIishField.PORT));
  180. }
  181. @Override
  182. public int getDefaultPort() {
  183. return 80;
  184. }
  185. @Override
  186. public Transport open(URIish uri, Repository local, String remoteName)
  187. throws NotSupportedException {
  188. return new TransportHttp(local, uri);
  189. }
  190. @Override
  191. public Transport open(URIish uri) throws NotSupportedException {
  192. return new TransportHttp(uri);
  193. }
  194. };
  195. static final TransportProtocol PROTO_FTP = new TransportProtocol() {
  196. @Override
  197. public String getName() {
  198. return JGitText.get().transportProtoFTP;
  199. }
  200. @Override
  201. public Set<String> getSchemes() {
  202. return Collections.singleton("ftp"); //$NON-NLS-1$
  203. }
  204. @Override
  205. public Set<URIishField> getRequiredFields() {
  206. return Collections.unmodifiableSet(EnumSet.of(URIishField.HOST,
  207. URIishField.PATH));
  208. }
  209. @Override
  210. public Set<URIishField> getOptionalFields() {
  211. return Collections.unmodifiableSet(EnumSet.of(URIishField.USER,
  212. URIishField.PASS, URIishField.PORT));
  213. }
  214. @Override
  215. public int getDefaultPort() {
  216. return 21;
  217. }
  218. @Override
  219. public Transport open(URIish uri, Repository local, String remoteName)
  220. throws NotSupportedException {
  221. return new TransportHttp(local, uri);
  222. }
  223. };
  224. /**
  225. * The current URI we're talking to. The inherited (final) field
  226. * {@link #uri} stores the original URI; {@code currentUri} may be different
  227. * after redirects.
  228. */
  229. private URIish currentUri;
  230. private URL baseUrl;
  231. private URL objectsUrl;
  232. private final HttpConfig http;
  233. private final ProxySelector proxySelector;
  234. private boolean useSmartHttp = true;
  235. private HttpAuthMethod authMethod = HttpAuthMethod.Type.NONE.method(null);
  236. private Map<String, String> headers;
  237. private boolean sslVerify;
  238. private boolean sslFailure = false;
  239. TransportHttp(final Repository local, final URIish uri)
  240. throws NotSupportedException {
  241. super(local, uri);
  242. setURI(uri);
  243. http = new HttpConfig(local.getConfig(), uri);
  244. proxySelector = ProxySelector.getDefault();
  245. sslVerify = http.isSslVerify();
  246. }
  247. private URL toURL(URIish urish) throws MalformedURLException {
  248. String uriString = urish.toString();
  249. if (!uriString.endsWith("/")) { //$NON-NLS-1$
  250. uriString += '/';
  251. }
  252. return new URL(uriString);
  253. }
  254. /**
  255. * Set uri a {@link org.eclipse.jgit.transport.URIish} object.
  256. *
  257. * @param uri
  258. * a {@link org.eclipse.jgit.transport.URIish} object.
  259. * @throws org.eclipse.jgit.errors.NotSupportedException
  260. * @since 4.9
  261. */
  262. protected void setURI(final URIish uri) throws NotSupportedException {
  263. try {
  264. currentUri = uri;
  265. baseUrl = toURL(uri);
  266. objectsUrl = new URL(baseUrl, "objects/"); //$NON-NLS-1$
  267. } catch (MalformedURLException e) {
  268. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  269. }
  270. }
  271. /**
  272. * Create a minimal HTTP transport with default configuration values.
  273. *
  274. * @param uri
  275. * @throws NotSupportedException
  276. */
  277. TransportHttp(final URIish uri) throws NotSupportedException {
  278. super(uri);
  279. setURI(uri);
  280. http = new HttpConfig(uri);
  281. proxySelector = ProxySelector.getDefault();
  282. sslVerify = http.isSslVerify();
  283. }
  284. /**
  285. * Toggle whether or not smart HTTP transport should be used.
  286. * <p>
  287. * This flag exists primarily to support backwards compatibility testing
  288. * within a testing framework, there is no need to modify it in most
  289. * applications.
  290. *
  291. * @param on
  292. * if {@code true} (default), smart HTTP is enabled.
  293. */
  294. public void setUseSmartHttp(final boolean on) {
  295. useSmartHttp = on;
  296. }
  297. /** {@inheritDoc} */
  298. @Override
  299. public FetchConnection openFetch() throws TransportException,
  300. NotSupportedException {
  301. final String service = SVC_UPLOAD_PACK;
  302. try {
  303. final HttpConnection c = connect(service);
  304. final InputStream in = openInputStream(c);
  305. try {
  306. BaseConnection f;
  307. if (isSmartHttp(c, service)) {
  308. readSmartHeaders(in, service);
  309. f = new SmartHttpFetchConnection(in);
  310. } else {
  311. // Assume this server doesn't support smart HTTP fetch
  312. // and fall back on dumb object walking.
  313. f = newDumbConnection(in);
  314. }
  315. f.setPeerUserAgent(c.getHeaderField(HttpSupport.HDR_SERVER));
  316. return (FetchConnection) f;
  317. } finally {
  318. in.close();
  319. }
  320. } catch (NotSupportedException err) {
  321. throw err;
  322. } catch (TransportException err) {
  323. throw err;
  324. } catch (IOException err) {
  325. throw new TransportException(uri, JGitText.get().errorReadingInfoRefs, err);
  326. }
  327. }
  328. private WalkFetchConnection newDumbConnection(InputStream in)
  329. throws IOException, PackProtocolException {
  330. HttpObjectDB d = new HttpObjectDB(objectsUrl);
  331. BufferedReader br = toBufferedReader(in);
  332. Map<String, Ref> refs;
  333. try {
  334. refs = d.readAdvertisedImpl(br);
  335. } finally {
  336. br.close();
  337. }
  338. if (!refs.containsKey(HEAD)) {
  339. // If HEAD was not published in the info/refs file (it usually
  340. // is not there) download HEAD by itself as a loose file and do
  341. // the resolution by hand.
  342. //
  343. HttpConnection conn = httpOpen(
  344. METHOD_GET,
  345. new URL(baseUrl, HEAD),
  346. AcceptEncoding.GZIP);
  347. int status = HttpSupport.response(conn);
  348. switch (status) {
  349. case HttpConnection.HTTP_OK: {
  350. br = toBufferedReader(openInputStream(conn));
  351. try {
  352. String line = br.readLine();
  353. if (line != null && line.startsWith(RefDirectory.SYMREF)) {
  354. String target = line.substring(RefDirectory.SYMREF.length());
  355. Ref r = refs.get(target);
  356. if (r == null)
  357. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  358. r = new SymbolicRef(HEAD, r);
  359. refs.put(r.getName(), r);
  360. } else if (line != null && ObjectId.isId(line)) {
  361. Ref r = new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK,
  362. HEAD, ObjectId.fromString(line));
  363. refs.put(r.getName(), r);
  364. }
  365. } finally {
  366. br.close();
  367. }
  368. break;
  369. }
  370. case HttpConnection.HTTP_NOT_FOUND:
  371. break;
  372. default:
  373. throw new TransportException(uri, MessageFormat.format(
  374. JGitText.get().cannotReadHEAD, Integer.valueOf(status),
  375. conn.getResponseMessage()));
  376. }
  377. }
  378. WalkFetchConnection wfc = new WalkFetchConnection(this, d);
  379. wfc.available(refs);
  380. return wfc;
  381. }
  382. private BufferedReader toBufferedReader(InputStream in) {
  383. return new BufferedReader(new InputStreamReader(in, Constants.CHARSET));
  384. }
  385. /** {@inheritDoc} */
  386. @Override
  387. public PushConnection openPush() throws NotSupportedException,
  388. TransportException {
  389. final String service = SVC_RECEIVE_PACK;
  390. try {
  391. final HttpConnection c = connect(service);
  392. final InputStream in = openInputStream(c);
  393. try {
  394. if (isSmartHttp(c, service)) {
  395. return smartPush(service, c, in);
  396. } else if (!useSmartHttp) {
  397. final String msg = JGitText.get().smartHTTPPushDisabled;
  398. throw new NotSupportedException(msg);
  399. } else {
  400. final String msg = JGitText.get().remoteDoesNotSupportSmartHTTPPush;
  401. throw new NotSupportedException(msg);
  402. }
  403. } finally {
  404. in.close();
  405. }
  406. } catch (NotSupportedException err) {
  407. throw err;
  408. } catch (TransportException err) {
  409. throw err;
  410. } catch (IOException err) {
  411. throw new TransportException(uri, JGitText.get().errorReadingInfoRefs, err);
  412. }
  413. }
  414. private PushConnection smartPush(String service, HttpConnection c,
  415. InputStream in) throws IOException, TransportException {
  416. readSmartHeaders(in, service);
  417. SmartHttpPushConnection p = new SmartHttpPushConnection(in);
  418. p.setPeerUserAgent(c.getHeaderField(HttpSupport.HDR_SERVER));
  419. return p;
  420. }
  421. /** {@inheritDoc} */
  422. @Override
  423. public void close() {
  424. // No explicit connections are maintained.
  425. }
  426. /**
  427. * Set additional headers on the HTTP connection
  428. *
  429. * @param headers
  430. * a map of name:values that are to be set as headers on the HTTP
  431. * connection
  432. * @since 3.4
  433. */
  434. public void setAdditionalHeaders(Map<String, String> headers) {
  435. this.headers = headers;
  436. }
  437. private HttpConnection connect(final String service)
  438. throws TransportException, NotSupportedException {
  439. URL u = getServiceURL(service);
  440. int authAttempts = 1;
  441. int redirects = 0;
  442. Collection<Type> ignoreTypes = null;
  443. for (;;) {
  444. try {
  445. final HttpConnection conn = httpOpen(METHOD_GET, u, AcceptEncoding.GZIP);
  446. if (useSmartHttp) {
  447. String exp = "application/x-" + service + "-advertisement"; //$NON-NLS-1$ //$NON-NLS-2$
  448. conn.setRequestProperty(HDR_ACCEPT, exp + ", */*"); //$NON-NLS-1$
  449. } else {
  450. conn.setRequestProperty(HDR_ACCEPT, "*/*"); //$NON-NLS-1$
  451. }
  452. final int status = HttpSupport.response(conn);
  453. switch (status) {
  454. case HttpConnection.HTTP_OK:
  455. // Check if HttpConnection did some authentication in the
  456. // background (e.g Kerberos/SPNEGO).
  457. // That may not work for streaming requests and jgit
  458. // explicit authentication would be required
  459. if (authMethod.getType() == HttpAuthMethod.Type.NONE
  460. && conn.getHeaderField(HDR_WWW_AUTHENTICATE) != null)
  461. authMethod = HttpAuthMethod.scanResponse(conn, ignoreTypes);
  462. return conn;
  463. case HttpConnection.HTTP_NOT_FOUND:
  464. throw new NoRemoteRepositoryException(uri,
  465. MessageFormat.format(JGitText.get().uriNotFound, u));
  466. case HttpConnection.HTTP_UNAUTHORIZED:
  467. authMethod = HttpAuthMethod.scanResponse(conn, ignoreTypes);
  468. if (authMethod.getType() == HttpAuthMethod.Type.NONE)
  469. throw new TransportException(uri, MessageFormat.format(
  470. JGitText.get().authenticationNotSupported, uri));
  471. CredentialsProvider credentialsProvider = getCredentialsProvider();
  472. if (credentialsProvider == null)
  473. throw new TransportException(uri,
  474. JGitText.get().noCredentialsProvider);
  475. if (authAttempts > 1)
  476. credentialsProvider.reset(currentUri);
  477. if (3 < authAttempts
  478. || !authMethod.authorize(currentUri,
  479. credentialsProvider)) {
  480. throw new TransportException(uri,
  481. JGitText.get().notAuthorized);
  482. }
  483. authAttempts++;
  484. continue;
  485. case HttpConnection.HTTP_FORBIDDEN:
  486. throw new TransportException(uri, MessageFormat.format(
  487. JGitText.get().serviceNotPermitted, baseUrl,
  488. service));
  489. case HttpConnection.HTTP_MOVED_PERM:
  490. case HttpConnection.HTTP_MOVED_TEMP:
  491. case HttpConnection.HTTP_SEE_OTHER:
  492. case HttpConnection.HTTP_11_MOVED_TEMP:
  493. // SEE_OTHER should actually never be sent by a git server,
  494. // and in general should occur only on POST requests. But it
  495. // doesn't hurt to accept it here as a redirect.
  496. if (http.getFollowRedirects() == HttpRedirectMode.FALSE) {
  497. throw new TransportException(uri,
  498. MessageFormat.format(
  499. JGitText.get().redirectsOff,
  500. Integer.valueOf(status)));
  501. }
  502. URIish newUri = redirect(conn.getHeaderField(HDR_LOCATION),
  503. Constants.INFO_REFS, redirects++);
  504. setURI(newUri);
  505. u = getServiceURL(service);
  506. authAttempts = 1;
  507. break;
  508. default:
  509. String err = status + " " + conn.getResponseMessage(); //$NON-NLS-1$
  510. throw new TransportException(uri, err);
  511. }
  512. } catch (NotSupportedException e) {
  513. throw e;
  514. } catch (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.indexOf(checkFor) < 0) {
  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(final 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, setting the accept-encoding request header to gzip.
  729. *
  730. * @param method HTTP request method
  731. * @param u url of the HTTP connection
  732. * @return the HTTP connection
  733. * @throws java.io.IOException
  734. * @since 3.3
  735. * @deprecated use {@link #httpOpen(String, URL, AcceptEncoding)} instead.
  736. */
  737. @Deprecated
  738. protected HttpConnection httpOpen(String method, URL u) throws IOException {
  739. return httpOpen(method, u, AcceptEncoding.GZIP);
  740. }
  741. /**
  742. * Open an HTTP connection.
  743. *
  744. * @param method HTTP request method
  745. * @param u url of the HTTP connection
  746. * @param acceptEncoding accept-encoding header option
  747. * @return the HTTP connection
  748. * @throws java.io.IOException
  749. * @since 4.6
  750. */
  751. protected HttpConnection httpOpen(String method, URL u,
  752. AcceptEncoding acceptEncoding) throws IOException {
  753. if (method == null || u == null || acceptEncoding == null) {
  754. throw new NullPointerException();
  755. }
  756. final Proxy proxy = HttpSupport.proxyFor(proxySelector, u);
  757. HttpConnection conn = connectionFactory.create(u, proxy);
  758. if (!sslVerify && "https".equals(u.getProtocol())) { //$NON-NLS-1$
  759. HttpSupport.disableSslVerify(conn);
  760. }
  761. // We must do our own redirect handling to implement git rules and to
  762. // handle http->https redirects
  763. conn.setInstanceFollowRedirects(false);
  764. conn.setRequestMethod(method);
  765. conn.setUseCaches(false);
  766. if (acceptEncoding == AcceptEncoding.GZIP) {
  767. conn.setRequestProperty(HDR_ACCEPT_ENCODING, ENCODING_GZIP);
  768. }
  769. conn.setRequestProperty(HDR_PRAGMA, "no-cache"); //$NON-NLS-1$
  770. if (UserAgent.get() != null) {
  771. conn.setRequestProperty(HDR_USER_AGENT, UserAgent.get());
  772. }
  773. int timeOut = getTimeout();
  774. if (timeOut != -1) {
  775. int effTimeOut = timeOut * 1000;
  776. conn.setConnectTimeout(effTimeOut);
  777. conn.setReadTimeout(effTimeOut);
  778. }
  779. if (this.headers != null && !this.headers.isEmpty()) {
  780. for (Map.Entry<String, String> entry : this.headers.entrySet())
  781. conn.setRequestProperty(entry.getKey(), entry.getValue());
  782. }
  783. authMethod.configureRequest(conn);
  784. return conn;
  785. }
  786. final InputStream openInputStream(HttpConnection conn)
  787. throws IOException {
  788. InputStream input = conn.getInputStream();
  789. if (isGzipContent(conn))
  790. input = new GZIPInputStream(input);
  791. return input;
  792. }
  793. IOException wrongContentType(String expType, String actType) {
  794. final String why = MessageFormat.format(JGitText.get().expectedReceivedContentType, expType, actType);
  795. return new TransportException(uri, why);
  796. }
  797. private boolean isSmartHttp(final HttpConnection c, final String service) {
  798. final String expType = "application/x-" + service + "-advertisement"; //$NON-NLS-1$ //$NON-NLS-2$
  799. final String actType = c.getContentType();
  800. return expType.equals(actType);
  801. }
  802. private boolean isGzipContent(final HttpConnection c) {
  803. return ENCODING_GZIP.equals(c.getHeaderField(HDR_CONTENT_ENCODING))
  804. || ENCODING_X_GZIP.equals(c.getHeaderField(HDR_CONTENT_ENCODING));
  805. }
  806. private void readSmartHeaders(final InputStream in, final String service)
  807. throws IOException {
  808. // A smart reply will have a '#' after the first 4 bytes, but
  809. // a dumb reply cannot contain a '#' until after byte 41. Do a
  810. // quick check to make sure its a smart reply before we parse
  811. // as a pkt-line stream.
  812. //
  813. final byte[] magic = new byte[5];
  814. IO.readFully(in, magic, 0, magic.length);
  815. if (magic[4] != '#') {
  816. throw new TransportException(uri, MessageFormat.format(
  817. JGitText.get().expectedPktLineWithService, RawParseUtils.decode(magic)));
  818. }
  819. final PacketLineIn pckIn = new PacketLineIn(new UnionInputStream(
  820. new ByteArrayInputStream(magic), in));
  821. final String exp = "# service=" + service; //$NON-NLS-1$
  822. final String act = pckIn.readString();
  823. if (!exp.equals(act)) {
  824. throw new TransportException(uri, MessageFormat.format(
  825. JGitText.get().expectedGot, exp, act));
  826. }
  827. while (pckIn.readString() != PacketLineIn.END) {
  828. // for now, ignore the remaining header lines
  829. }
  830. }
  831. class HttpObjectDB extends WalkRemoteObjectDatabase {
  832. private final URL httpObjectsUrl;
  833. HttpObjectDB(final URL b) {
  834. httpObjectsUrl = b;
  835. }
  836. @Override
  837. URIish getURI() {
  838. return new URIish(httpObjectsUrl);
  839. }
  840. @Override
  841. Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
  842. try {
  843. return readAlternates(INFO_HTTP_ALTERNATES);
  844. } catch (FileNotFoundException err) {
  845. // Fall through.
  846. }
  847. try {
  848. return readAlternates(INFO_ALTERNATES);
  849. } catch (FileNotFoundException err) {
  850. // Fall through.
  851. }
  852. return null;
  853. }
  854. @Override
  855. WalkRemoteObjectDatabase openAlternate(final String location)
  856. throws IOException {
  857. return new HttpObjectDB(new URL(httpObjectsUrl, location));
  858. }
  859. @Override
  860. BufferedReader openReader(String path) throws IOException {
  861. // Line oriented readable content is likely to compress well.
  862. // Request gzip encoding.
  863. InputStream is = open(path, AcceptEncoding.GZIP).in;
  864. return new BufferedReader(new InputStreamReader(is, Constants.CHARSET));
  865. }
  866. @Override
  867. Collection<String> getPackNames() throws IOException {
  868. final Collection<String> packs = new ArrayList<>();
  869. try {
  870. final BufferedReader br = openReader(INFO_PACKS);
  871. try {
  872. for (;;) {
  873. final String s = br.readLine();
  874. if (s == null || s.length() == 0)
  875. break;
  876. if (!s.startsWith("P pack-") || !s.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  877. throw invalidAdvertisement(s);
  878. packs.add(s.substring(2));
  879. }
  880. return packs;
  881. } finally {
  882. br.close();
  883. }
  884. } catch (FileNotFoundException err) {
  885. return packs;
  886. }
  887. }
  888. @Override
  889. FileStream open(final String path) throws IOException {
  890. return open(path, AcceptEncoding.UNSPECIFIED);
  891. }
  892. FileStream open(String path, AcceptEncoding acceptEncoding)
  893. throws IOException {
  894. final URL base = httpObjectsUrl;
  895. final URL u = new URL(base, path);
  896. final HttpConnection c = httpOpen(METHOD_GET, u, acceptEncoding);
  897. switch (HttpSupport.response(c)) {
  898. case HttpConnection.HTTP_OK:
  899. final InputStream in = openInputStream(c);
  900. // If content is being gzipped and then transferred, the content
  901. // length in the header is the zipped content length, not the
  902. // actual content length.
  903. if (!isGzipContent(c)) {
  904. final int len = c.getContentLength();
  905. return new FileStream(in, len);
  906. }
  907. return new FileStream(in);
  908. case HttpConnection.HTTP_NOT_FOUND:
  909. throw new FileNotFoundException(u.toString());
  910. default:
  911. throw new IOException(u.toString() + ": " //$NON-NLS-1$
  912. + HttpSupport.response(c) + " " //$NON-NLS-1$
  913. + c.getResponseMessage());
  914. }
  915. }
  916. Map<String, Ref> readAdvertisedImpl(final BufferedReader br)
  917. throws IOException, PackProtocolException {
  918. final TreeMap<String, Ref> avail = new TreeMap<>();
  919. for (;;) {
  920. String line = br.readLine();
  921. if (line == null)
  922. break;
  923. final int tab = line.indexOf('\t');
  924. if (tab < 0)
  925. throw invalidAdvertisement(line);
  926. String name;
  927. final ObjectId id;
  928. name = line.substring(tab + 1);
  929. id = ObjectId.fromString(line.substring(0, tab));
  930. if (name.endsWith("^{}")) { //$NON-NLS-1$
  931. name = name.substring(0, name.length() - 3);
  932. final Ref prior = avail.get(name);
  933. if (prior == null)
  934. throw outOfOrderAdvertisement(name);
  935. if (prior.getPeeledObjectId() != null)
  936. throw duplicateAdvertisement(name + "^{}"); //$NON-NLS-1$
  937. avail.put(name, new ObjectIdRef.PeeledTag(
  938. Ref.Storage.NETWORK, name,
  939. prior.getObjectId(), id));
  940. } else {
  941. Ref prior = avail.put(name, new ObjectIdRef.PeeledNonTag(
  942. Ref.Storage.NETWORK, name, id));
  943. if (prior != null)
  944. throw duplicateAdvertisement(name);
  945. }
  946. }
  947. return avail;
  948. }
  949. private PackProtocolException outOfOrderAdvertisement(final String n) {
  950. return new PackProtocolException(MessageFormat.format(JGitText.get().advertisementOfCameBefore, n, n));
  951. }
  952. private PackProtocolException invalidAdvertisement(final String n) {
  953. return new PackProtocolException(MessageFormat.format(JGitText.get().invalidAdvertisementOf, n));
  954. }
  955. private PackProtocolException duplicateAdvertisement(final String n) {
  956. return new PackProtocolException(MessageFormat.format(JGitText.get().duplicateAdvertisementsOf, n));
  957. }
  958. @Override
  959. void close() {
  960. // We do not maintain persistent connections.
  961. }
  962. }
  963. class SmartHttpFetchConnection extends BasePackFetchConnection {
  964. private MultiRequestService svc;
  965. SmartHttpFetchConnection(final InputStream advertisement)
  966. throws TransportException {
  967. super(TransportHttp.this);
  968. statelessRPC = true;
  969. init(advertisement, DisabledOutputStream.INSTANCE);
  970. outNeedsEnd = false;
  971. readAdvertisedRefs();
  972. }
  973. @Override
  974. protected void doFetch(final ProgressMonitor monitor,
  975. final Collection<Ref> want, final Set<ObjectId> have,
  976. final OutputStream outputStream) throws TransportException {
  977. try {
  978. svc = new MultiRequestService(SVC_UPLOAD_PACK);
  979. init(svc.getInputStream(), svc.getOutputStream());
  980. super.doFetch(monitor, want, have, outputStream);
  981. } finally {
  982. svc = null;
  983. }
  984. }
  985. @Override
  986. protected void onReceivePack() {
  987. svc.finalRequest = true;
  988. }
  989. }
  990. class SmartHttpPushConnection extends BasePackPushConnection {
  991. SmartHttpPushConnection(final InputStream advertisement)
  992. throws TransportException {
  993. super(TransportHttp.this);
  994. statelessRPC = true;
  995. init(advertisement, DisabledOutputStream.INSTANCE);
  996. outNeedsEnd = false;
  997. readAdvertisedRefs();
  998. }
  999. @Override
  1000. protected void doPush(final ProgressMonitor monitor,
  1001. final Map<String, RemoteRefUpdate> refUpdates,
  1002. OutputStream outputStream) throws TransportException {
  1003. final Service svc = new MultiRequestService(SVC_RECEIVE_PACK);
  1004. init(svc.getInputStream(), svc.getOutputStream());
  1005. super.doPush(monitor, refUpdates, outputStream);
  1006. }
  1007. }
  1008. /** Basic service for sending and receiving HTTP requests. */
  1009. abstract class Service {
  1010. protected final String serviceName;
  1011. protected final String requestType;
  1012. protected final String responseType;
  1013. protected HttpConnection conn;
  1014. protected HttpOutputStream out;
  1015. protected final HttpExecuteStream execute;
  1016. final UnionInputStream in;
  1017. Service(String serviceName) {
  1018. this.serviceName = serviceName;
  1019. this.requestType = "application/x-" + serviceName + "-request"; //$NON-NLS-1$ //$NON-NLS-2$
  1020. this.responseType = "application/x-" + serviceName + "-result"; //$NON-NLS-1$ //$NON-NLS-2$
  1021. this.out = new HttpOutputStream();
  1022. this.execute = new HttpExecuteStream();
  1023. this.in = new UnionInputStream(execute);
  1024. }
  1025. void openStream() throws IOException {
  1026. conn = httpOpen(METHOD_POST, new URL(baseUrl, serviceName),
  1027. AcceptEncoding.GZIP);
  1028. conn.setInstanceFollowRedirects(false);
  1029. conn.setDoOutput(true);
  1030. conn.setRequestProperty(HDR_CONTENT_TYPE, requestType);
  1031. conn.setRequestProperty(HDR_ACCEPT, responseType);
  1032. }
  1033. void sendRequest() throws IOException {
  1034. // Try to compress the content, but only if that is smaller.
  1035. TemporaryBuffer buf = new TemporaryBuffer.Heap(
  1036. http.getPostBuffer());
  1037. try {
  1038. GZIPOutputStream gzip = new GZIPOutputStream(buf);
  1039. out.writeTo(gzip, null);
  1040. gzip.close();
  1041. if (out.length() < buf.length())
  1042. buf = out;
  1043. } catch (IOException err) {
  1044. // Most likely caused by overflowing the buffer, meaning
  1045. // its larger if it were compressed. Don't compress.
  1046. buf = out;
  1047. }
  1048. HttpAuthMethod authenticator = null;
  1049. Collection<Type> ignoreTypes = EnumSet.noneOf(Type.class);
  1050. // Counts number of repeated authentication attempts using the same
  1051. // authentication scheme
  1052. int authAttempts = 1;
  1053. int redirects = 0;
  1054. for (;;) {
  1055. try {
  1056. // The very first time we will try with the authentication
  1057. // method used on the initial GET request. This is a hint
  1058. // only; it may fail. If so, we'll then re-try with proper
  1059. // 401 handling, going through the available authentication
  1060. // schemes.
  1061. openStream();
  1062. if (buf != out) {
  1063. conn.setRequestProperty(HDR_CONTENT_ENCODING,
  1064. ENCODING_GZIP);
  1065. }
  1066. conn.setFixedLengthStreamingMode((int) buf.length());
  1067. try (OutputStream httpOut = conn.getOutputStream()) {
  1068. buf.writeTo(httpOut, null);
  1069. }
  1070. final int status = HttpSupport.response(conn);
  1071. switch (status) {
  1072. case HttpConnection.HTTP_OK:
  1073. // We're done.
  1074. return;
  1075. case HttpConnection.HTTP_NOT_FOUND:
  1076. throw new NoRemoteRepositoryException(uri,
  1077. MessageFormat.format(JGitText.get().uriNotFound,
  1078. conn.getURL()));
  1079. case HttpConnection.HTTP_FORBIDDEN:
  1080. throw new TransportException(uri,
  1081. MessageFormat.format(
  1082. JGitText.get().serviceNotPermitted,
  1083. baseUrl, serviceName));
  1084. case HttpConnection.HTTP_MOVED_PERM:
  1085. case HttpConnection.HTTP_MOVED_TEMP:
  1086. case HttpConnection.HTTP_11_MOVED_TEMP:
  1087. // SEE_OTHER after a POST doesn't make sense for a git
  1088. // server, so we don't handle it here and thus we'll
  1089. // report an error in openResponse() later on.
  1090. if (http.getFollowRedirects() != HttpRedirectMode.TRUE) {
  1091. // Let openResponse() issue an error
  1092. return;
  1093. }
  1094. currentUri = redirect(conn.getHeaderField(HDR_LOCATION),
  1095. '/' + serviceName, redirects++);
  1096. try {
  1097. baseUrl = toURL(currentUri);
  1098. } catch (MalformedURLException e) {
  1099. throw new TransportException(uri,
  1100. MessageFormat.format(
  1101. JGitText.get().invalidRedirectLocation,
  1102. baseUrl, currentUri),
  1103. e);
  1104. }
  1105. continue;
  1106. case HttpConnection.HTTP_UNAUTHORIZED:
  1107. HttpAuthMethod nextMethod = HttpAuthMethod
  1108. .scanResponse(conn, ignoreTypes);
  1109. switch (nextMethod.getType()) {
  1110. case NONE:
  1111. throw new TransportException(uri,
  1112. MessageFormat.format(
  1113. JGitText.get().authenticationNotSupported,
  1114. conn.getURL()));
  1115. case NEGOTIATE:
  1116. // RFC 4559 states "When using the SPNEGO [...] with
  1117. // [...] POST, the authentication should be complete
  1118. // [...] before sending the user data." So in theory
  1119. // the initial GET should have been authenticated
  1120. // already. (Unless there was a redirect?)
  1121. //
  1122. // We try this only once:
  1123. ignoreTypes.add(HttpAuthMethod.Type.NEGOTIATE);
  1124. if (authenticator != null) {
  1125. ignoreTypes.add(authenticator.getType());
  1126. }
  1127. authAttempts = 1;
  1128. // We only do the Kerberos part of SPNEGO, which
  1129. // requires only one round.
  1130. break;
  1131. default:
  1132. // DIGEST or BASIC. Let's be sure we ignore
  1133. // NEGOTIATE; if it was available, we have tried it
  1134. // before.
  1135. ignoreTypes.add(HttpAuthMethod.Type.NEGOTIATE);
  1136. if (authenticator == null || authenticator
  1137. .getType() != nextMethod.getType()) {
  1138. if (authenticator != null) {
  1139. ignoreTypes.add(authenticator.getType());
  1140. }
  1141. authAttempts = 1;
  1142. }
  1143. break;
  1144. }
  1145. authMethod = nextMethod;
  1146. authenticator = nextMethod;
  1147. CredentialsProvider credentialsProvider = getCredentialsProvider();
  1148. if (credentialsProvider == null) {
  1149. throw new TransportException(uri,
  1150. JGitText.get().noCredentialsProvider);
  1151. }
  1152. if (authAttempts > 1) {
  1153. credentialsProvider.reset(currentUri);
  1154. }
  1155. if (3 < authAttempts || !authMethod
  1156. .authorize(currentUri, credentialsProvider)) {
  1157. throw new TransportException(uri,
  1158. JGitText.get().notAuthorized);
  1159. }
  1160. authAttempts++;
  1161. continue;
  1162. default:
  1163. // Just return here; openResponse() will report an
  1164. // appropriate error.
  1165. return;
  1166. }
  1167. } catch (SSLHandshakeException e) {
  1168. handleSslFailure(e);
  1169. continue; // Re-try
  1170. } catch (IOException e) {
  1171. if (authenticator == null || authMethod
  1172. .getType() != HttpAuthMethod.Type.NONE) {
  1173. // Can happen for instance if the server advertises
  1174. // Negotiate, but the client isn't configured for
  1175. // Kerberos. The first time (authenticator == null) we
  1176. // must re-try even if the authMethod was NONE: this may
  1177. // occur if the server advertised NTLM on the GET
  1178. // and the HttpConnection managed to successfully
  1179. // authenticate under the hood with NTLM. We might not
  1180. // have picked this up on the GET's 200 response.
  1181. if (authMethod.getType() != HttpAuthMethod.Type.NONE) {
  1182. ignoreTypes.add(authMethod.getType());
  1183. }
  1184. // Start over with the remaining available methods.
  1185. authMethod = HttpAuthMethod.Type.NONE.method(null);
  1186. authenticator = authMethod;
  1187. authAttempts = 1;
  1188. continue;
  1189. }
  1190. throw e;
  1191. }
  1192. }
  1193. }
  1194. void openResponse() throws IOException {
  1195. final int status = HttpSupport.response(conn);
  1196. if (status != HttpConnection.HTTP_OK) {
  1197. throw new TransportException(uri, status + " " //$NON-NLS-1$
  1198. + conn.getResponseMessage());
  1199. }
  1200. final String contentType = conn.getContentType();
  1201. if (!responseType.equals(contentType)) {
  1202. conn.getInputStream().close();
  1203. throw wrongContentType(responseType, contentType);
  1204. }
  1205. }
  1206. HttpOutputStream getOutputStream() {
  1207. return out;
  1208. }
  1209. InputStream getInputStream() {
  1210. return in;
  1211. }
  1212. abstract void execute() throws IOException;
  1213. class HttpExecuteStream extends InputStream {
  1214. @Override
  1215. public int read() throws IOException {
  1216. execute();
  1217. return -1;
  1218. }
  1219. @Override
  1220. public int read(byte[] b, int off, int len) throws IOException {
  1221. execute();
  1222. return -1;
  1223. }
  1224. @Override
  1225. public long skip(long n) throws IOException {
  1226. execute();
  1227. return 0;
  1228. }
  1229. }
  1230. class HttpOutputStream extends TemporaryBuffer {
  1231. HttpOutputStream() {
  1232. super(http.getPostBuffer());
  1233. }
  1234. @Override
  1235. protected OutputStream overflow() throws IOException {
  1236. openStream();
  1237. conn.setChunkedStreamingMode(0);
  1238. return conn.getOutputStream();
  1239. }
  1240. }
  1241. }
  1242. /**
  1243. * State required to speak multiple HTTP requests with the remote.
  1244. * <p>
  1245. * A service wrapper provides a normal looking InputStream and OutputStream
  1246. * pair which are connected via HTTP to the named remote service. Writing to
  1247. * the OutputStream is buffered until either the buffer overflows, or
  1248. * reading from the InputStream occurs. If overflow occurs HTTP/1.1 and its
  1249. * chunked transfer encoding is used to stream the request data to the
  1250. * remote service. If the entire request fits in the memory buffer, the
  1251. * older HTTP/1.0 standard and a fixed content length is used instead.
  1252. * <p>
  1253. * It is an error to attempt to read without there being outstanding data
  1254. * ready for transmission on the OutputStream.
  1255. * <p>
  1256. * No state is preserved between write-read request pairs. The caller is
  1257. * responsible for replaying state vector information as part of the request
  1258. * data written to the OutputStream. Any session HTTP cookies may or may not
  1259. * be preserved between requests, it is left up to the JVM's implementation
  1260. * of the HTTP client.
  1261. */
  1262. class MultiRequestService extends Service {
  1263. boolean finalRequest;
  1264. MultiRequestService(final String serviceName) {
  1265. super(serviceName);
  1266. }
  1267. /** Keep opening send-receive pairs to the given URI. */
  1268. @Override
  1269. void execute() throws IOException {
  1270. out.close();
  1271. if (conn == null) {
  1272. if (out.length() == 0) {
  1273. // Request output hasn't started yet, but more data is being
  1274. // requested. If there is no request data buffered and the
  1275. // final request was already sent, do nothing to ensure the
  1276. // caller is shown EOF on the InputStream; otherwise an
  1277. // programming error has occurred within this module.
  1278. if (finalRequest)
  1279. return;
  1280. throw new TransportException(uri,
  1281. JGitText.get().startingReadStageWithoutWrittenRequestDataPendingIsNotSupported);
  1282. }
  1283. sendRequest();
  1284. }
  1285. out.reset();
  1286. openResponse();
  1287. in.add(openInputStream(conn));
  1288. if (!finalRequest)
  1289. in.add(execute);
  1290. conn = null;
  1291. }
  1292. }
  1293. /** Service for maintaining a single long-poll connection. */
  1294. class LongPollService extends Service {
  1295. /**
  1296. * @param serviceName
  1297. */
  1298. LongPollService(String serviceName) {
  1299. super(serviceName);
  1300. }
  1301. /** Only open one send-receive request. */
  1302. @Override
  1303. void execute() throws IOException {
  1304. out.close();
  1305. if (conn == null)
  1306. sendRequest();
  1307. openResponse();
  1308. in.add(openInputStream(conn));
  1309. }
  1310. }
  1311. }