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.file.FileAlreadyExistsException;
  19. import java.nio.file.FileStore;
  20. import java.nio.file.FileSystemException;
  21. import java.nio.file.Files;
  22. import java.nio.file.InvalidPathException;
  23. import java.nio.file.Path;
  24. import java.nio.file.Paths;
  25. import java.nio.file.attribute.PosixFilePermission;
  26. import java.text.MessageFormat;
  27. import java.util.ArrayList;
  28. import java.util.Arrays;
  29. import java.util.List;
  30. import java.util.Map;
  31. import java.util.Optional;
  32. import java.util.Set;
  33. import java.util.UUID;
  34. import java.util.concurrent.ConcurrentHashMap;

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

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

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

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

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

  55.     private volatile AtomicFileCreation supportsAtomicFileCreation = AtomicFileCreation.UNDEFINED;

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

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

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

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

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

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

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

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

  125.         if (SystemReader.getInstance().isMacOS()) {
  126.             if (gitExe == null
  127.                     || DEFAULT_GIT_LOCATION.equals(gitExe.getPath())) {
  128.                 if (searchPath(path, "bash") != null) { //$NON-NLS-1$
  129.                     // On MacOSX, PATH is shorter when Eclipse is launched from the
  130.                     // Finder than from a terminal. Therefore try to launch bash as a
  131.                     // login shell and search using that.
  132.                     try {
  133.                         String w = readPipe(userHome(),
  134.                             new String[]{"bash", "--login", "-c", "which git"}, // //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  135.                                 SystemReader.getInstance().getDefaultCharset()
  136.                                         .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.                             SystemReader.getInstance().getDefaultCharset()
  155.                                     .name());
  156.                     if (StringUtils.isEmptyOrNull(w)) {
  157.                         gitExe = null;
  158.                     } else {
  159.                         File realGitExe = new File(new File(w),
  160.                                 DEFAULT_GIT_LOCATION.substring(1));
  161.                         if (!realGitExe.exists()) {
  162.                             gitExe = null;
  163.                         }
  164.                     }
  165.                 } catch (CommandFailedException e) {
  166.                     gitExe = null;
  167.                 }
  168.             }
  169.         }

  170.         return gitExe;
  171.     }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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