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

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