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.

FS_POSIX.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*
  2. * Copyright (C) 2010, Robin Rosenberg
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.util;
  44. import java.io.BufferedReader;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.io.InputStreamReader;
  48. import java.io.PrintStream;
  49. import java.nio.charset.Charset;
  50. import java.nio.file.AccessDeniedException;
  51. import java.nio.file.Files;
  52. import java.nio.file.Path;
  53. import java.nio.file.Paths;
  54. import java.nio.file.attribute.PosixFilePermission;
  55. import java.text.MessageFormat;
  56. import java.util.ArrayList;
  57. import java.util.Arrays;
  58. import java.util.List;
  59. import java.util.Optional;
  60. import java.util.Set;
  61. import java.util.UUID;
  62. import org.eclipse.jgit.annotations.Nullable;
  63. import org.eclipse.jgit.api.errors.JGitInternalException;
  64. import org.eclipse.jgit.errors.CommandFailedException;
  65. import org.eclipse.jgit.errors.ConfigInvalidException;
  66. import org.eclipse.jgit.internal.JGitText;
  67. import org.eclipse.jgit.lib.ConfigConstants;
  68. import org.eclipse.jgit.lib.Constants;
  69. import org.eclipse.jgit.lib.Repository;
  70. import org.eclipse.jgit.storage.file.FileBasedConfig;
  71. import org.slf4j.Logger;
  72. import org.slf4j.LoggerFactory;
  73. /**
  74. * Base FS for POSIX based systems
  75. *
  76. * @since 3.0
  77. */
  78. public class FS_POSIX extends FS {
  79. private final static Logger LOG = LoggerFactory.getLogger(FS_POSIX.class);
  80. private static final int DEFAULT_UMASK = 0022;
  81. private volatile int umask = -1;
  82. private volatile boolean supportsUnixNLink = true;
  83. private volatile AtomicFileCreation supportsAtomicCreateNewFile = AtomicFileCreation.UNDEFINED;
  84. private enum AtomicFileCreation {
  85. SUPPORTED, NOT_SUPPORTED, UNDEFINED
  86. }
  87. /**
  88. * Default constructor.
  89. */
  90. protected FS_POSIX() {
  91. }
  92. /**
  93. * Constructor
  94. *
  95. * @param src
  96. * FS to copy some settings from
  97. */
  98. protected FS_POSIX(FS src) {
  99. super(src);
  100. if (src instanceof FS_POSIX) {
  101. umask = ((FS_POSIX) src).umask;
  102. }
  103. }
  104. private void determineAtomicFileCreationSupport() {
  105. // @TODO: enhance SystemReader to support this without copying code
  106. AtomicFileCreation ret = getAtomicFileCreationSupportOption(
  107. SystemReader.getInstance().openUserConfig(null, this));
  108. if (ret == AtomicFileCreation.UNDEFINED
  109. && StringUtils.isEmptyOrNull(SystemReader.getInstance()
  110. .getenv(Constants.GIT_CONFIG_NOSYSTEM_KEY))) {
  111. ret = getAtomicFileCreationSupportOption(
  112. SystemReader.getInstance().openSystemConfig(null, this));
  113. }
  114. supportsAtomicCreateNewFile = ret;
  115. }
  116. private AtomicFileCreation getAtomicFileCreationSupportOption(
  117. FileBasedConfig config) {
  118. try {
  119. config.load();
  120. String value = config.getString(ConfigConstants.CONFIG_CORE_SECTION,
  121. null,
  122. ConfigConstants.CONFIG_KEY_SUPPORTSATOMICFILECREATION);
  123. if (value == null) {
  124. return AtomicFileCreation.UNDEFINED;
  125. }
  126. return StringUtils.toBoolean(value)
  127. ? AtomicFileCreation.SUPPORTED
  128. : AtomicFileCreation.NOT_SUPPORTED;
  129. } catch (IOException | ConfigInvalidException e) {
  130. return AtomicFileCreation.SUPPORTED;
  131. }
  132. }
  133. /** {@inheritDoc} */
  134. @Override
  135. public FS newInstance() {
  136. return new FS_POSIX(this);
  137. }
  138. /**
  139. * Set the umask, overriding any value observed from the shell.
  140. *
  141. * @param umask
  142. * mask to apply when creating files.
  143. * @since 4.0
  144. */
  145. public void setUmask(int umask) {
  146. this.umask = umask;
  147. }
  148. private int umask() {
  149. int u = umask;
  150. if (u == -1) {
  151. u = readUmask();
  152. umask = u;
  153. }
  154. return u;
  155. }
  156. /** @return mask returned from running {@code umask} command in shell. */
  157. private static int readUmask() {
  158. try {
  159. Process p = Runtime.getRuntime().exec(
  160. new String[] { "sh", "-c", "umask" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  161. null, null);
  162. try (BufferedReader lineRead = new BufferedReader(
  163. new InputStreamReader(p.getInputStream(), Charset
  164. .defaultCharset().name()))) {
  165. if (p.waitFor() == 0) {
  166. String s = lineRead.readLine();
  167. if (s != null && s.matches("0?\\d{3}")) { //$NON-NLS-1$
  168. return Integer.parseInt(s, 8);
  169. }
  170. }
  171. return DEFAULT_UMASK;
  172. }
  173. } catch (Exception e) {
  174. return DEFAULT_UMASK;
  175. }
  176. }
  177. /** {@inheritDoc} */
  178. @Override
  179. protected File discoverGitExe() {
  180. String path = SystemReader.getInstance().getenv("PATH"); //$NON-NLS-1$
  181. File gitExe = searchPath(path, "git"); //$NON-NLS-1$
  182. if (gitExe == null) {
  183. if (SystemReader.getInstance().isMacOS()) {
  184. if (searchPath(path, "bash") != null) { //$NON-NLS-1$
  185. // On MacOSX, PATH is shorter when Eclipse is launched from the
  186. // Finder than from a terminal. Therefore try to launch bash as a
  187. // login shell and search using that.
  188. String w;
  189. try {
  190. w = readPipe(userHome(),
  191. new String[]{"bash", "--login", "-c", "which git"}, // //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  192. Charset.defaultCharset().name());
  193. } catch (CommandFailedException e) {
  194. LOG.warn(e.getMessage());
  195. return null;
  196. }
  197. if (!StringUtils.isEmptyOrNull(w)) {
  198. gitExe = new File(w);
  199. }
  200. }
  201. }
  202. }
  203. return gitExe;
  204. }
  205. /** {@inheritDoc} */
  206. @Override
  207. public boolean isCaseSensitive() {
  208. return !SystemReader.getInstance().isMacOS();
  209. }
  210. /** {@inheritDoc} */
  211. @Override
  212. public boolean supportsExecute() {
  213. return true;
  214. }
  215. /** {@inheritDoc} */
  216. @Override
  217. public boolean canExecute(File f) {
  218. return FileUtils.canExecute(f);
  219. }
  220. /** {@inheritDoc} */
  221. @Override
  222. public boolean setExecute(File f, boolean canExecute) {
  223. if (!isFile(f))
  224. return false;
  225. if (!canExecute)
  226. return f.setExecutable(false, false);
  227. try {
  228. Path path = FileUtils.toPath(f);
  229. Set<PosixFilePermission> pset = Files.getPosixFilePermissions(path);
  230. // owner (user) is always allowed to execute.
  231. pset.add(PosixFilePermission.OWNER_EXECUTE);
  232. int mask = umask();
  233. apply(pset, mask, PosixFilePermission.GROUP_EXECUTE, 1 << 3);
  234. apply(pset, mask, PosixFilePermission.OTHERS_EXECUTE, 1);
  235. Files.setPosixFilePermissions(path, pset);
  236. return true;
  237. } catch (IOException e) {
  238. // The interface doesn't allow to throw IOException
  239. final boolean debug = Boolean.parseBoolean(SystemReader
  240. .getInstance().getProperty("jgit.fs.debug")); //$NON-NLS-1$
  241. if (debug)
  242. System.err.println(e);
  243. return false;
  244. }
  245. }
  246. private static void apply(Set<PosixFilePermission> set,
  247. int umask, PosixFilePermission perm, int test) {
  248. if ((umask & test) == 0) {
  249. // If bit is clear in umask, permission is allowed.
  250. set.add(perm);
  251. } else {
  252. // If bit is set in umask, permission is denied.
  253. set.remove(perm);
  254. }
  255. }
  256. /** {@inheritDoc} */
  257. @Override
  258. public ProcessBuilder runInShell(String cmd, String[] args) {
  259. List<String> argv = new ArrayList<>(4 + args.length);
  260. argv.add("sh"); //$NON-NLS-1$
  261. argv.add("-c"); //$NON-NLS-1$
  262. argv.add(cmd + " \"$@\""); //$NON-NLS-1$
  263. argv.add(cmd);
  264. argv.addAll(Arrays.asList(args));
  265. ProcessBuilder proc = new ProcessBuilder();
  266. proc.command(argv);
  267. return proc;
  268. }
  269. /** {@inheritDoc} */
  270. @Override
  271. public ProcessResult runHookIfPresent(Repository repository, String hookName,
  272. String[] args, PrintStream outRedirect, PrintStream errRedirect,
  273. String stdinArgs) throws JGitInternalException {
  274. return internalRunHookIfPresent(repository, hookName, args, outRedirect,
  275. errRedirect, stdinArgs);
  276. }
  277. /** {@inheritDoc} */
  278. @Override
  279. public boolean retryFailedLockFileCommit() {
  280. return false;
  281. }
  282. /** {@inheritDoc} */
  283. @Override
  284. public boolean supportsSymlinks() {
  285. return true;
  286. }
  287. /** {@inheritDoc} */
  288. @Override
  289. public void setHidden(File path, boolean hidden) throws IOException {
  290. // no action on POSIX
  291. }
  292. /** {@inheritDoc} */
  293. @Override
  294. public Attributes getAttributes(File path) {
  295. return FileUtils.getFileAttributesPosix(this, path);
  296. }
  297. /** {@inheritDoc} */
  298. @Override
  299. public File normalize(File file) {
  300. return FileUtils.normalize(file);
  301. }
  302. /** {@inheritDoc} */
  303. @Override
  304. public String normalize(String name) {
  305. return FileUtils.normalize(name);
  306. }
  307. /** {@inheritDoc} */
  308. @Override
  309. public File findHook(Repository repository, String hookName) {
  310. final File gitdir = repository.getDirectory();
  311. if (gitdir == null) {
  312. return null;
  313. }
  314. final Path hookPath = gitdir.toPath().resolve(Constants.HOOKS)
  315. .resolve(hookName);
  316. if (Files.isExecutable(hookPath))
  317. return hookPath.toFile();
  318. return null;
  319. }
  320. /** {@inheritDoc} */
  321. @Override
  322. public boolean supportsAtomicCreateNewFile() {
  323. if (supportsAtomicCreateNewFile == AtomicFileCreation.UNDEFINED) {
  324. determineAtomicFileCreationSupport();
  325. }
  326. return supportsAtomicCreateNewFile == AtomicFileCreation.SUPPORTED;
  327. }
  328. @Override
  329. @SuppressWarnings("boxing")
  330. /**
  331. * {@inheritDoc}
  332. * <p>
  333. * An implementation of the File#createNewFile() semantics which works also
  334. * on NFS. If the config option
  335. * {@code core.supportsAtomicCreateNewFile = true} (which is the default)
  336. * then simply File#createNewFile() is called.
  337. *
  338. * But if {@code core.supportsAtomicCreateNewFile = false} then after
  339. * successful creation of the lock file a hard link to that lock file is
  340. * created and the attribute nlink of the lock file is checked to be 2. If
  341. * multiple clients manage to create the same lock file nlink would be
  342. * greater than 2 showing the error.
  343. *
  344. * @see "https://www.time-travellers.org/shane/papers/NFS_considered_harmful.html"
  345. *
  346. * @deprecated use {@link FS_POSIX#createNewFileAtomic(File)} instead
  347. * @since 4.5
  348. */
  349. @Deprecated
  350. public boolean createNewFile(File lock) throws IOException {
  351. if (!lock.createNewFile()) {
  352. return false;
  353. }
  354. if (supportsAtomicCreateNewFile() || !supportsUnixNLink) {
  355. return true;
  356. }
  357. Path lockPath = lock.toPath();
  358. Path link = null;
  359. try {
  360. link = Files.createLink(
  361. Paths.get(lock.getAbsolutePath() + ".lnk"), //$NON-NLS-1$
  362. lockPath);
  363. Integer nlink = (Integer) (Files.getAttribute(lockPath,
  364. "unix:nlink")); //$NON-NLS-1$
  365. if (nlink > 2) {
  366. LOG.warn(MessageFormat.format(
  367. JGitText.get().failedAtomicFileCreation, lockPath,
  368. nlink));
  369. return false;
  370. } else if (nlink < 2) {
  371. supportsUnixNLink = false;
  372. }
  373. return true;
  374. } catch (UnsupportedOperationException | IllegalArgumentException e) {
  375. supportsUnixNLink = false;
  376. return true;
  377. } finally {
  378. if (link != null) {
  379. Files.delete(link);
  380. }
  381. }
  382. }
  383. /**
  384. * {@inheritDoc}
  385. * <p>
  386. * An implementation of the File#createNewFile() semantics which can create
  387. * a unique file atomically also on NFS. If the config option
  388. * {@code core.supportsAtomicCreateNewFile = true} (which is the default)
  389. * then simply File#createNewFile() is called.
  390. *
  391. * But if {@code core.supportsAtomicCreateNewFile = false} then after
  392. * successful creation of the lock file a hard link to that lock file is
  393. * created and the attribute nlink of the lock file is checked to be 2. If
  394. * multiple clients manage to create the same lock file nlink would be
  395. * greater than 2 showing the error. The hard link needs to be retained
  396. * until the corresponding file is no longer needed in order to prevent that
  397. * another process can create the same file concurrently using another NFS
  398. * client which might not yet see the file due to caching.
  399. *
  400. * @see "https://www.time-travellers.org/shane/papers/NFS_considered_harmful.html"
  401. * @param file
  402. * the unique file to be created atomically
  403. * @return LockToken this lock token must be held until the file is no
  404. * longer needed
  405. * @throws IOException
  406. * @since 5.0
  407. */
  408. @Override
  409. public LockToken createNewFileAtomic(File file) throws IOException {
  410. if (!file.createNewFile()) {
  411. return token(false, null);
  412. }
  413. if (supportsAtomicCreateNewFile() || !supportsUnixNLink) {
  414. return token(true, null);
  415. }
  416. Path link = null;
  417. Path path = file.toPath();
  418. try {
  419. link = Files.createLink(Paths.get(uniqueLinkPath(file)), path);
  420. Integer nlink = (Integer) (Files.getAttribute(path,
  421. "unix:nlink")); //$NON-NLS-1$
  422. if (nlink.intValue() > 2) {
  423. LOG.warn(MessageFormat.format(
  424. JGitText.get().failedAtomicFileCreation, path, nlink));
  425. return token(false, link);
  426. } else if (nlink.intValue() < 2) {
  427. supportsUnixNLink = false;
  428. }
  429. return token(true, link);
  430. } catch (UnsupportedOperationException | IllegalArgumentException
  431. | AccessDeniedException | SecurityException e) {
  432. supportsUnixNLink = false;
  433. return token(true, link);
  434. }
  435. }
  436. private static LockToken token(boolean created, @Nullable Path p) {
  437. return ((p != null) && Files.exists(p))
  438. ? new LockToken(created, Optional.of(p))
  439. : new LockToken(created, Optional.empty());
  440. }
  441. private static String uniqueLinkPath(File file) {
  442. UUID id = UUID.randomUUID();
  443. return file.getAbsolutePath() + "." //$NON-NLS-1$
  444. + Long.toHexString(id.getMostSignificantBits())
  445. + Long.toHexString(id.getLeastSignificantBits());
  446. }
  447. }