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

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