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

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