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.

OpenSshConfigFile.java 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  1. /*
  2. * Copyright (C) 2008, 2017, Google Inc.
  3. * Copyright (C) 2017, 2021, Thomas Wolf <thomas.wolf@paranor.ch> and others
  4. *
  5. * This program and the accompanying materials are made available under the
  6. * terms of the Eclipse Distribution License v. 1.0 which is available at
  7. * https://www.eclipse.org/org/documents/edl-v10.php.
  8. *
  9. * SPDX-License-Identifier: BSD-3-Clause
  10. */
  11. package org.eclipse.jgit.internal.transport.ssh;
  12. import static java.nio.charset.StandardCharsets.UTF_8;
  13. import java.io.BufferedReader;
  14. import java.io.File;
  15. import java.io.IOException;
  16. import java.nio.file.Files;
  17. import java.time.Instant;
  18. import java.util.ArrayList;
  19. import java.util.Collections;
  20. import java.util.HashMap;
  21. import java.util.Iterator;
  22. import java.util.LinkedList;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.Set;
  26. import java.util.TreeMap;
  27. import java.util.TreeSet;
  28. import org.eclipse.jgit.annotations.NonNull;
  29. import org.eclipse.jgit.errors.InvalidPatternException;
  30. import org.eclipse.jgit.fnmatch.FileNameMatcher;
  31. import org.eclipse.jgit.transport.SshConfigStore;
  32. import org.eclipse.jgit.transport.SshConstants;
  33. import org.eclipse.jgit.util.FS;
  34. import org.eclipse.jgit.util.StringUtils;
  35. import org.eclipse.jgit.util.SystemReader;
  36. /**
  37. * Fairly complete configuration parser for the openssh ~/.ssh/config file.
  38. * <p>
  39. * Both JSch 0.1.54 and Apache MINA sshd 2.1.0 have parsers for this, but both
  40. * are buggy. Therefore we implement our own parser to read an openssh
  41. * configuration file.
  42. * </p>
  43. * <p>
  44. * Limitations compared to the full openssh 7.5 parser:
  45. * </p>
  46. * <ul>
  47. * <li>This parser does not handle Match or Include keywords.
  48. * <li>This parser does not do host name canonicalization.
  49. * </ul>
  50. * <p>
  51. * Note that openssh's readconf.c is a validating parser; this parser does not
  52. * validate entries.
  53. * </p>
  54. * <p>
  55. * This config does %-substitutions for the following tokens:
  56. * </p>
  57. * <ul>
  58. * <li>%% - single %
  59. * <li>%C - short-hand for %l%h%p%r.
  60. * <li>%d - home directory path
  61. * <li>%h - remote host name
  62. * <li>%L - local host name without domain
  63. * <li>%l - FQDN of the local host
  64. * <li>%n - host name as specified in {@link #lookup(String, int, String)}
  65. * <li>%p - port number; if not given in {@link #lookup(String, int, String)}
  66. * replaced only if set in the config
  67. * <li>%r - remote user name; if not given in
  68. * {@link #lookup(String, int, String)} replaced only if set in the config
  69. * <li>%u - local user name
  70. * </ul>
  71. * <p>
  72. * %i is not handled; Java has no concept of a "user ID". %T is always replaced
  73. * by NONE.
  74. * </p>
  75. *
  76. * @see <a href="http://man.openbsd.org/OpenBSD-current/man5/ssh_config.5">man
  77. * ssh-config</a>
  78. */
  79. public class OpenSshConfigFile implements SshConfigStore {
  80. /** The user's home directory, as key files may be relative to here. */
  81. private final File home;
  82. /** The .ssh/config file we read and monitor for updates. */
  83. private final File configFile;
  84. /** User name of the user on the host OS. */
  85. private final String localUserName;
  86. /** Modification time of {@link #configFile} when it was last loaded. */
  87. private Instant lastModified;
  88. /**
  89. * Encapsulates entries read out of the configuration file, and a cache of
  90. * fully resolved entries created from that.
  91. */
  92. private static class State {
  93. List<HostEntry> entries = new LinkedList<>();
  94. // Previous lookups, keyed by user@hostname:port
  95. Map<String, HostEntry> hosts = new HashMap<>();
  96. @Override
  97. @SuppressWarnings("nls")
  98. public String toString() {
  99. return "State [entries=" + entries + ", hosts=" + hosts + "]";
  100. }
  101. }
  102. /** State read from the config file, plus the cache. */
  103. private State state;
  104. /**
  105. * Creates a new {@link OpenSshConfigFile} that will read the config from
  106. * file {@code config} use the given file {@code home} as "home" directory.
  107. *
  108. * @param home
  109. * user's home directory for the purpose of ~ replacement
  110. * @param config
  111. * file to load.
  112. * @param localUserName
  113. * user name of the current user on the local host OS
  114. */
  115. public OpenSshConfigFile(@NonNull File home, @NonNull File config,
  116. @NonNull String localUserName) {
  117. this.home = home;
  118. this.configFile = config;
  119. this.localUserName = localUserName;
  120. state = new State();
  121. }
  122. /**
  123. * Locate the configuration for a specific host request.
  124. *
  125. * @param hostName
  126. * the name the user has supplied to the SSH tool. This may be a
  127. * real host name, or it may just be a "Host" block in the
  128. * configuration file.
  129. * @param port
  130. * the user supplied; <= 0 if none
  131. * @param userName
  132. * the user supplied, may be {@code null} or empty if none given
  133. * @return the configuration for the requested name.
  134. */
  135. @Override
  136. @NonNull
  137. public HostEntry lookup(@NonNull String hostName, int port,
  138. String userName) {
  139. final State cache = refresh();
  140. String cacheKey = toCacheKey(hostName, port, userName);
  141. HostEntry h = cache.hosts.get(cacheKey);
  142. if (h != null) {
  143. return h;
  144. }
  145. HostEntry fullConfig = new HostEntry();
  146. Iterator<HostEntry> entries = cache.entries.iterator();
  147. if (entries.hasNext()) {
  148. // Should always have at least the first top entry containing
  149. // key-value pairs before the first Host block
  150. fullConfig.merge(entries.next());
  151. entries.forEachRemaining(entry -> {
  152. if (entry.matches(hostName)) {
  153. fullConfig.merge(entry);
  154. }
  155. });
  156. }
  157. fullConfig.substitute(hostName, port, userName, localUserName, home);
  158. cache.hosts.put(cacheKey, fullConfig);
  159. return fullConfig;
  160. }
  161. @NonNull
  162. private String toCacheKey(@NonNull String hostName, int port,
  163. String userName) {
  164. String key = hostName;
  165. if (port > 0) {
  166. key = key + ':' + Integer.toString(port);
  167. }
  168. if (userName != null && !userName.isEmpty()) {
  169. key = userName + '@' + key;
  170. }
  171. return key;
  172. }
  173. private synchronized State refresh() {
  174. final Instant mtime = FS.DETECTED.lastModifiedInstant(configFile);
  175. if (!mtime.equals(lastModified)) {
  176. State newState = new State();
  177. try (BufferedReader br = Files
  178. .newBufferedReader(configFile.toPath(), UTF_8)) {
  179. newState.entries = parse(br);
  180. } catch (IOException | RuntimeException none) {
  181. // Ignore -- we'll set and return an empty state
  182. }
  183. lastModified = mtime;
  184. state = newState;
  185. }
  186. return state;
  187. }
  188. private List<HostEntry> parse(BufferedReader reader)
  189. throws IOException {
  190. final List<HostEntry> entries = new LinkedList<>();
  191. // The man page doesn't say so, but the openssh parser (readconf.c)
  192. // starts out in active mode and thus always applies any lines that
  193. // occur before the first host block. We gather those options in a
  194. // HostEntry for DEFAULT_NAME.
  195. HostEntry defaults = new HostEntry();
  196. HostEntry current = defaults;
  197. entries.add(defaults);
  198. String line;
  199. while ((line = reader.readLine()) != null) {
  200. // OpenSsh ignores trailing comments on a line. Anything after the
  201. // first # on a line is trimmed away (yes, even if the hash is
  202. // inside quotes).
  203. //
  204. // See https://github.com/openssh/openssh-portable/commit/2bcbf679
  205. int i = line.indexOf('#');
  206. if (i >= 0) {
  207. line = line.substring(0, i);
  208. }
  209. line = line.trim();
  210. if (line.isEmpty()) {
  211. continue;
  212. }
  213. String[] parts = line.split("[ \t]*[= \t]", 2); //$NON-NLS-1$
  214. // Although the ssh-config man page doesn't say so, the openssh
  215. // parser does allow quoted keywords.
  216. String keyword = dequote(parts[0].trim());
  217. // man 5 ssh-config says lines had the format "keyword arguments",
  218. // with no indication that arguments were optional. However, let's
  219. // not crap out on missing arguments. See bug 444319.
  220. String argValue = parts.length > 1 ? parts[1].trim() : ""; //$NON-NLS-1$
  221. if (StringUtils.equalsIgnoreCase(SshConstants.HOST, keyword)) {
  222. current = new HostEntry(parseList(argValue));
  223. entries.add(current);
  224. continue;
  225. }
  226. if (HostEntry.isListKey(keyword)) {
  227. List<String> args = validate(keyword, parseList(argValue));
  228. current.setValue(keyword, args);
  229. } else if (!argValue.isEmpty()) {
  230. argValue = validate(keyword, dequote(argValue));
  231. current.setValue(keyword, argValue);
  232. }
  233. }
  234. return entries;
  235. }
  236. /**
  237. * Splits the argument into a list of whitespace-separated elements.
  238. * Elements containing whitespace must be quoted and will be de-quoted.
  239. *
  240. * @param argument
  241. * argument part of the configuration line as read from the
  242. * config file
  243. * @return a {@link List} of elements, possibly empty and possibly
  244. * containing empty elements, but not containing {@code null}
  245. */
  246. private List<String> parseList(String argument) {
  247. List<String> result = new ArrayList<>(4);
  248. int start = 0;
  249. int length = argument.length();
  250. while (start < length) {
  251. // Skip whitespace
  252. if (Character.isSpaceChar(argument.charAt(start))) {
  253. start++;
  254. continue;
  255. }
  256. if (argument.charAt(start) == '"') {
  257. int stop = argument.indexOf('"', ++start);
  258. if (stop < start) {
  259. // No closing double quote: skip
  260. break;
  261. }
  262. result.add(argument.substring(start, stop));
  263. start = stop + 1;
  264. } else {
  265. int stop = start + 1;
  266. while (stop < length
  267. && !Character.isSpaceChar(argument.charAt(stop))) {
  268. stop++;
  269. }
  270. result.add(argument.substring(start, stop));
  271. start = stop + 1;
  272. }
  273. }
  274. return result;
  275. }
  276. /**
  277. * Hook to perform validation on a single value, or to sanitize it. If this
  278. * throws an (unchecked) exception, parsing of the file is abandoned.
  279. *
  280. * @param key
  281. * of the entry
  282. * @param value
  283. * as read from the config file
  284. * @return the validated and possibly sanitized value
  285. */
  286. protected String validate(String key, String value) {
  287. if (String.CASE_INSENSITIVE_ORDER.compare(key,
  288. SshConstants.PREFERRED_AUTHENTICATIONS) == 0) {
  289. return stripWhitespace(value);
  290. }
  291. return value;
  292. }
  293. /**
  294. * Hook to perform validation on values, or to sanitize them. If this throws
  295. * an (unchecked) exception, parsing of the file is abandoned.
  296. *
  297. * @param key
  298. * of the entry
  299. * @param value
  300. * list of arguments as read from the config file
  301. * @return a {@link List} of values, possibly empty and possibly containing
  302. * empty elements, but not containing {@code null}
  303. */
  304. protected List<String> validate(String key, List<String> value) {
  305. return value;
  306. }
  307. private static boolean patternMatchesHost(String pattern, String name) {
  308. if (pattern.indexOf('*') >= 0 || pattern.indexOf('?') >= 0) {
  309. final FileNameMatcher fn;
  310. try {
  311. fn = new FileNameMatcher(pattern, null);
  312. } catch (InvalidPatternException e) {
  313. return false;
  314. }
  315. fn.append(name);
  316. return fn.isMatch();
  317. }
  318. // Not a pattern but a full host name
  319. return pattern.equals(name);
  320. }
  321. private static String dequote(String value) {
  322. if (value.startsWith("\"") && value.endsWith("\"") //$NON-NLS-1$ //$NON-NLS-2$
  323. && value.length() > 1)
  324. return value.substring(1, value.length() - 1);
  325. return value;
  326. }
  327. private static String stripWhitespace(String value) {
  328. final StringBuilder b = new StringBuilder();
  329. for (int i = 0; i < value.length(); i++) {
  330. if (!Character.isSpaceChar(value.charAt(i)))
  331. b.append(value.charAt(i));
  332. }
  333. return b.toString();
  334. }
  335. private static File toFile(String path, File home) {
  336. if (path.startsWith("~/") || path.startsWith("~" + File.separator)) { //$NON-NLS-1$ //$NON-NLS-2$
  337. return new File(home, path.substring(2));
  338. }
  339. File ret = new File(path);
  340. if (ret.isAbsolute()) {
  341. return ret;
  342. }
  343. return new File(home, path);
  344. }
  345. /**
  346. * Converts a positive value into an {@code int}.
  347. *
  348. * @param value
  349. * to convert
  350. * @return the value, or -1 if it wasn't a positive integral value
  351. */
  352. public static int positive(String value) {
  353. if (value != null) {
  354. try {
  355. return Integer.parseUnsignedInt(value);
  356. } catch (NumberFormatException e) {
  357. // Ignore
  358. }
  359. }
  360. return -1;
  361. }
  362. /**
  363. * Converts a ssh config flag value (yes/true/on - no/false/off) into an
  364. * {@code boolean}.
  365. *
  366. * @param value
  367. * to convert
  368. * @return {@code true} if {@code value} is "yes", "on", or "true";
  369. * {@code false} otherwise
  370. */
  371. public static boolean flag(String value) {
  372. if (value == null) {
  373. return false;
  374. }
  375. return SshConstants.YES.equals(value) || SshConstants.ON.equals(value)
  376. || SshConstants.TRUE.equals(value);
  377. }
  378. /**
  379. * Retrieves the local user name as given in the constructor.
  380. *
  381. * @return the user name
  382. */
  383. public String getLocalUserName() {
  384. return localUserName;
  385. }
  386. /**
  387. * A host entry from the ssh config file. Any merging of global values and
  388. * of several matching host entries, %-substitutions, and ~ replacement have
  389. * all been done.
  390. */
  391. public static class HostEntry implements SshConfigStore.HostConfig {
  392. /**
  393. * Keys that can be specified multiple times, building up a list. (I.e.,
  394. * those are the keys that do not follow the general rule of "first
  395. * occurrence wins".)
  396. */
  397. private static final Set<String> MULTI_KEYS = new TreeSet<>(
  398. String.CASE_INSENSITIVE_ORDER);
  399. static {
  400. MULTI_KEYS.add(SshConstants.CERTIFICATE_FILE);
  401. MULTI_KEYS.add(SshConstants.IDENTITY_FILE);
  402. MULTI_KEYS.add(SshConstants.LOCAL_FORWARD);
  403. MULTI_KEYS.add(SshConstants.REMOTE_FORWARD);
  404. MULTI_KEYS.add(SshConstants.SEND_ENV);
  405. }
  406. /**
  407. * Keys that take a whitespace-separated list of elements as argument.
  408. * Because the dequote-handling is different, we must handle those in
  409. * the parser. There are a few other keys that take comma-separated
  410. * lists as arguments, but for the parser those are single arguments
  411. * that must be quoted if they contain whitespace, and taking them apart
  412. * is the responsibility of the user of those keys.
  413. */
  414. private static final Set<String> LIST_KEYS = new TreeSet<>(
  415. String.CASE_INSENSITIVE_ORDER);
  416. static {
  417. LIST_KEYS.add(SshConstants.CANONICAL_DOMAINS);
  418. LIST_KEYS.add(SshConstants.GLOBAL_KNOWN_HOSTS_FILE);
  419. LIST_KEYS.add(SshConstants.SEND_ENV);
  420. LIST_KEYS.add(SshConstants.USER_KNOWN_HOSTS_FILE);
  421. }
  422. /**
  423. * OpenSSH has renamed some config keys. This maps old names to new
  424. * names.
  425. */
  426. private static final Map<String, String> ALIASES = new TreeMap<>(
  427. String.CASE_INSENSITIVE_ORDER);
  428. static {
  429. // See https://github.com/openssh/openssh-portable/commit/ee9c0da80
  430. ALIASES.put("PubkeyAcceptedKeyTypes", //$NON-NLS-1$
  431. SshConstants.PUBKEY_ACCEPTED_ALGORITHMS);
  432. }
  433. private Map<String, String> options;
  434. private Map<String, List<String>> multiOptions;
  435. private Map<String, List<String>> listOptions;
  436. private final List<String> patterns;
  437. // Constructor used to build the merged entry; never matches anything
  438. HostEntry() {
  439. this.patterns = Collections.emptyList();
  440. }
  441. HostEntry(List<String> patterns) {
  442. this.patterns = patterns;
  443. }
  444. boolean matches(String hostName) {
  445. boolean doesMatch = false;
  446. for (String pattern : patterns) {
  447. if (pattern.startsWith("!")) { //$NON-NLS-1$
  448. if (patternMatchesHost(pattern.substring(1), hostName)) {
  449. return false;
  450. }
  451. } else if (!doesMatch
  452. && patternMatchesHost(pattern, hostName)) {
  453. doesMatch = true;
  454. }
  455. }
  456. return doesMatch;
  457. }
  458. private static String toKey(String key) {
  459. String k = ALIASES.get(key);
  460. return k != null ? k : key;
  461. }
  462. /**
  463. * Retrieves the value of a single-valued key, or the first if the key
  464. * has multiple values. Keys are case-insensitive, so
  465. * {@code getValue("HostName") == getValue("HOSTNAME")}.
  466. *
  467. * @param key
  468. * to get the value of
  469. * @return the value, or {@code null} if none
  470. */
  471. @Override
  472. public String getValue(String key) {
  473. String k = toKey(key);
  474. String result = options != null ? options.get(k) : null;
  475. if (result == null) {
  476. // Let's be lenient and return at least the first value from
  477. // a list-valued or multi-valued key.
  478. List<String> values = listOptions != null ? listOptions.get(k)
  479. : null;
  480. if (values == null) {
  481. values = multiOptions != null ? multiOptions.get(k) : null;
  482. }
  483. if (values != null && !values.isEmpty()) {
  484. result = values.get(0);
  485. }
  486. }
  487. return result;
  488. }
  489. /**
  490. * Retrieves the values of a multi or list-valued key. Keys are
  491. * case-insensitive, so
  492. * {@code getValue("HostName") == getValue("HOSTNAME")}.
  493. *
  494. * @param key
  495. * to get the values of
  496. * @return a possibly empty list of values
  497. */
  498. @Override
  499. public List<String> getValues(String key) {
  500. String k = toKey(key);
  501. List<String> values = listOptions != null ? listOptions.get(k)
  502. : null;
  503. if (values == null) {
  504. values = multiOptions != null ? multiOptions.get(k) : null;
  505. }
  506. if (values == null || values.isEmpty()) {
  507. return new ArrayList<>();
  508. }
  509. return new ArrayList<>(values);
  510. }
  511. /**
  512. * Sets the value of a single-valued key if it not set yet, or adds a
  513. * value to a multi-valued key. If the value is {@code null}, the key is
  514. * removed altogether, whether it is single-, list-, or multi-valued.
  515. *
  516. * @param key
  517. * to modify
  518. * @param value
  519. * to set or add
  520. */
  521. public void setValue(String key, String value) {
  522. String k = toKey(key);
  523. if (value == null) {
  524. if (multiOptions != null) {
  525. multiOptions.remove(k);
  526. }
  527. if (listOptions != null) {
  528. listOptions.remove(k);
  529. }
  530. if (options != null) {
  531. options.remove(k);
  532. }
  533. return;
  534. }
  535. if (MULTI_KEYS.contains(k)) {
  536. if (multiOptions == null) {
  537. multiOptions = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
  538. }
  539. List<String> values = multiOptions.get(k);
  540. if (values == null) {
  541. values = new ArrayList<>(4);
  542. multiOptions.put(k, values);
  543. }
  544. values.add(value);
  545. } else {
  546. if (options == null) {
  547. options = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
  548. }
  549. if (!options.containsKey(k)) {
  550. options.put(k, value);
  551. }
  552. }
  553. }
  554. /**
  555. * Sets the values of a multi- or list-valued key.
  556. *
  557. * @param key
  558. * to set
  559. * @param values
  560. * a non-empty list of values
  561. */
  562. public void setValue(String key, List<String> values) {
  563. if (values.isEmpty()) {
  564. return;
  565. }
  566. String k = toKey(key);
  567. // Check multi-valued keys first; because of the replacement
  568. // strategy, they must take precedence over list-valued keys
  569. // which always follow the "first occurrence wins" strategy.
  570. //
  571. // Note that SendEnv is a multi-valued list-valued key. (It's
  572. // rather immaterial for JGit, though.)
  573. if (MULTI_KEYS.contains(k)) {
  574. if (multiOptions == null) {
  575. multiOptions = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
  576. }
  577. List<String> items = multiOptions.get(k);
  578. if (items == null) {
  579. items = new ArrayList<>(values);
  580. multiOptions.put(k, items);
  581. } else {
  582. items.addAll(values);
  583. }
  584. } else {
  585. if (listOptions == null) {
  586. listOptions = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
  587. }
  588. if (!listOptions.containsKey(k)) {
  589. listOptions.put(k, values);
  590. }
  591. }
  592. }
  593. /**
  594. * Does the key take a whitespace-separated list of values?
  595. *
  596. * @param key
  597. * to check
  598. * @return {@code true} if the key is a list-valued key.
  599. */
  600. public static boolean isListKey(String key) {
  601. return LIST_KEYS.contains(toKey(key));
  602. }
  603. void merge(HostEntry entry) {
  604. if (entry == null) {
  605. // Can occur if we could not read the config file
  606. return;
  607. }
  608. if (entry.options != null) {
  609. if (options == null) {
  610. options = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
  611. }
  612. for (Map.Entry<String, String> item : entry.options
  613. .entrySet()) {
  614. if (!options.containsKey(item.getKey())) {
  615. options.put(item.getKey(), item.getValue());
  616. }
  617. }
  618. }
  619. if (entry.listOptions != null) {
  620. if (listOptions == null) {
  621. listOptions = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
  622. }
  623. for (Map.Entry<String, List<String>> item : entry.listOptions
  624. .entrySet()) {
  625. if (!listOptions.containsKey(item.getKey())) {
  626. listOptions.put(item.getKey(), item.getValue());
  627. }
  628. }
  629. }
  630. if (entry.multiOptions != null) {
  631. if (multiOptions == null) {
  632. multiOptions = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
  633. }
  634. for (Map.Entry<String, List<String>> item : entry.multiOptions
  635. .entrySet()) {
  636. List<String> values = multiOptions.get(item.getKey());
  637. if (values == null) {
  638. values = new ArrayList<>(item.getValue());
  639. multiOptions.put(item.getKey(), values);
  640. } else {
  641. values.addAll(item.getValue());
  642. }
  643. }
  644. }
  645. }
  646. private List<String> substitute(List<String> values, String allowed,
  647. Replacer r, boolean withEnv) {
  648. List<String> result = new ArrayList<>(values.size());
  649. for (String value : values) {
  650. result.add(r.substitute(value, allowed, withEnv));
  651. }
  652. return result;
  653. }
  654. private List<String> replaceTilde(List<String> values, File home) {
  655. List<String> result = new ArrayList<>(values.size());
  656. for (String value : values) {
  657. result.add(toFile(value, home).getPath());
  658. }
  659. return result;
  660. }
  661. void substitute(String originalHostName, int port, String userName,
  662. String localUserName, File home) {
  663. int p = port >= 0 ? port : positive(getValue(SshConstants.PORT));
  664. if (p < 0) {
  665. p = SshConstants.SSH_DEFAULT_PORT;
  666. }
  667. String u = userName != null && !userName.isEmpty() ? userName
  668. : getValue(SshConstants.USER);
  669. if (u == null || u.isEmpty()) {
  670. u = localUserName;
  671. }
  672. Replacer r = new Replacer(originalHostName, p, u, localUserName,
  673. home);
  674. if (options != null) {
  675. // HOSTNAME first
  676. String hostName = options.get(SshConstants.HOST_NAME);
  677. if (hostName == null || hostName.isEmpty()) {
  678. options.put(SshConstants.HOST_NAME, originalHostName);
  679. } else {
  680. hostName = r.substitute(hostName, "h", false); //$NON-NLS-1$
  681. options.put(SshConstants.HOST_NAME, hostName);
  682. r.update('h', hostName);
  683. }
  684. }
  685. if (multiOptions != null) {
  686. List<String> values = multiOptions
  687. .get(SshConstants.IDENTITY_FILE);
  688. if (values != null) {
  689. values = substitute(values, "dhlru", r, true); //$NON-NLS-1$
  690. values = replaceTilde(values, home);
  691. multiOptions.put(SshConstants.IDENTITY_FILE, values);
  692. }
  693. values = multiOptions.get(SshConstants.CERTIFICATE_FILE);
  694. if (values != null) {
  695. values = substitute(values, "dhlru", r, true); //$NON-NLS-1$
  696. values = replaceTilde(values, home);
  697. multiOptions.put(SshConstants.CERTIFICATE_FILE, values);
  698. }
  699. }
  700. if (listOptions != null) {
  701. List<String> values = listOptions
  702. .get(SshConstants.USER_KNOWN_HOSTS_FILE);
  703. if (values != null) {
  704. values = replaceTilde(values, home);
  705. listOptions.put(SshConstants.USER_KNOWN_HOSTS_FILE, values);
  706. }
  707. }
  708. if (options != null) {
  709. // HOSTNAME already done above
  710. String value = options.get(SshConstants.IDENTITY_AGENT);
  711. if (value != null) {
  712. value = r.substitute(value, "dhlru", true); //$NON-NLS-1$
  713. value = toFile(value, home).getPath();
  714. options.put(SshConstants.IDENTITY_AGENT, value);
  715. }
  716. value = options.get(SshConstants.CONTROL_PATH);
  717. if (value != null) {
  718. value = r.substitute(value, "ChLlnpru", true); //$NON-NLS-1$
  719. value = toFile(value, home).getPath();
  720. options.put(SshConstants.CONTROL_PATH, value);
  721. }
  722. value = options.get(SshConstants.LOCAL_COMMAND);
  723. if (value != null) {
  724. value = r.substitute(value, "CdhlnprTu", false); //$NON-NLS-1$
  725. options.put(SshConstants.LOCAL_COMMAND, value);
  726. }
  727. value = options.get(SshConstants.REMOTE_COMMAND);
  728. if (value != null) {
  729. value = r.substitute(value, "Cdhlnpru", false); //$NON-NLS-1$
  730. options.put(SshConstants.REMOTE_COMMAND, value);
  731. }
  732. value = options.get(SshConstants.PROXY_COMMAND);
  733. if (value != null) {
  734. value = r.substitute(value, "hpr", false); //$NON-NLS-1$
  735. options.put(SshConstants.PROXY_COMMAND, value);
  736. }
  737. }
  738. // Match is not implemented and would need to be done elsewhere
  739. // anyway.
  740. }
  741. /**
  742. * Retrieves an unmodifiable map of all single-valued options, with
  743. * case-insensitive lookup by keys.
  744. *
  745. * @return all single-valued options
  746. */
  747. @Override
  748. @NonNull
  749. public Map<String, String> getOptions() {
  750. if (options == null) {
  751. return Collections.emptyMap();
  752. }
  753. return Collections.unmodifiableMap(options);
  754. }
  755. /**
  756. * Retrieves an unmodifiable map of all multi-valued options, with
  757. * case-insensitive lookup by keys.
  758. *
  759. * @return all multi-valued options
  760. */
  761. @Override
  762. @NonNull
  763. public Map<String, List<String>> getMultiValuedOptions() {
  764. if (listOptions == null && multiOptions == null) {
  765. return Collections.emptyMap();
  766. }
  767. Map<String, List<String>> allValues = new TreeMap<>(
  768. String.CASE_INSENSITIVE_ORDER);
  769. if (multiOptions != null) {
  770. allValues.putAll(multiOptions);
  771. }
  772. if (listOptions != null) {
  773. allValues.putAll(listOptions);
  774. }
  775. return Collections.unmodifiableMap(allValues);
  776. }
  777. @Override
  778. @SuppressWarnings("nls")
  779. public String toString() {
  780. return "HostEntry [options=" + options + ", multiOptions="
  781. + multiOptions + ", listOptions=" + listOptions + "]";
  782. }
  783. }
  784. private static class Replacer {
  785. private final Map<Character, String> replacements = new HashMap<>();
  786. public Replacer(String host, int port, String user,
  787. String localUserName, File home) {
  788. replacements.put(Character.valueOf('%'), "%"); //$NON-NLS-1$
  789. replacements.put(Character.valueOf('d'), home.getPath());
  790. replacements.put(Character.valueOf('h'), host);
  791. String localhost = SystemReader.getInstance().getHostname();
  792. replacements.put(Character.valueOf('l'), localhost);
  793. int period = localhost.indexOf('.');
  794. if (period > 0) {
  795. localhost = localhost.substring(0, period);
  796. }
  797. replacements.put(Character.valueOf('L'), localhost);
  798. replacements.put(Character.valueOf('n'), host);
  799. replacements.put(Character.valueOf('p'), Integer.toString(port));
  800. replacements.put(Character.valueOf('r'), user == null ? "" : user); //$NON-NLS-1$
  801. replacements.put(Character.valueOf('u'), localUserName);
  802. replacements.put(Character.valueOf('C'),
  803. substitute("%l%h%p%r", "hlpr", false)); //$NON-NLS-1$ //$NON-NLS-2$
  804. replacements.put(Character.valueOf('T'), "NONE"); //$NON-NLS-1$
  805. }
  806. public void update(char key, String value) {
  807. replacements.put(Character.valueOf(key), value);
  808. if ("lhpr".indexOf(key) >= 0) { //$NON-NLS-1$
  809. replacements.put(Character.valueOf('C'),
  810. substitute("%l%h%p%r", "hlpr", false)); //$NON-NLS-1$ //$NON-NLS-2$
  811. }
  812. }
  813. public String substitute(String input, String allowed,
  814. boolean withEnv) {
  815. if (input == null || input.length() <= 1
  816. || input.indexOf('%') < 0
  817. && (!withEnv || input.indexOf("${") < 0)) { //$NON-NLS-1$
  818. return input;
  819. }
  820. StringBuilder builder = new StringBuilder();
  821. int start = 0;
  822. int length = input.length();
  823. while (start < length) {
  824. char ch = input.charAt(start);
  825. switch (ch) {
  826. case '%':
  827. if (start + 1 >= length) {
  828. break;
  829. }
  830. String replacement = null;
  831. ch = input.charAt(start + 1);
  832. if (ch == '%' || allowed.indexOf(ch) >= 0) {
  833. replacement = replacements.get(Character.valueOf(ch));
  834. }
  835. if (replacement == null) {
  836. builder.append('%').append(ch);
  837. } else {
  838. builder.append(replacement);
  839. }
  840. start += 2;
  841. continue;
  842. case '$':
  843. if (!withEnv || start + 2 >= length) {
  844. break;
  845. }
  846. ch = input.charAt(start + 1);
  847. if (ch == '{') {
  848. int close = input.indexOf('}', start + 2);
  849. if (close > start + 2) {
  850. String variable = SystemReader.getInstance()
  851. .getenv(input.substring(start + 2, close));
  852. if (!StringUtils.isEmptyOrNull(variable)) {
  853. builder.append(variable);
  854. }
  855. start = close + 1;
  856. continue;
  857. }
  858. }
  859. ch = '$';
  860. break;
  861. default:
  862. break;
  863. }
  864. builder.append(ch);
  865. start++;
  866. }
  867. return builder.toString();
  868. }
  869. }
  870. /** {@inheritDoc} */
  871. @Override
  872. @SuppressWarnings("nls")
  873. public String toString() {
  874. return "OpenSshConfig [home=" + home + ", configFile=" + configFile
  875. + ", lastModified=" + lastModified + ", state=" + state + "]";
  876. }
  877. }