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

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