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

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