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

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