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

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