FS_POSIX.java

  1. /*
  2.  * Copyright (C) 2010, Robin Rosenberg and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */
  10. package org.eclipse.jgit.util;

  11. import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_CORE_SECTION;
  12. import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_SUPPORTSATOMICFILECREATION;

  13. import java.io.BufferedReader;
  14. import java.io.File;
  15. import java.io.IOException;
  16. import java.io.InputStreamReader;
  17. import java.io.OutputStream;
  18. import java.nio.charset.Charset;
  19. import java.nio.file.FileAlreadyExistsException;
  20. import java.nio.file.FileStore;
  21. import java.nio.file.FileSystemException;
  22. import java.nio.file.Files;
  23. import java.nio.file.InvalidPathException;
  24. import java.nio.file.Path;
  25. import java.nio.file.Paths;
  26. import java.nio.file.attribute.PosixFilePermission;
  27. import java.text.MessageFormat;
  28. import java.util.ArrayList;
  29. import java.util.Arrays;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.Optional;
  33. import java.util.Set;
  34. import java.util.UUID;
  35. import java.util.concurrent.ConcurrentHashMap;

  36. import org.eclipse.jgit.annotations.Nullable;
  37. import org.eclipse.jgit.api.errors.JGitInternalException;
  38. import org.eclipse.jgit.errors.CommandFailedException;
  39. import org.eclipse.jgit.errors.ConfigInvalidException;
  40. import org.eclipse.jgit.internal.JGitText;
  41. import org.eclipse.jgit.lib.Repository;
  42. import org.eclipse.jgit.lib.StoredConfig;
  43. import org.slf4j.Logger;
  44. import org.slf4j.LoggerFactory;

  45. /**
  46.  * Base FS for POSIX based systems
  47.  *
  48.  * @since 3.0
  49.  */
  50. public class FS_POSIX extends FS {
  51.     private static final Logger LOG = LoggerFactory.getLogger(FS_POSIX.class);

  52.     private static final String DEFAULT_GIT_LOCATION = "/usr/bin/git"; //$NON-NLS-1$

  53.     private static final int DEFAULT_UMASK = 0022;
  54.     private volatile int umask = -1;

  55.     private static final Map<FileStore, Boolean> CAN_HARD_LINK = new ConcurrentHashMap<>();

  56.     private volatile AtomicFileCreation supportsAtomicFileCreation = AtomicFileCreation.UNDEFINED;

  57.     private enum AtomicFileCreation {
  58.         SUPPORTED, NOT_SUPPORTED, UNDEFINED
  59.     }

  60.     /**
  61.      * Default constructor.
  62.      */
  63.     protected FS_POSIX() {
  64.     }

  65.     /**
  66.      * Constructor
  67.      *
  68.      * @param src
  69.      *            FS to copy some settings from
  70.      */
  71.     protected FS_POSIX(FS src) {
  72.         super(src);
  73.         if (src instanceof FS_POSIX) {
  74.             umask = ((FS_POSIX) src).umask;
  75.         }
  76.     }

  77.     /** {@inheritDoc} */
  78.     @Override
  79.     public FS newInstance() {
  80.         return new FS_POSIX(this);
  81.     }

  82.     /**
  83.      * Set the umask, overriding any value observed from the shell.
  84.      *
  85.      * @param umask
  86.      *            mask to apply when creating files.
  87.      * @since 4.0
  88.      */
  89.     public void setUmask(int umask) {
  90.         this.umask = umask;
  91.     }

  92.     private int umask() {
  93.         int u = umask;
  94.         if (u == -1) {
  95.             u = readUmask();
  96.             umask = u;
  97.         }
  98.         return u;
  99.     }

  100.     /** @return mask returned from running {@code umask} command in shell. */
  101.     private static int readUmask() {
  102.         try {
  103.             Process p = Runtime.getRuntime().exec(
  104.                     new String[] { "sh", "-c", "umask" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  105.                     null, null);
  106.             try (BufferedReader lineRead = new BufferedReader(
  107.                     new InputStreamReader(p.getInputStream(), Charset
  108.                             .defaultCharset().name()))) {
  109.                 if (p.waitFor() == 0) {
  110.                     String s = lineRead.readLine();
  111.                     if (s != null && s.matches("0?\\d{3}")) { //$NON-NLS-1$
  112.                         return Integer.parseInt(s, 8);
  113.                     }
  114.                 }
  115.                 return DEFAULT_UMASK;
  116.             }
  117.         } catch (Exception e) {
  118.             return DEFAULT_UMASK;
  119.         }
  120.     }

  121.     /** {@inheritDoc} */
  122.     @Override
  123.     protected File discoverGitExe() {
  124.         String path = SystemReader.getInstance().getenv("PATH"); //$NON-NLS-1$
  125.         File gitExe = searchPath(path, "git"); //$NON-NLS-1$

  126.         if (SystemReader.getInstance().isMacOS()) {
  127.             if (gitExe == null
  128.                     || DEFAULT_GIT_LOCATION.equals(gitExe.getPath())) {
  129.                 if (searchPath(path, "bash") != null) { //$NON-NLS-1$
  130.                     // On MacOSX, PATH is shorter when Eclipse is launched from the
  131.                     // Finder than from a terminal. Therefore try to launch bash as a
  132.                     // login shell and search using that.
  133.                     try {
  134.                         String w = readPipe(userHome(),
  135.                             new String[]{"bash", "--login", "-c", "which git"}, // //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  136.                             Charset.defaultCharset().name());
  137.                         if (!StringUtils.isEmptyOrNull(w)) {
  138.                             gitExe = new File(w);
  139.                         }
  140.                     } catch (CommandFailedException e) {
  141.                         LOG.warn(e.getMessage());
  142.                     }
  143.                 }
  144.             }
  145.             if (gitExe != null
  146.                     && DEFAULT_GIT_LOCATION.equals(gitExe.getPath())) {
  147.                 // If we still have the default git exe, it's an XCode wrapper
  148.                 // that may prompt the user to install the XCode command line
  149.                 // tools if not already present. Avoid the prompt by returning
  150.                 // null if no XCode git is there.
  151.                 try {
  152.                     String w = readPipe(userHome(),
  153.                             new String[] { "xcode-select", "-p" }, //$NON-NLS-1$ //$NON-NLS-2$
  154.                             Charset.defaultCharset().name());
  155.                     if (StringUtils.isEmptyOrNull(w)) {
  156.                         gitExe = null;
  157.                     } else {
  158.                         File realGitExe = new File(new File(w),
  159.                                 DEFAULT_GIT_LOCATION.substring(1));
  160.                         if (!realGitExe.exists()) {
  161.                             gitExe = null;
  162.                         }
  163.                     }
  164.                 } catch (CommandFailedException e) {
  165.                     gitExe = null;
  166.                 }
  167.             }
  168.         }

  169.         return gitExe;
  170.     }

  171.     /** {@inheritDoc} */
  172.     @Override
  173.     public boolean isCaseSensitive() {
  174.         return !SystemReader.getInstance().isMacOS();
  175.     }

  176.     /** {@inheritDoc} */
  177.     @Override
  178.     public boolean supportsExecute() {
  179.         return true;
  180.     }

  181.     /** {@inheritDoc} */
  182.     @Override
  183.     public boolean canExecute(File f) {
  184.         return FileUtils.canExecute(f);
  185.     }

  186.     /** {@inheritDoc} */
  187.     @Override
  188.     public boolean setExecute(File f, boolean canExecute) {
  189.         if (!isFile(f))
  190.             return false;
  191.         if (!canExecute)
  192.             return f.setExecutable(false, false);

  193.         try {
  194.             Path path = FileUtils.toPath(f);
  195.             Set<PosixFilePermission> pset = Files.getPosixFilePermissions(path);

  196.             // owner (user) is always allowed to execute.
  197.             pset.add(PosixFilePermission.OWNER_EXECUTE);

  198.             int mask = umask();
  199.             apply(pset, mask, PosixFilePermission.GROUP_EXECUTE, 1 << 3);
  200.             apply(pset, mask, PosixFilePermission.OTHERS_EXECUTE, 1);
  201.             Files.setPosixFilePermissions(path, pset);
  202.             return true;
  203.         } catch (IOException e) {
  204.             // The interface doesn't allow to throw IOException
  205.             final boolean debug = Boolean.parseBoolean(SystemReader
  206.                     .getInstance().getProperty("jgit.fs.debug")); //$NON-NLS-1$
  207.             if (debug)
  208.                 System.err.println(e);
  209.             return false;
  210.         }
  211.     }

  212.     private static void apply(Set<PosixFilePermission> set,
  213.             int umask, PosixFilePermission perm, int test) {
  214.         if ((umask & test) == 0) {
  215.             // If bit is clear in umask, permission is allowed.
  216.             set.add(perm);
  217.         } else {
  218.             // If bit is set in umask, permission is denied.
  219.             set.remove(perm);
  220.         }
  221.     }

  222.     /** {@inheritDoc} */
  223.     @Override
  224.     public ProcessBuilder runInShell(String cmd, String[] args) {
  225.         List<String> argv = new ArrayList<>(4 + args.length);
  226.         argv.add("sh"); //$NON-NLS-1$
  227.         argv.add("-c"); //$NON-NLS-1$
  228.         argv.add(cmd + " \"$@\""); //$NON-NLS-1$
  229.         argv.add(cmd);
  230.         argv.addAll(Arrays.asList(args));
  231.         ProcessBuilder proc = new ProcessBuilder();
  232.         proc.command(argv);
  233.         return proc;
  234.     }

  235.     @Override
  236.     String shellQuote(String cmd) {
  237.         return QuotedString.BOURNE.quote(cmd);
  238.     }

  239.     /** {@inheritDoc} */
  240.     @Override
  241.     public ProcessResult runHookIfPresent(Repository repository, String hookName,
  242.             String[] args, OutputStream outRedirect, OutputStream errRedirect,
  243.             String stdinArgs) throws JGitInternalException {
  244.         return internalRunHookIfPresent(repository, hookName, args, outRedirect,
  245.                 errRedirect, stdinArgs);
  246.     }

  247.     /** {@inheritDoc} */
  248.     @Override
  249.     public boolean retryFailedLockFileCommit() {
  250.         return false;
  251.     }

  252.     /** {@inheritDoc} */
  253.     @Override
  254.     public void setHidden(File path, boolean hidden) throws IOException {
  255.         // no action on POSIX
  256.     }

  257.     /** {@inheritDoc} */
  258.     @Override
  259.     public Attributes getAttributes(File path) {
  260.         return FileUtils.getFileAttributesPosix(this, path);
  261.     }

  262.     /** {@inheritDoc} */
  263.     @Override
  264.     public File normalize(File file) {
  265.         return FileUtils.normalize(file);
  266.     }

  267.     /** {@inheritDoc} */
  268.     @Override
  269.     public String normalize(String name) {
  270.         return FileUtils.normalize(name);
  271.     }

  272.     /** {@inheritDoc} */
  273.     @Override
  274.     public boolean supportsAtomicCreateNewFile() {
  275.         if (supportsAtomicFileCreation == AtomicFileCreation.UNDEFINED) {
  276.             try {
  277.                 StoredConfig config = SystemReader.getInstance().getUserConfig();
  278.                 String value = config.getString(CONFIG_CORE_SECTION, null,
  279.                         CONFIG_KEY_SUPPORTSATOMICFILECREATION);
  280.                 if (value != null) {
  281.                     supportsAtomicFileCreation = StringUtils.toBoolean(value)
  282.                             ? AtomicFileCreation.SUPPORTED
  283.                             : AtomicFileCreation.NOT_SUPPORTED;
  284.                 } else {
  285.                     supportsAtomicFileCreation = AtomicFileCreation.SUPPORTED;
  286.                 }
  287.             } catch (IOException | ConfigInvalidException e) {
  288.                 LOG.warn(JGitText.get().assumeAtomicCreateNewFile, e);
  289.                 supportsAtomicFileCreation = AtomicFileCreation.SUPPORTED;
  290.             }
  291.         }
  292.         return supportsAtomicFileCreation == AtomicFileCreation.SUPPORTED;
  293.     }

  294.     @Override
  295.     @SuppressWarnings("boxing")
  296.     /**
  297.      * {@inheritDoc}
  298.      * <p>
  299.      * An implementation of the File#createNewFile() semantics which works also
  300.      * on NFS. If the config option
  301.      * {@code core.supportsAtomicCreateNewFile = true} (which is the default)
  302.      * then simply File#createNewFile() is called.
  303.      *
  304.      * But if {@code core.supportsAtomicCreateNewFile = false} then after
  305.      * successful creation of the lock file a hard link to that lock file is
  306.      * created and the attribute nlink of the lock file is checked to be 2. If
  307.      * multiple clients manage to create the same lock file nlink would be
  308.      * greater than 2 showing the error.
  309.      *
  310.      * @see "https://www.time-travellers.org/shane/papers/NFS_considered_harmful.html"
  311.      *
  312.      * @deprecated use {@link FS_POSIX#createNewFileAtomic(File)} instead
  313.      * @since 4.5
  314.      */
  315.     @Deprecated
  316.     public boolean createNewFile(File lock) throws IOException {
  317.         if (!lock.createNewFile()) {
  318.             return false;
  319.         }
  320.         if (supportsAtomicCreateNewFile()) {
  321.             return true;
  322.         }
  323.         Path lockPath = lock.toPath();
  324.         Path link = null;
  325.         FileStore store = null;
  326.         try {
  327.             store = Files.getFileStore(lockPath);
  328.         } catch (SecurityException e) {
  329.             return true;
  330.         }
  331.         try {
  332.             Boolean canLink = CAN_HARD_LINK.computeIfAbsent(store,
  333.                     s -> Boolean.TRUE);
  334.             if (Boolean.FALSE.equals(canLink)) {
  335.                 return true;
  336.             }
  337.             link = Files.createLink(
  338.                     Paths.get(lock.getAbsolutePath() + ".lnk"), //$NON-NLS-1$
  339.                     lockPath);
  340.             Integer nlink = (Integer) (Files.getAttribute(lockPath,
  341.                     "unix:nlink")); //$NON-NLS-1$
  342.             if (nlink > 2) {
  343.                 LOG.warn(MessageFormat.format(
  344.                         JGitText.get().failedAtomicFileCreation, lockPath,
  345.                         nlink));
  346.                 return false;
  347.             } else if (nlink < 2) {
  348.                 CAN_HARD_LINK.put(store, Boolean.FALSE);
  349.             }
  350.             return true;
  351.         } catch (UnsupportedOperationException | IllegalArgumentException e) {
  352.             CAN_HARD_LINK.put(store, Boolean.FALSE);
  353.             return true;
  354.         } finally {
  355.             if (link != null) {
  356.                 Files.delete(link);
  357.             }
  358.         }
  359.     }

  360.     /**
  361.      * {@inheritDoc}
  362.      * <p>
  363.      * An implementation of the File#createNewFile() semantics which can create
  364.      * a unique file atomically also on NFS. If the config option
  365.      * {@code core.supportsAtomicCreateNewFile = true} (which is the default)
  366.      * then simply Files#createFile() is called.
  367.      *
  368.      * But if {@code core.supportsAtomicCreateNewFile = false} then after
  369.      * successful creation of the lock file a hard link to that lock file is
  370.      * created and the attribute nlink of the lock file is checked to be 2. If
  371.      * multiple clients manage to create the same lock file nlink would be
  372.      * greater than 2 showing the error. The hard link needs to be retained
  373.      * until the corresponding file is no longer needed in order to prevent that
  374.      * another process can create the same file concurrently using another NFS
  375.      * client which might not yet see the file due to caching.
  376.      *
  377.      * @see "https://www.time-travellers.org/shane/papers/NFS_considered_harmful.html"
  378.      * @param file
  379.      *            the unique file to be created atomically
  380.      * @return LockToken this lock token must be held until the file is no
  381.      *         longer needed
  382.      * @throws IOException
  383.      * @since 5.0
  384.      */
  385.     @Override
  386.     public LockToken createNewFileAtomic(File file) throws IOException {
  387.         Path path;
  388.         try {
  389.             path = file.toPath();
  390.             Files.createFile(path);
  391.         } catch (FileAlreadyExistsException | InvalidPathException e) {
  392.             return token(false, null);
  393.         }
  394.         if (supportsAtomicCreateNewFile()) {
  395.             return token(true, null);
  396.         }
  397.         Path link = null;
  398.         FileStore store = null;
  399.         try {
  400.             store = Files.getFileStore(path);
  401.         } catch (SecurityException e) {
  402.             return token(true, null);
  403.         }
  404.         try {
  405.             Boolean canLink = CAN_HARD_LINK.computeIfAbsent(store,
  406.                     s -> Boolean.TRUE);
  407.             if (Boolean.FALSE.equals(canLink)) {
  408.                 return token(true, null);
  409.             }
  410.             link = Files.createLink(Paths.get(uniqueLinkPath(file)), path);
  411.             Integer nlink = (Integer) (Files.getAttribute(path,
  412.                     "unix:nlink")); //$NON-NLS-1$
  413.             if (nlink.intValue() > 2) {
  414.                 LOG.warn(MessageFormat.format(
  415.                         JGitText.get().failedAtomicFileCreation, path, nlink));
  416.                 return token(false, link);
  417.             } else if (nlink.intValue() < 2) {
  418.                 CAN_HARD_LINK.put(store, Boolean.FALSE);
  419.             }
  420.             return token(true, link);
  421.         } catch (UnsupportedOperationException | IllegalArgumentException
  422.                 | FileSystemException | SecurityException e) {
  423.             CAN_HARD_LINK.put(store, Boolean.FALSE);
  424.             return token(true, link);
  425.         }
  426.     }

  427.     private static LockToken token(boolean created, @Nullable Path p) {
  428.         return ((p != null) && Files.exists(p))
  429.                 ? new LockToken(created, Optional.of(p))
  430.                 : new LockToken(created, Optional.empty());
  431.     }

  432.     private static String uniqueLinkPath(File file) {
  433.         UUID id = UUID.randomUUID();
  434.         return file.getAbsolutePath() + "." //$NON-NLS-1$
  435.                 + Long.toHexString(id.getMostSignificantBits())
  436.                 + Long.toHexString(id.getLeastSignificantBits());
  437.     }
  438. }