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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  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. * @param uri
  256. * @throws NotSupportedException
  257. * @since 4.9
  258. */
  259. protected void setURI(final URIish uri) throws NotSupportedException {
  260. try {
  261. currentUri = uri;
  262. baseUrl = toURL(uri);
  263. objectsUrl = new URL(baseUrl, "objects/"); //$NON-NLS-1$
  264. } catch (MalformedURLException e) {
  265. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  266. }
  267. }
  268. /**
  269. * Create a minimal HTTP transport with default configuration values.
  270. *
  271. * @param uri
  272. * @throws NotSupportedException
  273. */
  274. TransportHttp(final URIish uri) throws NotSupportedException {
  275. super(uri);
  276. setURI(uri);
  277. http = new HttpConfig(uri);
  278. proxySelector = ProxySelector.getDefault();
  279. sslVerify = http.isSslVerify();
  280. }
  281. /**
  282. * Toggle whether or not smart HTTP transport should be used.
  283. * <p>
  284. * This flag exists primarily to support backwards compatibility testing
  285. * within a testing framework, there is no need to modify it in most
  286. * applications.
  287. *
  288. * @param on
  289. * if {@code true} (default), smart HTTP is enabled.
  290. */
  291. public void setUseSmartHttp(final boolean on) {
  292. useSmartHttp = on;
  293. }
  294. @Override
  295. public FetchConnection openFetch() throws TransportException,
  296. NotSupportedException {
  297. final String service = SVC_UPLOAD_PACK;
  298. try {
  299. final HttpConnection c = connect(service);
  300. final InputStream in = openInputStream(c);
  301. try {
  302. BaseConnection f;
  303. if (isSmartHttp(c, service)) {
  304. readSmartHeaders(in, service);
  305. f = new SmartHttpFetchConnection(in);
  306. } else {
  307. // Assume this server doesn't support smart HTTP fetch
  308. // and fall back on dumb object walking.
  309. f = newDumbConnection(in);
  310. }
  311. f.setPeerUserAgent(c.getHeaderField(HttpSupport.HDR_SERVER));
  312. return (FetchConnection) f;
  313. } finally {
  314. in.close();
  315. }
  316. } catch (NotSupportedException err) {
  317. throw err;
  318. } catch (TransportException err) {
  319. throw err;
  320. } catch (IOException err) {
  321. throw new TransportException(uri, JGitText.get().errorReadingInfoRefs, err);
  322. }
  323. }
  324. private WalkFetchConnection newDumbConnection(InputStream in)
  325. throws IOException, PackProtocolException {
  326. HttpObjectDB d = new HttpObjectDB(objectsUrl);
  327. BufferedReader br = toBufferedReader(in);
  328. Map<String, Ref> refs;
  329. try {
  330. refs = d.readAdvertisedImpl(br);
  331. } finally {
  332. br.close();
  333. }
  334. if (!refs.containsKey(HEAD)) {
  335. // If HEAD was not published in the info/refs file (it usually
  336. // is not there) download HEAD by itself as a loose file and do
  337. // the resolution by hand.
  338. //
  339. HttpConnection conn = httpOpen(
  340. METHOD_GET,
  341. new URL(baseUrl, HEAD),
  342. AcceptEncoding.GZIP);
  343. int status = HttpSupport.response(conn);
  344. switch (status) {
  345. case HttpConnection.HTTP_OK: {
  346. br = toBufferedReader(openInputStream(conn));
  347. try {
  348. String line = br.readLine();
  349. if (line != null && line.startsWith(RefDirectory.SYMREF)) {
  350. String target = line.substring(RefDirectory.SYMREF.length());
  351. Ref r = refs.get(target);
  352. if (r == null)
  353. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  354. r = new SymbolicRef(HEAD, r);
  355. refs.put(r.getName(), r);
  356. } else if (line != null && ObjectId.isId(line)) {
  357. Ref r = new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK,
  358. HEAD, ObjectId.fromString(line));
  359. refs.put(r.getName(), r);
  360. }
  361. } finally {
  362. br.close();
  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, Constants.CHARSET));
  380. }
  381. @Override
  382. public PushConnection openPush() throws NotSupportedException,
  383. TransportException {
  384. final String service = SVC_RECEIVE_PACK;
  385. try {
  386. final HttpConnection c = connect(service);
  387. final InputStream in = openInputStream(c);
  388. try {
  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. } finally {
  399. in.close();
  400. }
  401. } catch (NotSupportedException err) {
  402. throw err;
  403. } catch (TransportException err) {
  404. throw err;
  405. } catch (IOException err) {
  406. throw new TransportException(uri, JGitText.get().errorReadingInfoRefs, err);
  407. }
  408. }
  409. private PushConnection smartPush(String service, HttpConnection c,
  410. InputStream in) throws IOException, TransportException {
  411. readSmartHeaders(in, service);
  412. SmartHttpPushConnection p = new SmartHttpPushConnection(in);
  413. p.setPeerUserAgent(c.getHeaderField(HttpSupport.HDR_SERVER));
  414. return p;
  415. }
  416. @Override
  417. public void close() {
  418. // No explicit connections are maintained.
  419. }
  420. /**
  421. * Set additional headers on the HTTP connection
  422. *
  423. * @param headers
  424. * a map of name:values that are to be set as headers on the HTTP
  425. * connection
  426. * @since 3.4
  427. */
  428. public void setAdditionalHeaders(Map<String, String> headers) {
  429. this.headers = headers;
  430. }
  431. private HttpConnection connect(final String service)
  432. throws TransportException, NotSupportedException {
  433. URL u = getServiceURL(service);
  434. int authAttempts = 1;
  435. int redirects = 0;
  436. Collection<Type> ignoreTypes = null;
  437. for (;;) {
  438. try {
  439. final HttpConnection conn = httpOpen(METHOD_GET, u, AcceptEncoding.GZIP);
  440. if (useSmartHttp) {
  441. String exp = "application/x-" + service + "-advertisement"; //$NON-NLS-1$ //$NON-NLS-2$
  442. conn.setRequestProperty(HDR_ACCEPT, exp + ", */*"); //$NON-NLS-1$
  443. } else {
  444. conn.setRequestProperty(HDR_ACCEPT, "*/*"); //$NON-NLS-1$
  445. }
  446. final int status = HttpSupport.response(conn);
  447. switch (status) {
  448. case HttpConnection.HTTP_OK:
  449. // Check if HttpConnection did some authentication in the
  450. // background (e.g Kerberos/SPNEGO).
  451. // That may not work for streaming requests and jgit
  452. // explicit authentication would be required
  453. if (authMethod.getType() == HttpAuthMethod.Type.NONE
  454. && conn.getHeaderField(HDR_WWW_AUTHENTICATE) != null)
  455. authMethod = HttpAuthMethod.scanResponse(conn, ignoreTypes);
  456. return conn;
  457. case HttpConnection.HTTP_NOT_FOUND:
  458. throw new NoRemoteRepositoryException(uri,
  459. MessageFormat.format(JGitText.get().uriNotFound, u));
  460. case HttpConnection.HTTP_UNAUTHORIZED:
  461. authMethod = HttpAuthMethod.scanResponse(conn, ignoreTypes);
  462. if (authMethod.getType() == HttpAuthMethod.Type.NONE)
  463. throw new TransportException(uri, MessageFormat.format(
  464. JGitText.get().authenticationNotSupported, uri));
  465. CredentialsProvider credentialsProvider = getCredentialsProvider();
  466. if (credentialsProvider == null)
  467. throw new TransportException(uri,
  468. JGitText.get().noCredentialsProvider);
  469. if (authAttempts > 1)
  470. credentialsProvider.reset(currentUri);
  471. if (3 < authAttempts
  472. || !authMethod.authorize(currentUri,
  473. credentialsProvider)) {
  474. throw new TransportException(uri,
  475. JGitText.get().notAuthorized);
  476. }
  477. authAttempts++;
  478. continue;
  479. case HttpConnection.HTTP_FORBIDDEN:
  480. throw new TransportException(uri, MessageFormat.format(
  481. JGitText.get().serviceNotPermitted, baseUrl,
  482. service));
  483. case HttpConnection.HTTP_MOVED_PERM:
  484. case HttpConnection.HTTP_MOVED_TEMP:
  485. case HttpConnection.HTTP_SEE_OTHER:
  486. case HttpConnection.HTTP_11_MOVED_TEMP:
  487. // SEE_OTHER should actually never be sent by a git server,
  488. // and in general should occur only on POST requests. But it
  489. // doesn't hurt to accept it here as a redirect.
  490. if (http.getFollowRedirects() == HttpRedirectMode.FALSE) {
  491. throw new TransportException(uri,
  492. MessageFormat.format(
  493. JGitText.get().redirectsOff,
  494. Integer.valueOf(status)));
  495. }
  496. URIish newUri = redirect(conn.getHeaderField(HDR_LOCATION),
  497. Constants.INFO_REFS, redirects++);
  498. setURI(newUri);
  499. u = getServiceURL(service);
  500. authAttempts = 1;
  501. break;
  502. default:
  503. String err = status + " " + conn.getResponseMessage(); //$NON-NLS-1$
  504. throw new TransportException(uri, err);
  505. }
  506. } catch (NotSupportedException e) {
  507. throw e;
  508. } catch (TransportException e) {
  509. throw e;
  510. } catch (SSLHandshakeException e) {
  511. handleSslFailure(e);
  512. continue; // Re-try
  513. } catch (IOException e) {
  514. if (authMethod.getType() != HttpAuthMethod.Type.NONE) {
  515. if (ignoreTypes == null) {
  516. ignoreTypes = new HashSet<>();
  517. }
  518. ignoreTypes.add(authMethod.getType());
  519. // reset auth method & attempts for next authentication type
  520. authMethod = HttpAuthMethod.Type.NONE.method(null);
  521. authAttempts = 1;
  522. continue;
  523. }
  524. throw new TransportException(uri, MessageFormat.format(JGitText.get().cannotOpenService, service), e);
  525. }
  526. }
  527. }
  528. private static class CredentialItems {
  529. CredentialItem.InformationalMessage message;
  530. /** Trust the server for this git operation */
  531. CredentialItem.YesNoType now;
  532. /**
  533. * Trust the server for all git operations from this repository; may be
  534. * {@code null} if the transport was created via
  535. * {@link #TransportHttp(URIish)}.
  536. */
  537. CredentialItem.YesNoType forRepo;
  538. /** Always trust the server from now on. */
  539. CredentialItem.YesNoType always;
  540. public CredentialItem[] items() {
  541. if (forRepo == null) {
  542. return new CredentialItem[] { message, now, always };
  543. } else {
  544. return new CredentialItem[] { message, now, forRepo, always };
  545. }
  546. }
  547. }
  548. private void handleSslFailure(Throwable e) throws TransportException {
  549. if (sslFailure || !trustInsecureSslConnection(e.getCause())) {
  550. throw new TransportException(uri,
  551. MessageFormat.format(
  552. JGitText.get().sslFailureExceptionMessage,
  553. currentUri.setPass(null)),
  554. e);
  555. }
  556. sslFailure = true;
  557. }
  558. private boolean trustInsecureSslConnection(Throwable cause) {
  559. if (cause instanceof CertificateException
  560. || cause instanceof CertPathBuilderException
  561. || cause instanceof CertPathValidatorException) {
  562. // Certificate expired or revoked, PKIX path building not
  563. // possible, self-signed certificate, host does not match ...
  564. CredentialsProvider provider = getCredentialsProvider();
  565. if (provider != null) {
  566. CredentialItems trust = constructSslTrustItems(cause);
  567. CredentialItem[] items = trust.items();
  568. if (provider.supports(items)) {
  569. boolean answered = provider.get(uri, items);
  570. if (answered) {
  571. // Not canceled
  572. boolean trustNow = trust.now.getValue();
  573. boolean trustLocal = trust.forRepo != null
  574. && trust.forRepo.getValue();
  575. boolean trustAlways = trust.always.getValue();
  576. if (trustNow || trustLocal || trustAlways) {
  577. sslVerify = false;
  578. if (trustAlways) {
  579. updateSslVerifyUser(false);
  580. } else if (trustLocal) {
  581. updateSslVerify(local.getConfig(), false);
  582. }
  583. return true;
  584. }
  585. }
  586. }
  587. }
  588. }
  589. return false;
  590. }
  591. private CredentialItems constructSslTrustItems(Throwable cause) {
  592. CredentialItems items = new CredentialItems();
  593. String info = MessageFormat.format(JGitText.get().sslFailureInfo,
  594. currentUri.setPass(null));
  595. String sslMessage = cause.getLocalizedMessage();
  596. if (sslMessage == null) {
  597. sslMessage = cause.toString();
  598. }
  599. sslMessage = MessageFormat.format(JGitText.get().sslFailureCause,
  600. sslMessage);
  601. items.message = new CredentialItem.InformationalMessage(info + '\n'
  602. + sslMessage + '\n'
  603. + JGitText.get().sslFailureTrustExplanation);
  604. items.now = new CredentialItem.YesNoType(JGitText.get().sslTrustNow);
  605. if (local != null) {
  606. items.forRepo = new CredentialItem.YesNoType(
  607. MessageFormat.format(JGitText.get().sslTrustForRepo,
  608. local.getDirectory()));
  609. }
  610. items.always = new CredentialItem.YesNoType(
  611. JGitText.get().sslTrustAlways);
  612. return items;
  613. }
  614. private void updateSslVerify(StoredConfig config, boolean value) {
  615. // Since git uses the original URI for matching, we must also use the
  616. // original URI and cannot use the current URI (which might be different
  617. // after redirects).
  618. String uriPattern = uri.getScheme() + "://" + uri.getHost(); //$NON-NLS-1$
  619. int port = uri.getPort();
  620. if (port > 0) {
  621. uriPattern += ":" + port; //$NON-NLS-1$
  622. }
  623. config.setBoolean(HttpConfig.HTTP, uriPattern,
  624. HttpConfig.SSL_VERIFY_KEY, value);
  625. try {
  626. config.save();
  627. } catch (IOException e) {
  628. LOG.error(JGitText.get().sslVerifyCannotSave, e);
  629. }
  630. }
  631. private void updateSslVerifyUser(boolean value) {
  632. FileBasedConfig userConfig = SystemReader.getInstance()
  633. .openUserConfig(null, FS.DETECTED);
  634. try {
  635. userConfig.load();
  636. updateSslVerify(userConfig, value);
  637. } catch (IOException | ConfigInvalidException e) {
  638. // Log it, but otherwise ignore here.
  639. LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid,
  640. userConfig.getFile().getAbsolutePath(), e));
  641. }
  642. }
  643. private URIish redirect(String location, String checkFor, int redirects)
  644. throws TransportException {
  645. if (location == null || location.isEmpty()) {
  646. throw new TransportException(uri,
  647. MessageFormat.format(JGitText.get().redirectLocationMissing,
  648. baseUrl));
  649. }
  650. if (redirects >= http.getMaxRedirects()) {
  651. throw new TransportException(uri,
  652. MessageFormat.format(JGitText.get().redirectLimitExceeded,
  653. Integer.valueOf(http.getMaxRedirects()), baseUrl,
  654. location));
  655. }
  656. try {
  657. if (!isValidRedirect(baseUrl, location, checkFor)) {
  658. throw new TransportException(uri,
  659. MessageFormat.format(JGitText.get().redirectBlocked,
  660. baseUrl, location));
  661. }
  662. location = location.substring(0, location.indexOf(checkFor));
  663. URIish result = new URIish(location);
  664. if (LOG.isInfoEnabled()) {
  665. LOG.info(MessageFormat.format(JGitText.get().redirectHttp,
  666. uri.setPass(null),
  667. Integer.valueOf(redirects), baseUrl, result));
  668. }
  669. return result;
  670. } catch (URISyntaxException e) {
  671. throw new TransportException(uri,
  672. MessageFormat.format(JGitText.get().invalidRedirectLocation,
  673. baseUrl, location),
  674. e);
  675. }
  676. }
  677. private boolean isValidRedirect(URL current, String next, String checkFor) {
  678. // Protocols must be the same, or current is "http" and next "https". We
  679. // do not follow redirects from https back to http.
  680. String oldProtocol = current.getProtocol().toLowerCase(Locale.ROOT);
  681. int schemeEnd = next.indexOf("://"); //$NON-NLS-1$
  682. if (schemeEnd < 0) {
  683. return false;
  684. }
  685. String newProtocol = next.substring(0, schemeEnd)
  686. .toLowerCase(Locale.ROOT);
  687. if (!oldProtocol.equals(newProtocol)) {
  688. if (!"https".equals(newProtocol)) { //$NON-NLS-1$
  689. return false;
  690. }
  691. }
  692. // git allows only rewriting the root, i.e., everything before INFO_REFS
  693. // or the service name
  694. if (next.indexOf(checkFor) < 0) {
  695. return false;
  696. }
  697. // Basically we should test here that whatever follows INFO_REFS is
  698. // unchanged. But since we re-construct the query part
  699. // anyway, it doesn't matter.
  700. return true;
  701. }
  702. private URL getServiceURL(final String service)
  703. throws NotSupportedException {
  704. try {
  705. final StringBuilder b = new StringBuilder();
  706. b.append(baseUrl);
  707. if (b.charAt(b.length() - 1) != '/') {
  708. b.append('/');
  709. }
  710. b.append(Constants.INFO_REFS);
  711. if (useSmartHttp) {
  712. b.append(b.indexOf("?") < 0 ? '?' : '&'); //$NON-NLS-1$
  713. b.append("service="); //$NON-NLS-1$
  714. b.append(service);
  715. }
  716. return new URL(b.toString());
  717. } catch (MalformedURLException e) {
  718. throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
  719. }
  720. }
  721. /**
  722. * Open an HTTP connection, setting the accept-encoding request header to gzip.
  723. *
  724. * @param method HTTP request method
  725. * @param u url of the HTTP connection
  726. * @return the HTTP connection
  727. * @throws IOException
  728. * @since 3.3
  729. * @deprecated use {@link #httpOpen(String, URL, AcceptEncoding)} instead.
  730. */
  731. @Deprecated
  732. protected HttpConnection httpOpen(String method, URL u) throws IOException {
  733. return httpOpen(method, u, AcceptEncoding.GZIP);
  734. }
  735. /**
  736. * Open an HTTP connection.
  737. *
  738. * @param method HTTP request method
  739. * @param u url of the HTTP connection
  740. * @param acceptEncoding accept-encoding header option
  741. * @return the HTTP connection
  742. * @throws IOException
  743. * @since 4.6
  744. */
  745. protected HttpConnection httpOpen(String method, URL u,
  746. AcceptEncoding acceptEncoding) throws IOException {
  747. if (method == null || u == null || acceptEncoding == null) {
  748. throw new NullPointerException();
  749. }
  750. final Proxy proxy = HttpSupport.proxyFor(proxySelector, u);
  751. HttpConnection conn = connectionFactory.create(u, proxy);
  752. if (!sslVerify && "https".equals(u.getProtocol())) { //$NON-NLS-1$
  753. HttpSupport.disableSslVerify(conn);
  754. }
  755. // We must do our own redirect handling to implement git rules and to
  756. // handle http->https redirects
  757. conn.setInstanceFollowRedirects(false);
  758. conn.setRequestMethod(method);
  759. conn.setUseCaches(false);
  760. if (acceptEncoding == AcceptEncoding.GZIP) {
  761. conn.setRequestProperty(HDR_ACCEPT_ENCODING, ENCODING_GZIP);
  762. }
  763. conn.setRequestProperty(HDR_PRAGMA, "no-cache"); //$NON-NLS-1$
  764. if (UserAgent.get() != null) {
  765. conn.setRequestProperty(HDR_USER_AGENT, UserAgent.get());
  766. }
  767. int timeOut = getTimeout();
  768. if (timeOut != -1) {
  769. int effTimeOut = timeOut * 1000;
  770. conn.setConnectTimeout(effTimeOut);
  771. conn.setReadTimeout(effTimeOut);
  772. }
  773. if (this.headers != null && !this.headers.isEmpty()) {
  774. for (Map.Entry<String, String> entry : this.headers.entrySet())
  775. conn.setRequestProperty(entry.getKey(), entry.getValue());
  776. }
  777. authMethod.configureRequest(conn);
  778. return conn;
  779. }
  780. final InputStream openInputStream(HttpConnection conn)
  781. throws IOException {
  782. InputStream input = conn.getInputStream();
  783. if (isGzipContent(conn))
  784. input = new GZIPInputStream(input);
  785. return input;
  786. }
  787. IOException wrongContentType(String expType, String actType) {
  788. final String why = MessageFormat.format(JGitText.get().expectedReceivedContentType, expType, actType);
  789. return new TransportException(uri, why);
  790. }
  791. private boolean isSmartHttp(final HttpConnection c, final String service) {
  792. final String expType = "application/x-" + service + "-advertisement"; //$NON-NLS-1$ //$NON-NLS-2$
  793. final String actType = c.getContentType();
  794. return expType.equals(actType);
  795. }
  796. private boolean isGzipContent(final HttpConnection c) {
  797. return ENCODING_GZIP.equals(c.getHeaderField(HDR_CONTENT_ENCODING))
  798. || ENCODING_X_GZIP.equals(c.getHeaderField(HDR_CONTENT_ENCODING));
  799. }
  800. private void readSmartHeaders(final InputStream in, final String service)
  801. throws IOException {
  802. // A smart reply will have a '#' after the first 4 bytes, but
  803. // a dumb reply cannot contain a '#' until after byte 41. Do a
  804. // quick check to make sure its a smart reply before we parse
  805. // as a pkt-line stream.
  806. //
  807. final byte[] magic = new byte[5];
  808. IO.readFully(in, magic, 0, magic.length);
  809. if (magic[4] != '#') {
  810. throw new TransportException(uri, MessageFormat.format(
  811. JGitText.get().expectedPktLineWithService, RawParseUtils.decode(magic)));
  812. }
  813. final PacketLineIn pckIn = new PacketLineIn(new UnionInputStream(
  814. new ByteArrayInputStream(magic), in));
  815. final String exp = "# service=" + service; //$NON-NLS-1$
  816. final String act = pckIn.readString();
  817. if (!exp.equals(act)) {
  818. throw new TransportException(uri, MessageFormat.format(
  819. JGitText.get().expectedGot, exp, act));
  820. }
  821. while (pckIn.readString() != PacketLineIn.END) {
  822. // for now, ignore the remaining header lines
  823. }
  824. }
  825. class HttpObjectDB extends WalkRemoteObjectDatabase {
  826. private final URL httpObjectsUrl;
  827. HttpObjectDB(final URL b) {
  828. httpObjectsUrl = b;
  829. }
  830. @Override
  831. URIish getURI() {
  832. return new URIish(httpObjectsUrl);
  833. }
  834. @Override
  835. Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
  836. try {
  837. return readAlternates(INFO_HTTP_ALTERNATES);
  838. } catch (FileNotFoundException err) {
  839. // Fall through.
  840. }
  841. try {
  842. return readAlternates(INFO_ALTERNATES);
  843. } catch (FileNotFoundException err) {
  844. // Fall through.
  845. }
  846. return null;
  847. }
  848. @Override
  849. WalkRemoteObjectDatabase openAlternate(final String location)
  850. throws IOException {
  851. return new HttpObjectDB(new URL(httpObjectsUrl, location));
  852. }
  853. @Override
  854. BufferedReader openReader(String path) throws IOException {
  855. // Line oriented readable content is likely to compress well.
  856. // Request gzip encoding.
  857. InputStream is = open(path, AcceptEncoding.GZIP).in;
  858. return new BufferedReader(new InputStreamReader(is, Constants.CHARSET));
  859. }
  860. @Override
  861. Collection<String> getPackNames() throws IOException {
  862. final Collection<String> packs = new ArrayList<>();
  863. try {
  864. final BufferedReader br = openReader(INFO_PACKS);
  865. try {
  866. for (;;) {
  867. final String s = br.readLine();
  868. if (s == null || s.length() == 0)
  869. break;
  870. if (!s.startsWith("P pack-") || !s.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  871. throw invalidAdvertisement(s);
  872. packs.add(s.substring(2));
  873. }
  874. return packs;
  875. } finally {
  876. br.close();
  877. }
  878. } catch (FileNotFoundException err) {
  879. return packs;
  880. }
  881. }
  882. @Override
  883. FileStream open(final String path) throws IOException {
  884. return open(path, AcceptEncoding.UNSPECIFIED);
  885. }
  886. FileStream open(String path, AcceptEncoding acceptEncoding)
  887. throws IOException {
  888. final URL base = httpObjectsUrl;
  889. final URL u = new URL(base, path);
  890. final HttpConnection c = httpOpen(METHOD_GET, u, acceptEncoding);
  891. switch (HttpSupport.response(c)) {
  892. case HttpConnection.HTTP_OK:
  893. final InputStream in = openInputStream(c);
  894. // If content is being gzipped and then transferred, the content
  895. // length in the header is the zipped content length, not the
  896. // actual content length.
  897. if (!isGzipContent(c)) {
  898. final int len = c.getContentLength();
  899. return new FileStream(in, len);
  900. }
  901. return new FileStream(in);
  902. case HttpConnection.HTTP_NOT_FOUND:
  903. throw new FileNotFoundException(u.toString());
  904. default:
  905. throw new IOException(u.toString() + ": " //$NON-NLS-1$
  906. + HttpSupport.response(c) + " " //$NON-NLS-1$
  907. + c.getResponseMessage());
  908. }
  909. }
  910. Map<String, Ref> readAdvertisedImpl(final BufferedReader br)
  911. throws IOException, PackProtocolException {
  912. final TreeMap<String, Ref> avail = new TreeMap<>();
  913. for (;;) {
  914. String line = br.readLine();
  915. if (line == null)
  916. break;
  917. final int tab = line.indexOf('\t');
  918. if (tab < 0)
  919. throw invalidAdvertisement(line);
  920. String name;
  921. final ObjectId id;
  922. name = line.substring(tab + 1);
  923. id = ObjectId.fromString(line.substring(0, tab));
  924. if (name.endsWith("^{}")) { //$NON-NLS-1$
  925. name = name.substring(0, name.length() - 3);
  926. final Ref prior = avail.get(name);
  927. if (prior == null)
  928. throw outOfOrderAdvertisement(name);
  929. if (prior.getPeeledObjectId() != null)
  930. throw duplicateAdvertisement(name + "^{}"); //$NON-NLS-1$
  931. avail.put(name, new ObjectIdRef.PeeledTag(
  932. Ref.Storage.NETWORK, name,
  933. prior.getObjectId(), id));
  934. } else {
  935. Ref prior = avail.put(name, new ObjectIdRef.PeeledNonTag(
  936. Ref.Storage.NETWORK, name, id));
  937. if (prior != null)
  938. throw duplicateAdvertisement(name);
  939. }
  940. }
  941. return avail;
  942. }
  943. private PackProtocolException outOfOrderAdvertisement(final String n) {
  944. return new PackProtocolException(MessageFormat.format(JGitText.get().advertisementOfCameBefore, n, n));
  945. }
  946. private PackProtocolException invalidAdvertisement(final String n) {
  947. return new PackProtocolException(MessageFormat.format(JGitText.get().invalidAdvertisementOf, n));
  948. }
  949. private PackProtocolException duplicateAdvertisement(final String n) {
  950. return new PackProtocolException(MessageFormat.format(JGitText.get().duplicateAdvertisementsOf, n));
  951. }
  952. @Override
  953. void close() {
  954. // We do not maintain persistent connections.
  955. }
  956. }
  957. class SmartHttpFetchConnection extends BasePackFetchConnection {
  958. private MultiRequestService svc;
  959. SmartHttpFetchConnection(final InputStream advertisement)
  960. throws TransportException {
  961. super(TransportHttp.this);
  962. statelessRPC = true;
  963. init(advertisement, DisabledOutputStream.INSTANCE);
  964. outNeedsEnd = false;
  965. readAdvertisedRefs();
  966. }
  967. @Override
  968. protected void doFetch(final ProgressMonitor monitor,
  969. final Collection<Ref> want, final Set<ObjectId> have,
  970. final OutputStream outputStream) throws TransportException {
  971. try {
  972. svc = new MultiRequestService(SVC_UPLOAD_PACK);
  973. init(svc.getInputStream(), svc.getOutputStream());
  974. super.doFetch(monitor, want, have, outputStream);
  975. } finally {
  976. svc = null;
  977. }
  978. }
  979. @Override
  980. protected void onReceivePack() {
  981. svc.finalRequest = true;
  982. }
  983. }
  984. class SmartHttpPushConnection extends BasePackPushConnection {
  985. SmartHttpPushConnection(final InputStream advertisement)
  986. throws TransportException {
  987. super(TransportHttp.this);
  988. statelessRPC = true;
  989. init(advertisement, DisabledOutputStream.INSTANCE);
  990. outNeedsEnd = false;
  991. readAdvertisedRefs();
  992. }
  993. @Override
  994. protected void doPush(final ProgressMonitor monitor,
  995. final Map<String, RemoteRefUpdate> refUpdates,
  996. OutputStream outputStream) throws TransportException {
  997. final Service svc = new MultiRequestService(SVC_RECEIVE_PACK);
  998. init(svc.getInputStream(), svc.getOutputStream());
  999. super.doPush(monitor, refUpdates, outputStream);
  1000. }
  1001. }
  1002. /** Basic service for sending and receiving HTTP requests. */
  1003. abstract class Service {
  1004. protected final String serviceName;
  1005. protected final String requestType;
  1006. protected final String responseType;
  1007. protected HttpConnection conn;
  1008. protected HttpOutputStream out;
  1009. protected final HttpExecuteStream execute;
  1010. final UnionInputStream in;
  1011. Service(String serviceName) {
  1012. this.serviceName = serviceName;
  1013. this.requestType = "application/x-" + serviceName + "-request"; //$NON-NLS-1$ //$NON-NLS-2$
  1014. this.responseType = "application/x-" + serviceName + "-result"; //$NON-NLS-1$ //$NON-NLS-2$
  1015. this.out = new HttpOutputStream();
  1016. this.execute = new HttpExecuteStream();
  1017. this.in = new UnionInputStream(execute);
  1018. }
  1019. void openStream() throws IOException {
  1020. conn = httpOpen(METHOD_POST, new URL(baseUrl, serviceName),
  1021. AcceptEncoding.GZIP);
  1022. conn.setInstanceFollowRedirects(false);
  1023. conn.setDoOutput(true);
  1024. conn.setRequestProperty(HDR_CONTENT_TYPE, requestType);
  1025. conn.setRequestProperty(HDR_ACCEPT, responseType);
  1026. }
  1027. void sendRequest() throws IOException {
  1028. // Try to compress the content, but only if that is smaller.
  1029. TemporaryBuffer buf = new TemporaryBuffer.Heap(
  1030. http.getPostBuffer());
  1031. try {
  1032. GZIPOutputStream gzip = new GZIPOutputStream(buf);
  1033. out.writeTo(gzip, null);
  1034. gzip.close();
  1035. if (out.length() < buf.length())
  1036. buf = out;
  1037. } catch (IOException err) {
  1038. // Most likely caused by overflowing the buffer, meaning
  1039. // its larger if it were compressed. Don't compress.
  1040. buf = out;
  1041. }
  1042. HttpAuthMethod authenticator = null;
  1043. Collection<Type> ignoreTypes = EnumSet.noneOf(Type.class);
  1044. // Counts number of repeated authentication attempts using the same
  1045. // authentication scheme
  1046. int authAttempts = 1;
  1047. int redirects = 0;
  1048. for (;;) {
  1049. try {
  1050. // The very first time we will try with the authentication
  1051. // method used on the initial GET request. This is a hint
  1052. // only; it may fail. If so, we'll then re-try with proper
  1053. // 401 handling, going through the available authentication
  1054. // schemes.
  1055. openStream();
  1056. if (buf != out) {
  1057. conn.setRequestProperty(HDR_CONTENT_ENCODING,
  1058. ENCODING_GZIP);
  1059. }
  1060. conn.setFixedLengthStreamingMode((int) buf.length());
  1061. try (OutputStream httpOut = conn.getOutputStream()) {
  1062. buf.writeTo(httpOut, null);
  1063. }
  1064. final int status = HttpSupport.response(conn);
  1065. switch (status) {
  1066. case HttpConnection.HTTP_OK:
  1067. // We're done.
  1068. return;
  1069. case HttpConnection.HTTP_NOT_FOUND:
  1070. throw new NoRemoteRepositoryException(uri,
  1071. MessageFormat.format(JGitText.get().uriNotFound,
  1072. conn.getURL()));
  1073. case HttpConnection.HTTP_FORBIDDEN:
  1074. throw new TransportException(uri,
  1075. MessageFormat.format(
  1076. JGitText.get().serviceNotPermitted,
  1077. baseUrl, serviceName));
  1078. case HttpConnection.HTTP_MOVED_PERM:
  1079. case HttpConnection.HTTP_MOVED_TEMP:
  1080. case HttpConnection.HTTP_11_MOVED_TEMP:
  1081. // SEE_OTHER after a POST doesn't make sense for a git
  1082. // server, so we don't handle it here and thus we'll
  1083. // report an error in openResponse() later on.
  1084. if (http.getFollowRedirects() != HttpRedirectMode.TRUE) {
  1085. // Let openResponse() issue an error
  1086. return;
  1087. }
  1088. currentUri = redirect(conn.getHeaderField(HDR_LOCATION),
  1089. '/' + serviceName, redirects++);
  1090. try {
  1091. baseUrl = toURL(currentUri);
  1092. } catch (MalformedURLException e) {
  1093. throw new TransportException(uri,
  1094. MessageFormat.format(
  1095. JGitText.get().invalidRedirectLocation,
  1096. baseUrl, currentUri),
  1097. e);
  1098. }
  1099. continue;
  1100. case HttpConnection.HTTP_UNAUTHORIZED:
  1101. HttpAuthMethod nextMethod = HttpAuthMethod
  1102. .scanResponse(conn, ignoreTypes);
  1103. switch (nextMethod.getType()) {
  1104. case NONE:
  1105. throw new TransportException(uri,
  1106. MessageFormat.format(
  1107. JGitText.get().authenticationNotSupported,
  1108. conn.getURL()));
  1109. case NEGOTIATE:
  1110. // RFC 4559 states "When using the SPNEGO [...] with
  1111. // [...] POST, the authentication should be complete
  1112. // [...] before sending the user data." So in theory
  1113. // the initial GET should have been authenticated
  1114. // already. (Unless there was a redirect?)
  1115. //
  1116. // We try this only once:
  1117. ignoreTypes.add(HttpAuthMethod.Type.NEGOTIATE);
  1118. if (authenticator != null) {
  1119. ignoreTypes.add(authenticator.getType());
  1120. }
  1121. authAttempts = 1;
  1122. // We only do the Kerberos part of SPNEGO, which
  1123. // requires only one round.
  1124. break;
  1125. default:
  1126. // DIGEST or BASIC. Let's be sure we ignore
  1127. // NEGOTIATE; if it was available, we have tried it
  1128. // before.
  1129. ignoreTypes.add(HttpAuthMethod.Type.NEGOTIATE);
  1130. if (authenticator == null || authenticator
  1131. .getType() != nextMethod.getType()) {
  1132. if (authenticator != null) {
  1133. ignoreTypes.add(authenticator.getType());
  1134. }
  1135. authAttempts = 1;
  1136. }
  1137. break;
  1138. }
  1139. authMethod = nextMethod;
  1140. authenticator = nextMethod;
  1141. CredentialsProvider credentialsProvider = getCredentialsProvider();
  1142. if (credentialsProvider == null) {
  1143. throw new TransportException(uri,
  1144. JGitText.get().noCredentialsProvider);
  1145. }
  1146. if (authAttempts > 1) {
  1147. credentialsProvider.reset(currentUri);
  1148. }
  1149. if (3 < authAttempts || !authMethod
  1150. .authorize(currentUri, credentialsProvider)) {
  1151. throw new TransportException(uri,
  1152. JGitText.get().notAuthorized);
  1153. }
  1154. authAttempts++;
  1155. continue;
  1156. default:
  1157. // Just return here; openResponse() will report an
  1158. // appropriate error.
  1159. return;
  1160. }
  1161. } catch (SSLHandshakeException e) {
  1162. handleSslFailure(e);
  1163. continue; // Re-try
  1164. } catch (IOException e) {
  1165. if (authenticator == null || authMethod
  1166. .getType() != HttpAuthMethod.Type.NONE) {
  1167. // Can happen for instance if the server advertises
  1168. // Negotiate, but the client isn't configured for
  1169. // Kerberos. The first time (authenticator == null) we
  1170. // must re-try even if the authMethod was NONE: this may
  1171. // occur if the server advertised NTLM on the GET
  1172. // and the HttpConnection managed to successfully
  1173. // authenticate under the hood with NTLM. We might not
  1174. // have picked this up on the GET's 200 response.
  1175. if (authMethod.getType() != HttpAuthMethod.Type.NONE) {
  1176. ignoreTypes.add(authMethod.getType());
  1177. }
  1178. // Start over with the remaining available methods.
  1179. authMethod = HttpAuthMethod.Type.NONE.method(null);
  1180. authenticator = authMethod;
  1181. authAttempts = 1;
  1182. continue;
  1183. }
  1184. throw e;
  1185. }
  1186. }
  1187. }
  1188. void openResponse() throws IOException {
  1189. final int status = HttpSupport.response(conn);
  1190. if (status != HttpConnection.HTTP_OK) {
  1191. throw new TransportException(uri, status + " " //$NON-NLS-1$
  1192. + conn.getResponseMessage());
  1193. }
  1194. final String contentType = conn.getContentType();
  1195. if (!responseType.equals(contentType)) {
  1196. conn.getInputStream().close();
  1197. throw wrongContentType(responseType, contentType);
  1198. }
  1199. }
  1200. HttpOutputStream getOutputStream() {
  1201. return out;
  1202. }
  1203. InputStream getInputStream() {
  1204. return in;
  1205. }
  1206. abstract void execute() throws IOException;
  1207. class HttpExecuteStream extends InputStream {
  1208. @Override
  1209. public int read() throws IOException {
  1210. execute();
  1211. return -1;
  1212. }
  1213. @Override
  1214. public int read(byte[] b, int off, int len) throws IOException {
  1215. execute();
  1216. return -1;
  1217. }
  1218. @Override
  1219. public long skip(long n) throws IOException {
  1220. execute();
  1221. return 0;
  1222. }
  1223. }
  1224. class HttpOutputStream extends TemporaryBuffer {
  1225. HttpOutputStream() {
  1226. super(http.getPostBuffer());
  1227. }
  1228. @Override
  1229. protected OutputStream overflow() throws IOException {
  1230. openStream();
  1231. conn.setChunkedStreamingMode(0);
  1232. return conn.getOutputStream();
  1233. }
  1234. }
  1235. }
  1236. /**
  1237. * State required to speak multiple HTTP requests with the remote.
  1238. * <p>
  1239. * A service wrapper provides a normal looking InputStream and OutputStream
  1240. * pair which are connected via HTTP to the named remote service. Writing to
  1241. * the OutputStream is buffered until either the buffer overflows, or
  1242. * reading from the InputStream occurs. If overflow occurs HTTP/1.1 and its
  1243. * chunked transfer encoding is used to stream the request data to the
  1244. * remote service. If the entire request fits in the memory buffer, the
  1245. * older HTTP/1.0 standard and a fixed content length is used instead.
  1246. * <p>
  1247. * It is an error to attempt to read without there being outstanding data
  1248. * ready for transmission on the OutputStream.
  1249. * <p>
  1250. * No state is preserved between write-read request pairs. The caller is
  1251. * responsible for replaying state vector information as part of the request
  1252. * data written to the OutputStream. Any session HTTP cookies may or may not
  1253. * be preserved between requests, it is left up to the JVM's implementation
  1254. * of the HTTP client.
  1255. */
  1256. class MultiRequestService extends Service {
  1257. boolean finalRequest;
  1258. MultiRequestService(final String serviceName) {
  1259. super(serviceName);
  1260. }
  1261. /** Keep opening send-receive pairs to the given URI. */
  1262. @Override
  1263. void execute() throws IOException {
  1264. out.close();
  1265. if (conn == null) {
  1266. if (out.length() == 0) {
  1267. // Request output hasn't started yet, but more data is being
  1268. // requested. If there is no request data buffered and the
  1269. // final request was already sent, do nothing to ensure the
  1270. // caller is shown EOF on the InputStream; otherwise an
  1271. // programming error has occurred within this module.
  1272. if (finalRequest)
  1273. return;
  1274. throw new TransportException(uri,
  1275. JGitText.get().startingReadStageWithoutWrittenRequestDataPendingIsNotSupported);
  1276. }
  1277. sendRequest();
  1278. }
  1279. out.reset();
  1280. openResponse();
  1281. in.add(openInputStream(conn));
  1282. if (!finalRequest)
  1283. in.add(execute);
  1284. conn = null;
  1285. }
  1286. }
  1287. /** Service for maintaining a single long-poll connection. */
  1288. class LongPollService extends Service {
  1289. /**
  1290. * @param serviceName
  1291. */
  1292. LongPollService(String serviceName) {
  1293. super(serviceName);
  1294. }
  1295. /** Only open one send-receive request. */
  1296. @Override
  1297. void execute() throws IOException {
  1298. out.close();
  1299. if (conn == null)
  1300. sendRequest();
  1301. openResponse();
  1302. in.add(openInputStream(conn));
  1303. }
  1304. }
  1305. }