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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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.Files;
  51. import java.nio.file.Path;
  52. import java.nio.file.Paths;
  53. import java.nio.file.attribute.PosixFilePermission;
  54. import java.util.ArrayList;
  55. import java.util.Arrays;
  56. import java.util.List;
  57. import java.util.Set;
  58. import org.eclipse.jgit.api.errors.JGitInternalException;
  59. import org.eclipse.jgit.errors.CommandFailedException;
  60. import org.eclipse.jgit.errors.ConfigInvalidException;
  61. import org.eclipse.jgit.lib.ConfigConstants;
  62. import org.eclipse.jgit.lib.Constants;
  63. import org.eclipse.jgit.lib.Repository;
  64. import org.eclipse.jgit.storage.file.FileBasedConfig;
  65. import org.slf4j.Logger;
  66. import org.slf4j.LoggerFactory;
  67. /**
  68. * Base FS for POSIX based systems
  69. *
  70. * @since 3.0
  71. */
  72. public class FS_POSIX extends FS {
  73. private final static Logger LOG = LoggerFactory.getLogger(FS_POSIX.class);
  74. private static final int DEFAULT_UMASK = 0022;
  75. private volatile int umask = -1;
  76. private volatile boolean supportsUnixNLink = true;
  77. private volatile AtomicFileCreation supportsAtomicCreateNewFile = AtomicFileCreation.UNDEFINED;
  78. private enum AtomicFileCreation {
  79. SUPPORTED, NOT_SUPPORTED, UNDEFINED
  80. }
  81. /**
  82. * Default constructor.
  83. */
  84. protected FS_POSIX() {
  85. }
  86. /**
  87. * Constructor
  88. *
  89. * @param src
  90. * FS to copy some settings from
  91. */
  92. protected FS_POSIX(FS src) {
  93. super(src);
  94. if (src instanceof FS_POSIX) {
  95. umask = ((FS_POSIX) src).umask;
  96. }
  97. }
  98. private void determineAtomicFileCreationSupport() {
  99. // @TODO: enhance SystemReader to support this without copying code
  100. AtomicFileCreation ret = getAtomicFileCreationSupportOption(
  101. SystemReader.getInstance().openUserConfig(null, this));
  102. if (ret == AtomicFileCreation.UNDEFINED
  103. && StringUtils.isEmptyOrNull(SystemReader.getInstance()
  104. .getenv(Constants.GIT_CONFIG_NOSYSTEM_KEY))) {
  105. ret = getAtomicFileCreationSupportOption(
  106. SystemReader.getInstance().openSystemConfig(null, this));
  107. }
  108. supportsAtomicCreateNewFile = ret;
  109. }
  110. private AtomicFileCreation getAtomicFileCreationSupportOption(
  111. FileBasedConfig config) {
  112. try {
  113. config.load();
  114. String value = config.getString(ConfigConstants.CONFIG_CORE_SECTION,
  115. null,
  116. ConfigConstants.CONFIG_KEY_SUPPORTSATOMICFILECREATION);
  117. if (value == null) {
  118. return AtomicFileCreation.UNDEFINED;
  119. }
  120. return StringUtils.toBoolean(value)
  121. ? AtomicFileCreation.SUPPORTED
  122. : AtomicFileCreation.NOT_SUPPORTED;
  123. } catch (IOException | ConfigInvalidException e) {
  124. return AtomicFileCreation.SUPPORTED;
  125. }
  126. }
  127. /** {@inheritDoc} */
  128. @Override
  129. public FS newInstance() {
  130. return new FS_POSIX(this);
  131. }
  132. /**
  133. * Set the umask, overriding any value observed from the shell.
  134. *
  135. * @param umask
  136. * mask to apply when creating files.
  137. * @since 4.0
  138. */
  139. public void setUmask(int umask) {
  140. this.umask = umask;
  141. }
  142. private int umask() {
  143. int u = umask;
  144. if (u == -1) {
  145. u = readUmask();
  146. umask = u;
  147. }
  148. return u;
  149. }
  150. /** @return mask returned from running {@code umask} command in shell. */
  151. private static int readUmask() {
  152. try {
  153. Process p = Runtime.getRuntime().exec(
  154. new String[] { "sh", "-c", "umask" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  155. null, null);
  156. try (BufferedReader lineRead = new BufferedReader(
  157. new InputStreamReader(p.getInputStream(), Charset
  158. .defaultCharset().name()))) {
  159. if (p.waitFor() == 0) {
  160. String s = lineRead.readLine();
  161. if (s != null && s.matches("0?\\d{3}")) { //$NON-NLS-1$
  162. return Integer.parseInt(s, 8);
  163. }
  164. }
  165. return DEFAULT_UMASK;
  166. }
  167. } catch (Exception e) {
  168. return DEFAULT_UMASK;
  169. }
  170. }
  171. /** {@inheritDoc} */
  172. @Override
  173. protected File discoverGitExe() {
  174. String path = SystemReader.getInstance().getenv("PATH"); //$NON-NLS-1$
  175. File gitExe = searchPath(path, "git"); //$NON-NLS-1$
  176. if (gitExe == null) {
  177. if (SystemReader.getInstance().isMacOS()) {
  178. if (searchPath(path, "bash") != null) { //$NON-NLS-1$
  179. // On MacOSX, PATH is shorter when Eclipse is launched from the
  180. // Finder than from a terminal. Therefore try to launch bash as a
  181. // login shell and search using that.
  182. String w;
  183. try {
  184. w = readPipe(userHome(),
  185. new String[]{"bash", "--login", "-c", "which git"}, // //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  186. Charset.defaultCharset().name());
  187. } catch (CommandFailedException e) {
  188. LOG.warn(e.getMessage());
  189. return null;
  190. }
  191. if (!StringUtils.isEmptyOrNull(w)) {
  192. gitExe = new File(w);
  193. }
  194. }
  195. }
  196. }
  197. return gitExe;
  198. }
  199. /** {@inheritDoc} */
  200. @Override
  201. public boolean isCaseSensitive() {
  202. return !SystemReader.getInstance().isMacOS();
  203. }
  204. /** {@inheritDoc} */
  205. @Override
  206. public boolean supportsExecute() {
  207. return true;
  208. }
  209. /** {@inheritDoc} */
  210. @Override
  211. public boolean canExecute(File f) {
  212. return FileUtils.canExecute(f);
  213. }
  214. /** {@inheritDoc} */
  215. @Override
  216. public boolean setExecute(File f, boolean canExecute) {
  217. if (!isFile(f))
  218. return false;
  219. if (!canExecute)
  220. return f.setExecutable(false, false);
  221. try {
  222. Path path = FileUtils.toPath(f);
  223. Set<PosixFilePermission> pset = Files.getPosixFilePermissions(path);
  224. // owner (user) is always allowed to execute.
  225. pset.add(PosixFilePermission.OWNER_EXECUTE);
  226. int mask = umask();
  227. apply(pset, mask, PosixFilePermission.GROUP_EXECUTE, 1 << 3);
  228. apply(pset, mask, PosixFilePermission.OTHERS_EXECUTE, 1);
  229. Files.setPosixFilePermissions(path, pset);
  230. return true;
  231. } catch (IOException e) {
  232. // The interface doesn't allow to throw IOException
  233. final boolean debug = Boolean.parseBoolean(SystemReader
  234. .getInstance().getProperty("jgit.fs.debug")); //$NON-NLS-1$
  235. if (debug)
  236. System.err.println(e);
  237. return false;
  238. }
  239. }
  240. private static void apply(Set<PosixFilePermission> set,
  241. int umask, PosixFilePermission perm, int test) {
  242. if ((umask & test) == 0) {
  243. // If bit is clear in umask, permission is allowed.
  244. set.add(perm);
  245. } else {
  246. // If bit is set in umask, permission is denied.
  247. set.remove(perm);
  248. }
  249. }
  250. /** {@inheritDoc} */
  251. @Override
  252. public ProcessBuilder runInShell(String cmd, String[] args) {
  253. List<String> argv = new ArrayList<>(4 + args.length);
  254. argv.add("sh"); //$NON-NLS-1$
  255. argv.add("-c"); //$NON-NLS-1$
  256. argv.add(cmd + " \"$@\""); //$NON-NLS-1$
  257. argv.add(cmd);
  258. argv.addAll(Arrays.asList(args));
  259. ProcessBuilder proc = new ProcessBuilder();
  260. proc.command(argv);
  261. return proc;
  262. }
  263. /** {@inheritDoc} */
  264. @Override
  265. public ProcessResult runHookIfPresent(Repository repository, String hookName,
  266. String[] args, PrintStream outRedirect, PrintStream errRedirect,
  267. String stdinArgs) throws JGitInternalException {
  268. return internalRunHookIfPresent(repository, hookName, args, outRedirect,
  269. errRedirect, stdinArgs);
  270. }
  271. /** {@inheritDoc} */
  272. @Override
  273. public boolean retryFailedLockFileCommit() {
  274. return false;
  275. }
  276. /** {@inheritDoc} */
  277. @Override
  278. public boolean supportsSymlinks() {
  279. return true;
  280. }
  281. /** {@inheritDoc} */
  282. @Override
  283. public void setHidden(File path, boolean hidden) throws IOException {
  284. // no action on POSIX
  285. }
  286. /** {@inheritDoc} */
  287. @Override
  288. public Attributes getAttributes(File path) {
  289. return FileUtils.getFileAttributesPosix(this, path);
  290. }
  291. /** {@inheritDoc} */
  292. @Override
  293. public File normalize(File file) {
  294. return FileUtils.normalize(file);
  295. }
  296. /** {@inheritDoc} */
  297. @Override
  298. public String normalize(String name) {
  299. return FileUtils.normalize(name);
  300. }
  301. /** {@inheritDoc} */
  302. @Override
  303. public File findHook(Repository repository, String hookName) {
  304. final File gitdir = repository.getDirectory();
  305. if (gitdir == null) {
  306. return null;
  307. }
  308. final Path hookPath = gitdir.toPath().resolve(Constants.HOOKS)
  309. .resolve(hookName);
  310. if (Files.isExecutable(hookPath))
  311. return hookPath.toFile();
  312. return null;
  313. }
  314. /** {@inheritDoc} */
  315. @Override
  316. public boolean supportsAtomicCreateNewFile() {
  317. if (supportsAtomicCreateNewFile == AtomicFileCreation.UNDEFINED) {
  318. determineAtomicFileCreationSupport();
  319. }
  320. return supportsAtomicCreateNewFile == AtomicFileCreation.SUPPORTED;
  321. }
  322. @Override
  323. @SuppressWarnings("boxing")
  324. /**
  325. * {@inheritDoc}
  326. * <p>
  327. * An implementation of the File#createNewFile() semantics which works also
  328. * on NFS. If the config option
  329. * {@code core.supportsAtomicCreateNewFile = true} (which is the default)
  330. * then simply File#createNewFile() is called.
  331. *
  332. * But if {@code core.supportsAtomicCreateNewFile = false} then after
  333. * successful creation of the lock file a hard link to that lock file is
  334. * created and the attribute nlink of the lock file is checked to be 2. If
  335. * multiple clients manage to create the same lock file nlink would be
  336. * greater than 2 showing the error.
  337. *
  338. * @see https://www.time-travellers.org/shane/papers/NFS_considered_harmful.html
  339. * @since 4.5
  340. */
  341. public boolean createNewFile(File lock) throws IOException {
  342. if (!lock.createNewFile()) {
  343. return false;
  344. }
  345. if (supportsAtomicCreateNewFile() || !supportsUnixNLink) {
  346. return true;
  347. }
  348. Path lockPath = lock.toPath();
  349. Path link = Files.createLink(Paths.get(lock.getAbsolutePath() + ".lnk"), //$NON-NLS-1$
  350. lockPath);
  351. try {
  352. Integer nlink = (Integer) (Files.getAttribute(lockPath,
  353. "unix:nlink")); //$NON-NLS-1$
  354. if (nlink != 2) {
  355. LOG.warn("nlink of link to lock file {0} was not 2 but {1}", //$NON-NLS-1$
  356. lock.getPath(), nlink);
  357. return false;
  358. }
  359. return true;
  360. } catch (UnsupportedOperationException | IllegalArgumentException e) {
  361. supportsUnixNLink = false;
  362. return true;
  363. } finally {
  364. Files.delete(link);
  365. }
  366. }
  367. }