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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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.storage.file.FileBasedConfig;
  54. import org.eclipse.jgit.util.FS;
  55. import org.eclipse.jgit.util.StringUtils;
  56. import org.eclipse.jgit.util.SystemReader;
  57. import org.slf4j.Logger;
  58. import org.slf4j.LoggerFactory;
  59. /**
  60. * A representation of the "http.*" config values in a git
  61. * {@link org.eclipse.jgit.lib.Config}. git provides for setting values for
  62. * specific URLs through "http.&lt;url&gt;.*" subsections. git always considers
  63. * only the initial original URL for such settings, not any redirected URL.
  64. *
  65. * @since 4.9
  66. */
  67. public class HttpConfig {
  68. private static final Logger LOG = LoggerFactory.getLogger(HttpConfig.class);
  69. private static final String FTP = "ftp"; //$NON-NLS-1$
  70. /** git config section key for http settings. */
  71. public static final String HTTP = "http"; //$NON-NLS-1$
  72. /** git config key for the "followRedirects" setting. */
  73. public static final String FOLLOW_REDIRECTS_KEY = "followRedirects"; //$NON-NLS-1$
  74. /** git config key for the "maxRedirects" setting. */
  75. public static final String MAX_REDIRECTS_KEY = "maxRedirects"; //$NON-NLS-1$
  76. /** git config key for the "postBuffer" setting. */
  77. public static final String POST_BUFFER_KEY = "postBuffer"; //$NON-NLS-1$
  78. /** git config key for the "sslVerify" setting. */
  79. public static final String SSL_VERIFY_KEY = "sslVerify"; //$NON-NLS-1$
  80. /**
  81. * git config key for the "cookieFile" setting.
  82. *
  83. * @since 5.4
  84. */
  85. public static final String COOKIE_FILE_KEY = "cookieFile"; //$NON-NLS-1$
  86. /**
  87. * git config key for the "saveCookies" setting.
  88. *
  89. * @since 5.4
  90. */
  91. public static final String SAVE_COOKIES_KEY = "saveCookies"; //$NON-NLS-1$
  92. /**
  93. * Custom JGit config key which holds the maximum number of cookie files to
  94. * keep in the cache.
  95. *
  96. * @since 5.4
  97. */
  98. public static final String COOKIE_FILE_CACHE_LIMIT_KEY = "cookieFileCacheLimit"; //$NON-NLS-1$
  99. private static final int DEFAULT_COOKIE_FILE_CACHE_LIMIT = 10;
  100. private static final String MAX_REDIRECT_SYSTEM_PROPERTY = "http.maxRedirects"; //$NON-NLS-1$
  101. private static final int DEFAULT_MAX_REDIRECTS = 5;
  102. private static final int MAX_REDIRECTS = (new Supplier<Integer>() {
  103. @Override
  104. public Integer get() {
  105. String rawValue = SystemReader.getInstance()
  106. .getProperty(MAX_REDIRECT_SYSTEM_PROPERTY);
  107. Integer value = Integer.valueOf(DEFAULT_MAX_REDIRECTS);
  108. if (rawValue != null) {
  109. try {
  110. value = Integer.valueOf(Integer.parseUnsignedInt(rawValue));
  111. } catch (NumberFormatException e) {
  112. LOG.warn(MessageFormat.format(
  113. JGitText.get().invalidSystemProperty,
  114. MAX_REDIRECT_SYSTEM_PROPERTY, rawValue, value));
  115. }
  116. }
  117. return value;
  118. }
  119. }).get().intValue();
  120. /**
  121. * Config values for http.followRedirect.
  122. */
  123. public enum HttpRedirectMode implements Config.ConfigEnum {
  124. /** Always follow redirects (up to the http.maxRedirects limit). */
  125. TRUE("true"), //$NON-NLS-1$
  126. /**
  127. * Only follow redirects on the initial GET request. This is the
  128. * default.
  129. */
  130. INITIAL("initial"), //$NON-NLS-1$
  131. /** Never follow redirects. */
  132. FALSE("false"); //$NON-NLS-1$
  133. private final String configValue;
  134. private HttpRedirectMode(String configValue) {
  135. this.configValue = configValue;
  136. }
  137. @Override
  138. public String toConfigValue() {
  139. return configValue;
  140. }
  141. @Override
  142. public boolean matchConfigValue(String s) {
  143. return configValue.equals(s);
  144. }
  145. }
  146. private int postBuffer;
  147. private boolean sslVerify;
  148. private HttpRedirectMode followRedirects;
  149. private int maxRedirects;
  150. private String cookieFile;
  151. private boolean saveCookies;
  152. private int cookieFileCacheLimit;
  153. /**
  154. * Get the "http.postBuffer" setting
  155. *
  156. * @return the value of the "http.postBuffer" setting
  157. */
  158. public int getPostBuffer() {
  159. return postBuffer;
  160. }
  161. /**
  162. * Get the "http.sslVerify" setting
  163. *
  164. * @return the value of the "http.sslVerify" setting
  165. */
  166. public boolean isSslVerify() {
  167. return sslVerify;
  168. }
  169. /**
  170. * Get the "http.followRedirects" setting
  171. *
  172. * @return the value of the "http.followRedirects" setting
  173. */
  174. public HttpRedirectMode getFollowRedirects() {
  175. return followRedirects;
  176. }
  177. /**
  178. * Get the "http.maxRedirects" setting
  179. *
  180. * @return the value of the "http.maxRedirects" setting
  181. */
  182. public int getMaxRedirects() {
  183. return maxRedirects;
  184. }
  185. /**
  186. * Get the "http.cookieFile" setting
  187. *
  188. * @return the value of the "http.cookieFile" setting
  189. *
  190. * @since 5.4
  191. */
  192. public String getCookieFile() {
  193. return cookieFile;
  194. }
  195. /**
  196. * Get the "http.saveCookies" setting
  197. *
  198. * @return the value of the "http.saveCookies" setting
  199. *
  200. * @since 5.4
  201. */
  202. public boolean getSaveCookies() {
  203. return saveCookies;
  204. }
  205. /**
  206. * Get the "http.cookieFileCacheLimit" setting (gives the maximum number of
  207. * cookie files to keep in the LRU cache)
  208. *
  209. * @return the value of the "http.cookieFileCacheLimit" setting
  210. *
  211. * @since 5.4
  212. */
  213. public int getCookieFileCacheLimit() {
  214. return cookieFileCacheLimit;
  215. }
  216. /**
  217. * Creates a new {@link org.eclipse.jgit.transport.HttpConfig} tailored to
  218. * the given {@link org.eclipse.jgit.transport.URIish}.
  219. *
  220. * @param config
  221. * to read the {@link org.eclipse.jgit.transport.HttpConfig} from
  222. * @param uri
  223. * to get the configuration values for
  224. */
  225. public HttpConfig(Config config, URIish uri) {
  226. init(config, uri);
  227. }
  228. /**
  229. * Creates a {@link org.eclipse.jgit.transport.HttpConfig} that reads values
  230. * solely from the user config.
  231. *
  232. * @param uri
  233. * to get the configuration values for
  234. */
  235. public HttpConfig(URIish uri) {
  236. FileBasedConfig userConfig = SystemReader.getInstance()
  237. .openUserConfig(null, FS.DETECTED);
  238. try {
  239. userConfig.load();
  240. } catch (IOException | ConfigInvalidException e) {
  241. // Log it and then work with default values.
  242. LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid,
  243. userConfig.getFile().getAbsolutePath(), e));
  244. init(new Config(), uri);
  245. return;
  246. }
  247. init(userConfig, uri);
  248. }
  249. private void init(Config config, URIish uri) {
  250. // Set defaults from the section first
  251. int postBufferSize = config.getInt(HTTP, POST_BUFFER_KEY,
  252. 1 * 1024 * 1024);
  253. boolean sslVerifyFlag = config.getBoolean(HTTP, SSL_VERIFY_KEY, true);
  254. HttpRedirectMode followRedirectsMode = config.getEnum(
  255. HttpRedirectMode.values(), HTTP, null,
  256. FOLLOW_REDIRECTS_KEY, HttpRedirectMode.INITIAL);
  257. int redirectLimit = config.getInt(HTTP, MAX_REDIRECTS_KEY,
  258. MAX_REDIRECTS);
  259. if (redirectLimit < 0) {
  260. redirectLimit = MAX_REDIRECTS;
  261. }
  262. cookieFile = config.getString(HTTP, null, COOKIE_FILE_KEY);
  263. saveCookies = config.getBoolean(HTTP, SAVE_COOKIES_KEY, false);
  264. cookieFileCacheLimit = config.getInt(HTTP, COOKIE_FILE_CACHE_LIMIT_KEY,
  265. DEFAULT_COOKIE_FILE_CACHE_LIMIT);
  266. String match = findMatch(config.getSubsections(HTTP), uri);
  267. if (match != null) {
  268. // Override with more specific items
  269. postBufferSize = config.getInt(HTTP, match, POST_BUFFER_KEY,
  270. postBufferSize);
  271. sslVerifyFlag = config.getBoolean(HTTP, match, SSL_VERIFY_KEY,
  272. sslVerifyFlag);
  273. followRedirectsMode = config.getEnum(HttpRedirectMode.values(),
  274. HTTP, match, FOLLOW_REDIRECTS_KEY, followRedirectsMode);
  275. int newMaxRedirects = config.getInt(HTTP, match, MAX_REDIRECTS_KEY,
  276. redirectLimit);
  277. if (newMaxRedirects >= 0) {
  278. redirectLimit = newMaxRedirects;
  279. }
  280. String urlSpecificCookieFile = config.getString(HTTP, match,
  281. COOKIE_FILE_KEY);
  282. if (urlSpecificCookieFile != null) {
  283. cookieFile = urlSpecificCookieFile;
  284. }
  285. saveCookies = config.getBoolean(HTTP, match, SAVE_COOKIES_KEY,
  286. saveCookies);
  287. }
  288. postBuffer = postBufferSize;
  289. sslVerify = sslVerifyFlag;
  290. followRedirects = followRedirectsMode;
  291. maxRedirects = redirectLimit;
  292. }
  293. /**
  294. * Determines the best match from a set of subsection names (representing
  295. * prefix URLs) for the given {@link URIish}.
  296. *
  297. * @param names
  298. * to match against the {@code uri}
  299. * @param uri
  300. * to find a match for
  301. * @return the best matching subsection name, or {@code null} if no
  302. * subsection matches
  303. */
  304. private String findMatch(Set<String> names, URIish uri) {
  305. String bestMatch = null;
  306. int bestMatchLength = -1;
  307. boolean withUser = false;
  308. String uPath = uri.getPath();
  309. boolean hasPath = !StringUtils.isEmptyOrNull(uPath);
  310. if (hasPath) {
  311. uPath = normalize(uPath);
  312. if (uPath == null) {
  313. // Normalization failed; warning was logged.
  314. return null;
  315. }
  316. }
  317. for (String s : names) {
  318. try {
  319. URIish candidate = new URIish(s);
  320. // Scheme and host must match case-insensitively
  321. if (!compare(uri.getScheme(), candidate.getScheme())
  322. || !compare(uri.getHost(), candidate.getHost())) {
  323. continue;
  324. }
  325. // Ports must match after default ports have been substituted
  326. if (defaultedPort(uri.getPort(),
  327. uri.getScheme()) != defaultedPort(candidate.getPort(),
  328. candidate.getScheme())) {
  329. continue;
  330. }
  331. // User: if present in candidate, must match
  332. boolean hasUser = false;
  333. if (candidate.getUser() != null) {
  334. if (!candidate.getUser().equals(uri.getUser())) {
  335. continue;
  336. }
  337. hasUser = true;
  338. }
  339. // Path: prefix match, longer is better
  340. String cPath = candidate.getPath();
  341. int matchLength = -1;
  342. if (StringUtils.isEmptyOrNull(cPath)) {
  343. matchLength = 0;
  344. } else {
  345. if (!hasPath) {
  346. continue;
  347. }
  348. // Paths can match only on segments
  349. matchLength = segmentCompare(uPath, cPath);
  350. if (matchLength < 0) {
  351. continue;
  352. }
  353. }
  354. // A longer path match is always preferred even over a user
  355. // match. If the path matches are equal, a match with user wins
  356. // over a match without user.
  357. if (matchLength > bestMatchLength
  358. || (!withUser && hasUser && matchLength >= 0
  359. && matchLength == bestMatchLength)) {
  360. bestMatch = s;
  361. bestMatchLength = matchLength;
  362. withUser = hasUser;
  363. }
  364. } catch (URISyntaxException e) {
  365. LOG.warn(MessageFormat
  366. .format(JGitText.get().httpConfigInvalidURL, s));
  367. }
  368. }
  369. return bestMatch;
  370. }
  371. private boolean compare(String a, String b) {
  372. if (a == null) {
  373. return b == null;
  374. }
  375. return a.equalsIgnoreCase(b);
  376. }
  377. private int defaultedPort(int port, String scheme) {
  378. if (port >= 0) {
  379. return port;
  380. }
  381. if (FTP.equalsIgnoreCase(scheme)) {
  382. return 21;
  383. } else if (HTTP.equalsIgnoreCase(scheme)) {
  384. return 80;
  385. } else {
  386. return 443; // https
  387. }
  388. }
  389. static int segmentCompare(String uriPath, String m) {
  390. // Precondition: !uriPath.isEmpty() && !m.isEmpty(),and u must already
  391. // be normalized
  392. String matchPath = normalize(m);
  393. if (matchPath == null || !uriPath.startsWith(matchPath)) {
  394. return -1;
  395. }
  396. // We can match only on a segment boundary: either both paths are equal,
  397. // or if matchPath does not end in '/', there is a '/' in uriPath right
  398. // after the match.
  399. int uLength = uriPath.length();
  400. int mLength = matchPath.length();
  401. if (mLength == uLength || matchPath.charAt(mLength - 1) == '/'
  402. || (mLength < uLength && uriPath.charAt(mLength) == '/')) {
  403. return mLength;
  404. }
  405. return -1;
  406. }
  407. static String normalize(String path) {
  408. // C-git resolves . and .. segments
  409. int i = 0;
  410. int length = path.length();
  411. StringBuilder builder = new StringBuilder(length);
  412. builder.append('/');
  413. if (length > 0 && path.charAt(0) == '/') {
  414. i = 1;
  415. }
  416. while (i < length) {
  417. int slash = path.indexOf('/', i);
  418. if (slash < 0) {
  419. slash = length;
  420. }
  421. if (slash == i || (slash == i + 1 && path.charAt(i) == '.')) {
  422. // Skip /. or also double slashes
  423. } else if (slash == i + 2 && path.charAt(i) == '.'
  424. && path.charAt(i + 1) == '.') {
  425. // Remove previous segment if we have "/.."
  426. int l = builder.length() - 2; // Skip terminating slash.
  427. while (l >= 0 && builder.charAt(l) != '/') {
  428. l--;
  429. }
  430. if (l < 0) {
  431. LOG.warn(MessageFormat.format(
  432. JGitText.get().httpConfigCannotNormalizeURL, path));
  433. return null;
  434. }
  435. builder.setLength(l + 1);
  436. } else {
  437. // Include the slash, if any
  438. builder.append(path, i, Math.min(length, slash + 1));
  439. }
  440. i = slash + 1;
  441. }
  442. if (builder.length() > 1 && builder.charAt(builder.length() - 1) == '/'
  443. && length > 0 && path.charAt(length - 1) != '/') {
  444. // . or .. normalization left a trailing slash when the original
  445. // path had none at the end
  446. builder.setLength(builder.length() - 1);
  447. }
  448. return builder.toString();
  449. }
  450. }