/** * Create localconf folder and properties file necessary to run build task in order to check merge integrity. * @param branchName */ public void createLocalConfigFile(String branchName) throws Exception { String branchPath = SvnUtils.TEMP_FOLDER + "/" + branchName; //create localconf directory String newDirectoryPath = branchPath + "/localconf"; if ( !Files.exists( Paths.get(newDirectoryPath))) { Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rwxrwxrwx"); FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions .asFileAttribute(permissions); Files.createDirectory(Paths.get(newDirectoryPath), fileAttributes); } //copy properties template Files.copy( Paths.get(branchPath + "/common/conf/worldnettps.properties.template"), Paths.get(newDirectoryPath + "/worldnettps.properties"), StandardCopyOption.REPLACE_EXISTING); //setting glassfish directory in properties file String appServerDir = PropertiesUtil.getString("appserver.dir"); String sedCommand = String.format( "sed -i '/glassfish.dir/c\\glassfish.dir=%s' localconf/worldnettps.properties", appServerDir); CommandExecutor.run( sedCommand, branchPath); logger.info("worldnettps.properties file has been created in localconf folder."); }
/** * 获取Posix权限 */ public static Set<PosixFilePermission> getPosixPerm(int perm) { StringBuilder permStr = new StringBuilder(); permStr.append(uCanRead(perm) ? "r" : "-"); permStr.append(uCanWrite(perm) ? "w" : "-"); permStr.append(uCanExec(perm) ? "x" : "-"); permStr.append(gCanRead(perm) ? "r" : "-"); permStr.append(gCanWrite(perm) ? "w" : "-"); permStr.append(gCanExec(perm) ? "x" : "-"); permStr.append(oCanRead(perm) ? "r" : "-"); permStr.append(oCanWrite(perm) ? "w" : "-"); permStr.append(oCanExec(perm) ? "x" : "-"); return PosixFilePermissions.fromString(permStr.toString()); }
public void testMissingWritePermission() throws IOException { assumeTrue("posix filesystem", isPosix); final String[] tempPaths = tmpPaths(); Path path = PathUtils.get(randomFrom(tempPaths)); try (PosixPermissionsResetter attr = new PosixPermissionsResetter(path)) { attr.setPermissions(new HashSet<>(Arrays.asList(PosixFilePermission.OTHERS_READ, PosixFilePermission.GROUP_READ, PosixFilePermission.OWNER_READ))); Settings build = Settings.builder() .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString()) .putArray(Environment.PATH_DATA_SETTING.getKey(), tempPaths).build(); IOException ioException = expectThrows(IOException.class, () -> { new NodeEnvironment(build, new Environment(build)); }); assertTrue(ioException.getMessage(), ioException.getMessage().startsWith(path.toString())); } }
public void testMissingWritePermissionOnIndex() throws IOException { assumeTrue("posix filesystem", isPosix); final String[] tempPaths = tmpPaths(); Path path = PathUtils.get(randomFrom(tempPaths)); Path fooIndex = path.resolve("nodes").resolve("0").resolve(NodeEnvironment.INDICES_FOLDER) .resolve("foo"); Files.createDirectories(fooIndex); try (PosixPermissionsResetter attr = new PosixPermissionsResetter(fooIndex)) { attr.setPermissions(new HashSet<>(Arrays.asList(PosixFilePermission.OTHERS_READ, PosixFilePermission.GROUP_READ, PosixFilePermission.OWNER_READ))); Settings build = Settings.builder() .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString()) .putArray(Environment.PATH_DATA_SETTING.getKey(), tempPaths).build(); IOException ioException = expectThrows(IOException.class, () -> { new NodeEnvironment(build, new Environment(build)); }); assertTrue(ioException.getMessage(), ioException.getMessage().startsWith("failed to write in data directory")); } }
public void testMissingWritePermissionOnShard() throws IOException { assumeTrue("posix filesystem", isPosix); final String[] tempPaths = tmpPaths(); Path path = PathUtils.get(randomFrom(tempPaths)); Path fooIndex = path.resolve("nodes").resolve("0").resolve(NodeEnvironment.INDICES_FOLDER) .resolve("foo"); Path fooShard = fooIndex.resolve("0"); Path fooShardIndex = fooShard.resolve("index"); Path fooShardTranslog = fooShard.resolve("translog"); Path fooShardState = fooShard.resolve("_state"); Path pick = randomFrom(fooShard, fooShardIndex, fooShardTranslog, fooShardState); Files.createDirectories(pick); try (PosixPermissionsResetter attr = new PosixPermissionsResetter(pick)) { attr.setPermissions(new HashSet<>(Arrays.asList(PosixFilePermission.OTHERS_READ, PosixFilePermission.GROUP_READ, PosixFilePermission.OWNER_READ))); Settings build = Settings.builder() .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString()) .putArray(Environment.PATH_DATA_SETTING.getKey(), tempPaths).build(); IOException ioException = expectThrows(IOException.class, () -> { new NodeEnvironment(build, new Environment(build)); }); assertTrue(ioException.getMessage(), ioException.getMessage().startsWith("failed to write in data directory")); } }
public void testBinPermissions() throws Exception { assumeTrue("posix filesystem", isPosix); Tuple<Path, Environment> env = createEnv(fs, temp); Path pluginDir = createPluginDir(temp); Path binDir = pluginDir.resolve("bin"); Files.createDirectory(binDir); Files.createFile(binDir.resolve("somescript")); String pluginZip = createPlugin("fake", pluginDir); try (PosixPermissionsResetter binAttrs = new PosixPermissionsResetter(env.v2().binFile())) { Set<PosixFilePermission> perms = binAttrs.getCopyPermissions(); // make sure at least one execute perm is missing, so we know we forced it during installation perms.remove(PosixFilePermission.GROUP_EXECUTE); binAttrs.setPermissions(perms); installPlugin(pluginZip, env.v1()); assertPlugin("fake", pluginDir, env.v2()); } }
public static void setAsExecutable(String filePath) throws IOException { //using PosixFilePermission to set file permissions 755 Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_EXECUTE); Files.setPosixFilePermissions(Paths.get(filePath), perms); logger.info("Modified as executable " + filePath); }
public TestWorkspaceBuilder build() throws IOException { // mkdir -p Files.createDirectories(path.getParent()); try (Writer out = Files.newBufferedWriter(path, Charset.defaultCharset())) { out.write(contents); } Set<PosixFilePermission> permissions = Sets.newHashSet( PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE); if (isExecutable) { permissions.add(PosixFilePermission.OWNER_EXECUTE); } Files.setPosixFilePermissions(path, permissions); return workspaceBuilder; }
public int execute(String[] args, @Nullable Path workingDir, Map<String, String> addEnv) throws IOException { if (!Files.isExecutable(file)) { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(file, perms); } ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); CommandLine cmd = new CommandLine(file.toFile()); cmd.addArguments(args); DefaultExecutor exec = new DefaultExecutor(); exec.setWatchdog(watchdog); exec.setStreamHandler(createStreamHandler()); exec.setExitValues(null); if (workingDir != null) { exec.setWorkingDirectory(workingDir.toFile()); } in.close(); LOG.info("Executing: {}", cmd.toString()); Map<String, String> env = new HashMap<>(System.getenv()); env.putAll(addEnv); return exec.execute(cmd, env); }
public static void copyFilesAndApplyPermissions(Path sourceDir, Path targetDir, List<String> filenames) throws IOException { for (String fileName : filenames) { Files.copy(sourceDir.resolve(fileName), targetDir.resolve(fileName)); try { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); Files.setPosixFilePermissions(targetDir.resolve(fileName), perms); } catch (Throwable ignored) { } } }
private static int permissionToInt(PosixFilePermission permission) { switch (permission) { case OWNER_EXECUTE: return 100; case GROUP_EXECUTE: return 10; case OTHERS_EXECUTE: return 1; case OWNER_WRITE: return 200; case GROUP_WRITE: return 20; case OTHERS_WRITE: return 2; case OWNER_READ: return 400; case GROUP_READ: return 40; case OTHERS_READ: return 4; default: return 0; } }
private static void chmodFiles(final Args arg, final HashMap<String, String> pairs, final String[] chmodList) throws IOException { final HashSet<PosixFilePermission> chmodSet = new HashSet<>(); chmodSet.add(PosixFilePermission.OWNER_EXECUTE); chmodSet.add(PosixFilePermission.OWNER_READ); chmodSet.add(PosixFilePermission.OWNER_WRITE); System.out.println("Setting file permissions..."); for(final String filename: chmodList) { System.out.println("\t" + arg.projectFolder.toString() + substitute(filename, pairs)); final String resourceName = WebFramework.getResourceName(filename); final Path path = FileSystems.getDefault().getPath(arg.projectFolder.toString() + substitute(filename, pairs)); Files.setPosixFilePermissions(path, chmodSet); } }
private boolean mkdirs(File file, Set<PosixFilePermission> permissions) throws IOException { if (file.exists()) { return false; } if (file.mkdir()) { Files.setPosixFilePermissions(file.toPath(), permissions); return true; } File parent = file.getParentFile(); if (parent == null) { return false; } if (!mkdirs(parent, permissions) && !parent.exists()) { return false; } if (file.mkdir()) { Files.setPosixFilePermissions(file.toPath(), permissions); return true; } return false; }
public static void assertFilePermissions(Path testRoot) throws IOException { Path file1 = testRoot.resolve(FILE_1); // mode 664 PosixFileAttributeView allAttributesFile1 = Files.getFileAttributeView(file1, PosixFileAttributeView.class); Assert.assertThat( allAttributesFile1.readAttributes().permissions(), Matchers.containsInAnyOrder( PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_READ)); Path file2 = testRoot.resolve(FILE_2); // mode 777 PosixFileAttributeView allAttributesFile2 = Files.getFileAttributeView(file2, PosixFileAttributeView.class); Assert.assertThat( allAttributesFile2.readAttributes().permissions(), Matchers.containsInAnyOrder(PosixFilePermission.values())); }
@Test public void testCopyDirectory_posixPermissions() throws IOException { assumeTrue(!System.getProperty("os.name").startsWith("Windows")); Set<PosixFilePermission> permission = Sets.newHashSet(); permission.add(PosixFilePermission.OWNER_READ); permission.add(PosixFilePermission.GROUP_READ); permission.add(PosixFilePermission.OTHERS_READ); permission.add(PosixFilePermission.OTHERS_EXECUTE); permission.add(PosixFilePermission.OTHERS_WRITE); Path src = testDir.newFolder("src").toPath(); Path dest = testDir.newFolder("dest").toPath(); Path rootFile = Files.createFile(src.resolve("root1.file")); Assert.assertNotEquals( "This test is useless - modified permissions are default permissions", Files.getPosixFilePermissions(rootFile), permission); Files.setPosixFilePermissions(rootFile, permission); FileUtil.copyDirectory(src, dest); Assert.assertEquals( permission, Files.getPosixFilePermissions(dest.resolve(src.relativize(rootFile)))); }
@Test public void addLauncherScript() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File source = this.testJarFile.getFile(); File dest = this.temporaryFolder.newFile("dest.jar"); Repackager repackager = new Repackager(source); LaunchScript script = new MockLauncherScript("ABC"); repackager.repackage(dest, NO_LIBRARIES, script); byte[] bytes = FileCopyUtils.copyToByteArray(dest); assertThat(new String(bytes)).startsWith("ABC"); assertThat(hasLauncherClasses(source)).isFalse(); assertThat(hasLauncherClasses(dest)).isTrue(); try { assertThat(Files.getPosixFilePermissions(dest.toPath())) .contains(PosixFilePermission.OWNER_EXECUTE); } catch (UnsupportedOperationException ex) { // Probably running the test on Windows } }
/** * Tries to add the Posix permissions if the file belongs to a Posix filesystem. This is an * addition, which means that no permissions are removed. * * <p>For Windows type filesystems, it uses setReadable/setWritable/setExecutable, which is only * supported for the owner, and ignores the rest of permissions. */ public static void addPermissions(Path path, Set<PosixFilePermission> permissionsToAdd) throws IOException { if (path.getFileSystem().supportedFileAttributeViews().contains("posix")) { Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(path); permissions.addAll(permissionsToAdd); Files.setPosixFilePermissions(path, permissions); } else { File file = path.toFile(); if (permissionsToAdd.contains(PosixFilePermission.OWNER_READ)) { if (!file.setReadable(true)) { throw new IOException("Could not set 'readable' permission for file: " + path); } } if (permissionsToAdd.contains(PosixFilePermission.OWNER_WRITE)) { if (!file.setWritable(true)) { throw new IOException("Could not set 'writable' permission for file: " + path); } } if (permissionsToAdd.contains(PosixFilePermission.OWNER_EXECUTE)) { if (!file.setExecutable(true)) { throw new IOException("Could not set 'executable' permission for file: " + path); } } } }
@Test public void testGitOriginWithHookExitError() throws Exception { Path hook = Files.createTempFile("script", "script"); Files.write(hook, "exit 1".getBytes(UTF_8)); Files.setPosixFilePermissions(hook, ImmutableSet.<PosixFilePermission>builder() .addAll(Files.getPosixFilePermissions(hook)) .add(PosixFilePermission.OWNER_EXECUTE).build()); options.gitOrigin.originCheckoutHook = hook.toAbsolutePath().toString(); origin = origin(); Reader<GitRevision> reader = newReader(); thrown.expect(RepoException.class); thrown.expectMessage("Error executing the git checkout hook"); reader.checkout(origin.resolve("master"), checkoutDir); }
@Test public void testWriteError() throws Exception { Deployer deployer = getService( Deployer.class ); Path plan = Files.createTempDirectory( "xmvn-test" ).resolve( "plan.xml" ); try ( BufferedWriter bw = Files.newBufferedWriter( plan ) ) { bw.write( "<metadata/>" ); } Files.setPosixFilePermissions( plan, Collections.singleton( PosixFilePermission.OTHERS_READ ) ); DeploymentRequest req = new DeploymentRequest(); req.setPlanPath( plan ); req.setArtifact( new DefaultArtifact( "g:a:v" ).setPath( Paths.get( "src/test/resources/simple.xml" ) ) ); DeploymentResult res = deployer.deploy( req ); assertNotNull( res.getException() ); assertTrue( IOException.class.isAssignableFrom( res.getException().getClass() ) ); }
/** * creates and grants permission to daemon files directory */ private static void setupEnvironment() { final File daemonFilePath = new File("/var/run/iofabric"); if (!daemonFilePath.exists()) { try { daemonFilePath.mkdirs(); UserPrincipalLookupService lookupservice = FileSystems.getDefault().getUserPrincipalLookupService(); final GroupPrincipal group = lookupservice.lookupPrincipalByGroupName("iofabric"); Files.getFileAttributeView(daemonFilePath.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setGroup(group); Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwx---"); Files.setPosixFilePermissions(daemonFilePath.toPath(), perms); } catch (Exception e) { } } }
private void runChmodCheck(String routeSuffix, String expectedPermissions) throws Exception { MockEndpoint mock = getMockEndpoint("mock:chmod" + routeSuffix); mock.expectedMessageCount(1); String testFileName = "chmod" + routeSuffix + ".txt"; String fullTestFileName = TEST_DIRECTORY + testFileName; String testFileContent = "Writing file with chmod " + routeSuffix + " option at " + new Date(); mock.expectedFileExists(fullTestFileName, testFileContent); template.sendBodyAndHeader("direct:write" + routeSuffix, testFileContent, Exchange.FILE_NAME, testFileName); File f = new File(fullTestFileName); Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(f.toPath(), LinkOption.NOFOLLOW_LINKS); assertEquals(expectedPermissions, PosixFilePermissions.toString(permissions)); assertEquals(expectedPermissions.replace("-", "").length(), permissions.size()); assertMockEndpointsSatisfied(); }
public static void createUnixDirectories( final Permission perm, final Path... dirs) throws IOException { FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(POSIX_OWNrwx); switch (perm) { case OWNER_FULL_GROUP_EXEC: attr = PosixFilePermissions.asFileAttribute(POSIX_OWNrwx_GRPr_x); break; case OWNER_FULL_GROUP_EXEC_OTHER_EXEC: attr = PosixFilePermissions.asFileAttribute(POSIX_OWNrwx_GRPr_x_OTHr_x); break; } for (Path dir : dirs) { if (!java.nio.file.Files.exists(dir, LinkOption.NOFOLLOW_LINKS)) { m_logger.debug("Creating directory: {} with permissions: {}", dir, perm); java.nio.file.Files.createDirectories(dir, attr); } else { m_logger.debug("Directory exists: {}", dir); } } }
@Test public void testFromFile() throws Exception { File pwFile = folder.newFile(); try(FileOutputStream o = new FileOutputStream(pwFile)) { o.write("this is a fairly long password".getBytes()); } Set<PosixFilePermission> permission = new HashSet<>(); permission.add(PosixFilePermission.OWNER_READ); permission.add(PosixFilePermission.OWNER_WRITE); Files.setPosixFilePermissions(pwFile.toPath(), permission); PasswordProvider uic = new PasswordProvider(); uic.setArchivePassword(pwFile); }
@Test public void addLauncherScript() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File source = this.testJarFile.getFile(); File dest = this.temporaryFolder.newFile("dest.jar"); Repackager repackager = new Repackager(source); LaunchScript script = new MockLauncherScript("ABC"); repackager.repackage(dest, NO_LIBRARIES, script); byte[] bytes = FileCopyUtils.copyToByteArray(dest); assertThat(new String(bytes), startsWith("ABC")); assertThat(hasLauncherClasses(source), equalTo(false)); assertThat(hasLauncherClasses(dest), equalTo(true)); try { assertThat(Files.getPosixFilePermissions(dest.toPath()), hasItem(PosixFilePermission.OWNER_EXECUTE)); } catch (UnsupportedOperationException ex) { // Probably running the test on Windows } }
/** * Adds the executable file permission. * * @param file the path to the file */ private void addExecutablePermission(String file) { final Path path = Paths.get(file); if (Files.exists(path)) { try { PosixFileAttributeView attr = Files.getFileAttributeView(path, PosixFileAttributeView.class); Set<PosixFilePermission> permissions = attr.readAttributes().permissions(); if(permissions.add(PosixFilePermission.OWNER_EXECUTE)) { logger.info(String.format("Added +x permission to file: %s", file)); } attr.setPermissions(permissions); } catch (IOException e) { logger.error(String.format("Failed to add the executable permissions to file: %s", file)); } } }
public void archiveDump(final Path fromDir, final Path toDir) throws IOException { log.info("Archiving " + fromDir + " to " + toDir); Files.createDirectories(toDir.getParent()); if (Files.exists(toDir)) { log.info(toDir + " exists. Deleting it"); FileUtils.deleteDirectory(toDir.toFile()); } final Set<PosixFilePermission> readOnly = new HashSet<PosixFilePermission>(); readOnly.add(PosixFilePermission.OWNER_READ); readOnly.add(PosixFilePermission.GROUP_READ); readOnly.add(PosixFilePermission.OTHERS_READ); try (DirectoryStream<Path> listing = Files.newDirectoryStream(fromDir)) { for (final Path table : listing) { if (Files.isDirectory(table)) { try (DirectoryStream<Path> tableListing = Files.newDirectoryStream(table)) { for (final Path dumpFile : Files.newDirectoryStream(table)) { Files.setPosixFilePermissions(dumpFile, readOnly); } } } } } Files.move(fromDir, toDir); }
public Set<PosixFilePermission> intToPosixFilePermission(int mode) { if (mode >= 1000 || mode < 0) { throw new IllegalArgumentException("Invalid mode " + mode); } final int owner = mode / 100; final int group = (mode - owner * 100) / 10; final int others = mode - owner * 100 - group * 10; if (owner > 7 || group > 7 || others > 7) { throw new IllegalArgumentException("Invalid mode " + mode); } return Sets.union( Sets.union(singleIntToFilePermission(owner, "OWNER"), singleIntToFilePermission(group, "GROUP")), singleIntToFilePermission(others, "OTHERS")); }
DropboxVirtualFile(String fileName, VirtualVolume volume) throws IOException { super(fileName, volume); if (file.exists()) { Set<PosixFilePermission> perms = Files.getPosixFilePermissions(Paths.get(fileName)); long attr = (perms.contains(PosixFilePermission.OWNER_READ) ? TypeMode.S_IRUSR : 0L) | (perms.contains(PosixFilePermission.OWNER_WRITE) ? TypeMode.S_IWUSR : 0L) | (perms.contains(PosixFilePermission.OWNER_EXECUTE) ? TypeMode.S_IXUSR : 0L) | (perms.contains(PosixFilePermission.GROUP_READ) ? TypeMode.S_IRGRP : 0L) | (perms.contains(PosixFilePermission.GROUP_WRITE) ? TypeMode.S_IWGRP : 0L) | (perms.contains(PosixFilePermission.GROUP_EXECUTE) ? TypeMode.S_IXGRP : 0L) | (perms.contains(PosixFilePermission.OTHERS_READ) ? TypeMode.S_IROTH : 0L) | (perms.contains(PosixFilePermission.OTHERS_WRITE) ? TypeMode.S_IWOTH : 0L) | (perms.contains(PosixFilePermission.OTHERS_EXECUTE) ? TypeMode.S_IXOTH : 0L); this.attr = attr; } else { this.attr = 256; // 420 init: owner R+W, group+other R } }
@Override public void setAttr(long attr) throws IOException { this.attr = attr; if (file.exists()) { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); // add owners permission if ((attr & TypeMode.S_IRUSR) > 0) perms.add(PosixFilePermission.OWNER_READ); if ((attr & TypeMode.S_IWUSR) > 0) perms.add(PosixFilePermission.OWNER_WRITE); if ((attr & TypeMode.S_IXUSR) > 0) perms.add(PosixFilePermission.OWNER_EXECUTE); // add group permissions if ((attr & TypeMode.S_IRGRP) > 0) perms.add(PosixFilePermission.GROUP_READ); if ((attr & TypeMode.S_IWGRP) > 0) perms.add(PosixFilePermission.GROUP_WRITE); if ((attr & TypeMode.S_IXGRP) > 0) perms.add(PosixFilePermission.GROUP_EXECUTE); // add others permissions if ((attr & TypeMode.S_IROTH) > 0) perms.add(PosixFilePermission.OTHERS_READ); if ((attr & TypeMode.S_IWOTH) > 0) perms.add(PosixFilePermission.OTHERS_WRITE); if ((attr & TypeMode.S_IXOTH) > 0) perms.add(PosixFilePermission.OTHERS_EXECUTE); Files.setPosixFilePermissions(Paths.get(file.getPath()), perms); } }
private Set<PosixFilePermission> singleIntToFilePermission(Integer mode, String groupType) { Set<PosixFilePermission> permissions = new HashSet<>(9); if (Arrays.asList(new Integer[] { 1, 3, 5, 7 }).contains(mode)) { permissions.add(PosixFilePermission.valueOf(groupType + "_EXECUTE")); } if (Arrays.asList(new Integer[] { 2, 3, 6, 7 }).contains(mode)) { permissions.add(PosixFilePermission.valueOf(groupType + "_WRITE")); } if (Arrays.asList(new Integer[] { 4, 5, 6, 7 }).contains(mode)) { permissions.add(PosixFilePermission.valueOf(groupType + "_READ")); } return permissions; }
@Test public void testLoadResourceRestrictedFailure() throws Exception { exception.expect(IllegalArgumentException.class); Path fooFile = Paths.get(resourcesDir.getPath(), "foo.txt"); Files.write(fooFile, "Hello\n".getBytes(StandardCharsets.UTF_8)); Files.setPosixFilePermissions(fooFile, ImmutableSet.of(PosixFilePermission.OTHERS_READ)); RuntimeEL.loadRuntimeConfiguration(runtimeInfo); try { RuntimeEL.loadResourceRaw("foo.txt", true); } finally { Files.deleteIfExists(fooFile); } }
@Test public void testLoadResourceRestrictedSuccess() throws Exception { Path fooFile = Paths.get(resourcesDir.getPath(), "foo.txt"); Files.write(fooFile, "Hello\n".getBytes(StandardCharsets.UTF_8)); Files.setPosixFilePermissions(fooFile, ImmutableSet.of( PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE) ); RuntimeEL.loadRuntimeConfiguration(runtimeInfo); try { RuntimeEL.loadResourceRaw("foo.txt", true); } finally { Files.deleteIfExists(fooFile); } }
private void validateRealmFile(File realmFile) { boolean checkRealmFilePermission = conf.get(REALM_FILE_PERMISSION_CHECK, REALM_FILE_PERMISSION_CHECK_DEFAULT); if(!checkRealmFilePermission) { return; } if (!realmFile.exists()) { throw new RuntimeException(Utils.format("Realm file '{}' does not exists", realmFile)); } if (!realmFile.isFile()) { throw new RuntimeException(Utils.format("Realm file '{}' is not a file", realmFile)); } try { Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(realmFile.toPath()); permissions.removeAll(OWNER_PERMISSIONS); if (!permissions.isEmpty()) { throw new RuntimeException(Utils.format("The permissions of the realm file '{}' should be owner only", realmFile)); } } catch (IOException ex) { throw new RuntimeException(Utils.format("Could not get the permissions of the realm file '{}', {}", realmFile, ex.toString()), ex); } }
private static EnumSet<PosixFilePermission> convertFromNioFileAttributes( boolean isDirectory, FileAttribute<?>... attributes) { if (attributes != null) { for (FileAttribute<?> attr : attributes) { if (attr.name().equals("posix:permissions")) { Collection<PosixFilePermission> callerPerms = (Collection<PosixFilePermission>) attr.value(); return EnumSet.copyOf(callerPerms); } } } if (isDirectory) { return createDefaultDirectory().permissions; } else { return createDefaultFile().permissions; } }
@IgnoreIf(FsType.WINDOWS) @Test public void testCheckAccessCopyOfExecutableFileWindows() throws Exception { Path path = root.resolve("path"); Files.createFile(path, PosixFilePermissions.asFileAttribute( EnumSet.allOf(PosixFilePermission.class)) ); Path copy = root.resolve("copy"); Files.copy(path, copy); assertTrue(Files.isReadable(copy)); assertTrue(Files.isWritable(copy)); assertTrue(Files.exists(copy)); assertTrue(Files.exists(copy, LinkOption.NOFOLLOW_LINKS)); assertTrue(Files.isExecutable(copy)); }
@Test public void preserveOriginalFile() throws Exception { Path path = testFolder.newFile("Test.java").toPath(); Files.write(path, "class Test {}\n".getBytes(UTF_8)); try { Files.setPosixFilePermissions(path, EnumSet.of(PosixFilePermission.OWNER_READ)); } catch (UnsupportedOperationException e) { return; } Main main = new Main( new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out, UTF_8)), true), new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.err, UTF_8)), true), System.in); int errorCode = main.format("-replace", path.toAbsolutePath().toString()); assertThat(errorCode).named("Error Code").isEqualTo(0); }
@Override protected String getFilePermissions(File file, LsArguments args) { try { final Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file.toPath()); return (file.isDirectory() ? "d" : "-") + (perms.contains(PosixFilePermission.OWNER_READ) ? 'r' : '-') + (perms.contains(PosixFilePermission.OWNER_WRITE) ? 'w' : '-') + (perms.contains(PosixFilePermission.OWNER_EXECUTE) ? 'x' : '-') + (perms.contains(PosixFilePermission.GROUP_READ) ? 'r' : '-') + (perms.contains(PosixFilePermission.GROUP_WRITE) ? 'w' : '-') + (perms.contains(PosixFilePermission.GROUP_EXECUTE) ? 'x' : '-') + (perms.contains(PosixFilePermission.OTHERS_READ) ? 'r' : '-') + (perms.contains(PosixFilePermission.OTHERS_WRITE) ? 'w' : '-') + (perms.contains(PosixFilePermission.OTHERS_EXECUTE) ? 'x' : '-'); } catch (Exception e) { return super.getFilePermissions(file, args); } }
static Set<PosixFilePermission> convertToPermissionsSet(int mode) { Set<PosixFilePermission> result = EnumSet.noneOf(PosixFilePermission.class); if (isSet(mode, 0400)) { result.add(OWNER_READ); } if (isSet(mode, 0200)) { result.add(OWNER_WRITE); } if (isSet(mode, 0100)) { result.add(OWNER_EXECUTE); } if (isSet(mode, 040)) { result.add(GROUP_READ); } if (isSet(mode, 020)) { result.add(GROUP_WRITE); } if (isSet(mode, 010)) { result.add(GROUP_EXECUTE); } if (isSet(mode, 04)) { result.add(OTHERS_READ); } if (isSet(mode, 02)) { result.add(OTHERS_WRITE); } if (isSet(mode, 01)) { result.add(OTHERS_EXECUTE); } return result; }
public static int convertToInt(Set<PosixFilePermission> permissions) { int result = 0; if (permissions.contains(OWNER_READ)) { result = result | 0400; } if (permissions.contains(OWNER_WRITE)) { result = result | 0200; } if (permissions.contains(OWNER_EXECUTE)) { result = result | 0100; } if (permissions.contains(GROUP_READ)) { result = result | 040; } if (permissions.contains(GROUP_WRITE)) { result = result | 020; } if (permissions.contains(GROUP_EXECUTE)) { result = result | 010; } if (permissions.contains(OTHERS_READ)) { result = result | 04; } if (permissions.contains(OTHERS_WRITE)) { result = result | 02; } if (permissions.contains(OTHERS_EXECUTE)) { result = result | 01; } return result; }