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

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