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.

HttpConfig.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /*
  2. * Copyright (C) 2008, 2010, Google Inc.
  3. * Copyright (C) 2017, Thomas Wolf <thomas.wolf@paranor.ch>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.transport;
  45. import java.io.IOException;
  46. import java.net.URISyntaxException;
  47. import java.text.MessageFormat;
  48. import java.util.Set;
  49. import java.util.function.Supplier;
  50. import org.eclipse.jgit.errors.ConfigInvalidException;
  51. import org.eclipse.jgit.internal.JGitText;
  52. import org.eclipse.jgit.lib.Config;
  53. import org.eclipse.jgit.lib.StoredConfig;
  54. import org.eclipse.jgit.util.StringUtils;
  55. import org.eclipse.jgit.util.SystemReader;
  56. import org.slf4j.Logger;
  57. import org.slf4j.LoggerFactory;
  58. /**
  59. * A representation of the "http.*" config values in a git
  60. * {@link org.eclipse.jgit.lib.Config}. git provides for setting values for
  61. * specific URLs through "http.&lt;url&gt;.*" subsections. git always considers
  62. * only the initial original URL for such settings, not any redirected URL.
  63. *
  64. * @since 4.9
  65. */
  66. public class HttpConfig {
  67. private static final Logger LOG = LoggerFactory.getLogger(HttpConfig.class);
  68. private static final String FTP = "ftp"; //$NON-NLS-1$
  69. /** git config section key for http settings. */
  70. public static final String HTTP = "http"; //$NON-NLS-1$
  71. /** git config key for the "followRedirects" setting. */
  72. public static final String FOLLOW_REDIRECTS_KEY = "followRedirects"; //$NON-NLS-1$
  73. /** git config key for the "maxRedirects" setting. */
  74. public static final String MAX_REDIRECTS_KEY = "maxRedirects"; //$NON-NLS-1$
  75. /** git config key for the "postBuffer" setting. */
  76. public static final String POST_BUFFER_KEY = "postBuffer"; //$NON-NLS-1$
  77. /** git config key for the "sslVerify" setting. */
  78. public static final String SSL_VERIFY_KEY = "sslVerify"; //$NON-NLS-1$
  79. /**
  80. * git config key for the "cookieFile" setting.
  81. *
  82. * @since 5.4
  83. */
  84. public static final String COOKIE_FILE_KEY = "cookieFile"; //$NON-NLS-1$
  85. /**
  86. * git config key for the "saveCookies" setting.
  87. *
  88. * @since 5.4
  89. */
  90. public static final String SAVE_COOKIES_KEY = "saveCookies"; //$NON-NLS-1$
  91. /**
  92. * Custom JGit config key which holds the maximum number of cookie files to
  93. * keep in the cache.
  94. *
  95. * @since 5.4
  96. */
  97. public static final String COOKIE_FILE_CACHE_LIMIT_KEY = "cookieFileCacheLimit"; //$NON-NLS-1$
  98. private static final int DEFAULT_COOKIE_FILE_CACHE_LIMIT = 10;
  99. private static final String MAX_REDIRECT_SYSTEM_PROPERTY = "http.maxRedirects"; //$NON-NLS-1$
  100. private static final int DEFAULT_MAX_REDIRECTS = 5;
  101. private static final int MAX_REDIRECTS = (new Supplier<Integer>() {
  102. @Override
  103. public Integer get() {
  104. String rawValue = SystemReader.getInstance()
  105. .getProperty(MAX_REDIRECT_SYSTEM_PROPERTY);
  106. Integer value = Integer.valueOf(DEFAULT_MAX_REDIRECTS);
  107. if (rawValue != null) {
  108. try {
  109. value = Integer.valueOf(Integer.parseUnsignedInt(rawValue));
  110. } catch (NumberFormatException e) {
  111. LOG.warn(MessageFormat.format(
  112. JGitText.get().invalidSystemProperty,
  113. MAX_REDIRECT_SYSTEM_PROPERTY, rawValue, value));
  114. }
  115. }
  116. return value;
  117. }
  118. }).get().intValue();
  119. /**
  120. * Config values for http.followRedirect.
  121. */
  122. public enum HttpRedirectMode implements Config.ConfigEnum {
  123. /** Always follow redirects (up to the http.maxRedirects limit). */
  124. TRUE("true"), //$NON-NLS-1$
  125. /**
  126. * Only follow redirects on the initial GET request. This is the
  127. * default.
  128. */
  129. INITIAL("initial"), //$NON-NLS-1$
  130. /** Never follow redirects. */
  131. FALSE("false"); //$NON-NLS-1$
  132. private final String configValue;
  133. private HttpRedirectMode(String configValue) {
  134. this.configValue = configValue;
  135. }
  136. @Override
  137. public String toConfigValue() {
  138. return configValue;
  139. }
  140. @Override
  141. public boolean matchConfigValue(String s) {
  142. return configValue.equals(s);
  143. }
  144. }
  145. private int postBuffer;
  146. private boolean sslVerify;
  147. private HttpRedirectMode followRedirects;
  148. private int maxRedirects;
  149. private String cookieFile;
  150. private boolean saveCookies;
  151. private int cookieFileCacheLimit;
  152. /**
  153. * Get the "http.postBuffer" setting
  154. *
  155. * @return the value of the "http.postBuffer" setting
  156. */
  157. public int getPostBuffer() {
  158. return postBuffer;
  159. }
  160. /**
  161. * Get the "http.sslVerify" setting
  162. *
  163. * @return the value of the "http.sslVerify" setting
  164. */
  165. public boolean isSslVerify() {
  166. return sslVerify;
  167. }
  168. /**
  169. * Get the "http.followRedirects" setting
  170. *
  171. * @return the value of the "http.followRedirects" setting
  172. */
  173. public HttpRedirectMode getFollowRedirects() {
  174. return followRedirects;
  175. }
  176. /**
  177. * Get the "http.maxRedirects" setting
  178. *
  179. * @return the value of the "http.maxRedirects" setting
  180. */
  181. public int getMaxRedirects() {
  182. return maxRedirects;
  183. }
  184. /**
  185. * Get the "http.cookieFile" setting
  186. *
  187. * @return the value of the "http.cookieFile" setting
  188. *
  189. * @since 5.4
  190. */
  191. public String getCookieFile() {
  192. return cookieFile;
  193. }
  194. /**
  195. * Get the "http.saveCookies" setting
  196. *
  197. * @return the value of the "http.saveCookies" setting
  198. *
  199. * @since 5.4
  200. */
  201. public boolean getSaveCookies() {
  202. return saveCookies;
  203. }
  204. /**
  205. * Get the "http.cookieFileCacheLimit" setting (gives the maximum number of
  206. * cookie files to keep in the LRU cache)
  207. *
  208. * @return the value of the "http.cookieFileCacheLimit" setting
  209. *
  210. * @since 5.4
  211. */
  212. public int getCookieFileCacheLimit() {
  213. return cookieFileCacheLimit;
  214. }
  215. /**
  216. * Creates a new {@link org.eclipse.jgit.transport.HttpConfig} tailored to
  217. * the given {@link org.eclipse.jgit.transport.URIish}.
  218. *
  219. * @param config
  220. * to read the {@link org.eclipse.jgit.transport.HttpConfig} from
  221. * @param uri
  222. * to get the configuration values for
  223. */
  224. public HttpConfig(Config config, URIish uri) {
  225. init(config, uri);
  226. }
  227. /**
  228. * Creates a {@link org.eclipse.jgit.transport.HttpConfig} that reads values
  229. * solely from the user config.
  230. *
  231. * @param uri
  232. * to get the configuration values for
  233. */
  234. public HttpConfig(URIish uri) {
  235. StoredConfig userConfig = null;
  236. try {
  237. userConfig = SystemReader.getInstance().getUserConfig();
  238. } catch (IOException | ConfigInvalidException e) {
  239. // Log it and then work with default values.
  240. LOG.error(e.getMessage(), e);
  241. init(new Config(), uri);
  242. return;
  243. }
  244. init(userConfig, uri);
  245. }
  246. private void init(Config config, URIish uri) {
  247. // Set defaults from the section first
  248. int postBufferSize = config.getInt(HTTP, POST_BUFFER_KEY,
  249. 1 * 1024 * 1024);
  250. boolean sslVerifyFlag = config.getBoolean(HTTP, SSL_VERIFY_KEY, true);
  251. HttpRedirectMode followRedirectsMode = config.getEnum(
  252. HttpRedirectMode.values(), HTTP, null,
  253. FOLLOW_REDIRECTS_KEY, HttpRedirectMode.INITIAL);
  254. int redirectLimit = config.getInt(HTTP, MAX_REDIRECTS_KEY,
  255. MAX_REDIRECTS);
  256. if (redirectLimit < 0) {
  257. redirectLimit = MAX_REDIRECTS;
  258. }
  259. cookieFile = config.getString(HTTP, null, COOKIE_FILE_KEY);
  260. saveCookies = config.getBoolean(HTTP, SAVE_COOKIES_KEY, false);
  261. cookieFileCacheLimit = config.getInt(HTTP, COOKIE_FILE_CACHE_LIMIT_KEY,
  262. DEFAULT_COOKIE_FILE_CACHE_LIMIT);
  263. String match = findMatch(config.getSubsections(HTTP), uri);
  264. if (match != null) {
  265. // Override with more specific items
  266. postBufferSize = config.getInt(HTTP, match, POST_BUFFER_KEY,
  267. postBufferSize);
  268. sslVerifyFlag = config.getBoolean(HTTP, match, SSL_VERIFY_KEY,
  269. sslVerifyFlag);
  270. followRedirectsMode = config.getEnum(HttpRedirectMode.values(),
  271. HTTP, match, FOLLOW_REDIRECTS_KEY, followRedirectsMode);
  272. int newMaxRedirects = config.getInt(HTTP, match, MAX_REDIRECTS_KEY,
  273. redirectLimit);
  274. if (newMaxRedirects >= 0) {
  275. redirectLimit = newMaxRedirects;
  276. }
  277. String urlSpecificCookieFile = config.getString(HTTP, match,
  278. COOKIE_FILE_KEY);
  279. if (urlSpecificCookieFile != null) {
  280. cookieFile = urlSpecificCookieFile;
  281. }
  282. saveCookies = config.getBoolean(HTTP, match, SAVE_COOKIES_KEY,
  283. saveCookies);
  284. }
  285. postBuffer = postBufferSize;
  286. sslVerify = sslVerifyFlag;
  287. followRedirects = followRedirectsMode;
  288. maxRedirects = redirectLimit;
  289. }
  290. /**
  291. * Determines the best match from a set of subsection names (representing
  292. * prefix URLs) for the given {@link URIish}.
  293. *
  294. * @param names
  295. * to match against the {@code uri}
  296. * @param uri
  297. * to find a match for
  298. * @return the best matching subsection name, or {@code null} if no
  299. * subsection matches
  300. */
  301. private String findMatch(Set<String> names, URIish uri) {
  302. String bestMatch = null;
  303. int bestMatchLength = -1;
  304. boolean withUser = false;
  305. String uPath = uri.getPath();
  306. boolean hasPath = !StringUtils.isEmptyOrNull(uPath);
  307. if (hasPath) {
  308. uPath = normalize(uPath);
  309. if (uPath == null) {
  310. // Normalization failed; warning was logged.
  311. return null;
  312. }
  313. }
  314. for (String s : names) {
  315. try {
  316. URIish candidate = new URIish(s);
  317. // Scheme and host must match case-insensitively
  318. if (!compare(uri.getScheme(), candidate.getScheme())
  319. || !compare(uri.getHost(), candidate.getHost())) {
  320. continue;
  321. }
  322. // Ports must match after default ports have been substituted
  323. if (defaultedPort(uri.getPort(),
  324. uri.getScheme()) != defaultedPort(candidate.getPort(),
  325. candidate.getScheme())) {
  326. continue;
  327. }
  328. // User: if present in candidate, must match
  329. boolean hasUser = false;
  330. if (candidate.getUser() != null) {
  331. if (!candidate.getUser().equals(uri.getUser())) {
  332. continue;
  333. }
  334. hasUser = true;
  335. }
  336. // Path: prefix match, longer is better
  337. String cPath = candidate.getPath();
  338. int matchLength = -1;
  339. if (StringUtils.isEmptyOrNull(cPath)) {
  340. matchLength = 0;
  341. } else {
  342. if (!hasPath) {
  343. continue;
  344. }
  345. // Paths can match only on segments
  346. matchLength = segmentCompare(uPath, cPath);
  347. if (matchLength < 0) {
  348. continue;
  349. }
  350. }
  351. // A longer path match is always preferred even over a user
  352. // match. If the path matches are equal, a match with user wins
  353. // over a match without user.
  354. if (matchLength > bestMatchLength
  355. || (!withUser && hasUser && matchLength >= 0
  356. && matchLength == bestMatchLength)) {
  357. bestMatch = s;
  358. bestMatchLength = matchLength;
  359. withUser = hasUser;
  360. }
  361. } catch (URISyntaxException e) {
  362. LOG.warn(MessageFormat
  363. .format(JGitText.get().httpConfigInvalidURL, s));
  364. }
  365. }
  366. return bestMatch;
  367. }
  368. private boolean compare(String a, String b) {
  369. if (a == null) {
  370. return b == null;
  371. }
  372. return a.equalsIgnoreCase(b);
  373. }
  374. private int defaultedPort(int port, String scheme) {
  375. if (port >= 0) {
  376. return port;
  377. }
  378. if (FTP.equalsIgnoreCase(scheme)) {
  379. return 21;
  380. } else if (HTTP.equalsIgnoreCase(scheme)) {
  381. return 80;
  382. } else {
  383. return 443; // https
  384. }
  385. }
  386. static int segmentCompare(String uriPath, String m) {
  387. // Precondition: !uriPath.isEmpty() && !m.isEmpty(),and u must already
  388. // be normalized
  389. String matchPath = normalize(m);
  390. if (matchPath == null || !uriPath.startsWith(matchPath)) {
  391. return -1;
  392. }
  393. // We can match only on a segment boundary: either both paths are equal,
  394. // or if matchPath does not end in '/', there is a '/' in uriPath right
  395. // after the match.
  396. int uLength = uriPath.length();
  397. int mLength = matchPath.length();
  398. if (mLength == uLength || matchPath.charAt(mLength - 1) == '/'
  399. || (mLength < uLength && uriPath.charAt(mLength) == '/')) {
  400. return mLength;
  401. }
  402. return -1;
  403. }
  404. static String normalize(String path) {
  405. // C-git resolves . and .. segments
  406. int i = 0;
  407. int length = path.length();
  408. StringBuilder builder = new StringBuilder(length);
  409. builder.append('/');
  410. if (length > 0 && path.charAt(0) == '/') {
  411. i = 1;
  412. }
  413. while (i < length) {
  414. int slash = path.indexOf('/', i);
  415. if (slash < 0) {
  416. slash = length;
  417. }
  418. if (slash == i || (slash == i + 1 && path.charAt(i) == '.')) {
  419. // Skip /. or also double slashes
  420. } else if (slash == i + 2 && path.charAt(i) == '.'
  421. && path.charAt(i + 1) == '.') {
  422. // Remove previous segment if we have "/.."
  423. int l = builder.length() - 2; // Skip terminating slash.
  424. while (l >= 0 && builder.charAt(l) != '/') {
  425. l--;
  426. }
  427. if (l < 0) {
  428. LOG.warn(MessageFormat.format(
  429. JGitText.get().httpConfigCannotNormalizeURL, path));
  430. return null;
  431. }
  432. builder.setLength(l + 1);
  433. } else {
  434. // Include the slash, if any
  435. builder.append(path, i, Math.min(length, slash + 1));
  436. }
  437. i = slash + 1;
  438. }
  439. if (builder.length() > 1 && builder.charAt(builder.length() - 1) == '/'
  440. && length > 0 && path.charAt(length - 1) != '/') {
  441. // . or .. normalization left a trailing slash when the original
  442. // path had none at the end
  443. builder.setLength(builder.length() - 1);
  444. }
  445. return builder.toString();
  446. }
  447. }