Chmod.java revision 4378
286N/A/*
286N/A * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
286N/A *
286N/A * Redistribution and use in source and binary forms, with or without
286N/A * modification, are permitted provided that the following conditions
286N/A * are met:
286N/A *
286N/A * - Redistributions of source code must retain the above copyright
286N/A * notice, this list of conditions and the following disclaimer.
286N/A *
286N/A * - Redistributions in binary form must reproduce the above copyright
286N/A * notice, this list of conditions and the following disclaimer in the
286N/A * documentation and/or other materials provided with the distribution.
286N/A *
286N/A * - Neither the name of Oracle nor the names of its
286N/A * contributors may be used to endorse or promote products derived
286N/A * from this software without specific prior written permission.
286N/A *
286N/A * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
286N/A * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
286N/A * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
286N/A * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
286N/A * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
286N/A * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
286N/A * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
286N/A * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
286N/A * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
286N/A * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
286N/A * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
286N/A */
286N/A
286N/A/*
286N/A * This source code is provided to illustrate the usage of a given feature
286N/A * or technique and has been deliberately simplified. Additional steps
286N/A * required for a production-quality application, such as security checks,
286N/A * input validation and proper error handling, might not be present in
286N/A * this sample code.
286N/A */
286N/A
286N/A
286N/Aimport java.nio.file.*;
286N/Aimport java.nio.file.attribute.*;
286N/Aimport static java.nio.file.attribute.PosixFilePermission.*;
286N/Aimport static java.nio.file.FileVisitResult.*;
286N/Aimport java.io.IOException;
286N/Aimport java.util.*;
286N/A
286N/A/**
286N/A * Sample code that changes the permissions of files in a similar manner to the
286N/A * chmod(1) program.
286N/A */
286N/A
286N/Apublic class Chmod {
286N/A
286N/A /**
286N/A * Compiles a list of one or more <em>symbolic mode expressions</em> that
286N/A * may be used to change a set of file permissions. This method is
286N/A * intended for use where file permissions are required to be changed in
286N/A * a manner similar to the UNIX <i>chmod</i> program.
286N/A *
286N/A * <p> The {@code exprs} parameter is a comma separated list of expressions
286N/A * where each takes the form:
286N/A * <blockquote>
286N/A * <i>who operator</i> [<i>permissions</i>]
286N/A * </blockquote>
286N/A * where <i>who</i> is one or more of the characters {@code 'u'}, {@code 'g'},
286N/A * {@code 'o'}, or {@code 'a'} meaning the owner (user), group, others, or
286N/A * all (owner, group, and others) respectively.
286N/A *
286N/A * <p> <i>operator</i> is the character {@code '+'}, {@code '-'}, or {@code
286N/A * '='} signifying how permissions are to be changed. {@code '+'} means the
286N/A * permissions are added, {@code '-'} means the permissions are removed, and
286N/A * {@code '='} means the permissions are assigned absolutely.
286N/A *
286N/A * <p> <i>permissions</i> is a sequence of zero or more of the following:
286N/A * {@code 'r'} for read permission, {@code 'w'} for write permission, and
286N/A * {@code 'x'} for execute permission. If <i>permissions</i> is omitted
286N/A * when assigned absolutely, then the permissions are cleared for
286N/A * the owner, group, or others as identified by <i>who</i>. When omitted
286N/A * when adding or removing then the expression is ignored.
286N/A *
286N/A * <p> The following examples demonstrate possible values for the {@code
286N/A * exprs} parameter:
286N/A *
286N/A * <table border="0">
286N/A * <tr>
286N/A * <td> {@code u=rw} </td>
286N/A * <td> Sets the owner permissions to be read and write. </td>
286N/A * </tr>
286N/A * <tr>
286N/A * <td> {@code ug+w} </td>
286N/A * <td> Sets the owner write and group write permissions. </td>
286N/A * </tr>
286N/A * <tr>
286N/A * <td> {@code u+w,o-rwx} </td>
286N/A * <td> Sets the owner write, and removes the others read, others write
286N/A * and others execute permissions. </td>
286N/A * </tr>
286N/A * <tr>
286N/A * <td> {@code o=} </td>
286N/A * <td> Sets the others permission to none (others read, others write and
286N/A * others execute permissions are removed if set) </td>
286N/A * </tr>
286N/A * </table>
286N/A *
286N/A * @param exprs
286N/A * List of one or more <em>symbolic mode expressions</em>
286N/A *
286N/A * @return A {@code Changer} that may be used to changer a set of
286N/A * file permissions
286N/A *
286N/A * @throws IllegalArgumentException
286N/A * If the value of the {@code exprs} parameter is invalid
286N/A */
286N/A public static Changer compile(String exprs) {
286N/A // minimum is who and operator (u= for example)
286N/A if (exprs.length() < 2)
286N/A throw new IllegalArgumentException("Invalid mode");
286N/A
286N/A // permissions that the changer will add or remove
286N/A final Set<PosixFilePermission> toAdd = new HashSet<PosixFilePermission>();
286N/A final Set<PosixFilePermission> toRemove = new HashSet<PosixFilePermission>();
286N/A
286N/A // iterate over each of expression modes
286N/A for (String expr: exprs.split(",")) {
286N/A // minimum of who and operator
286N/A if (expr.length() < 2)
286N/A throw new IllegalArgumentException("Invalid mode");
286N/A
286N/A int pos = 0;
286N/A
286N/A // who
286N/A boolean u = false;
286N/A boolean g = false;
286N/A boolean o = false;
286N/A boolean done = false;
286N/A for (;;) {
286N/A switch (expr.charAt(pos)) {
286N/A case 'u' : u = true; break;
286N/A case 'g' : g = true; break;
286N/A case 'o' : o = true; break;
286N/A case 'a' : u = true; g = true; o = true; break;
286N/A default : done = true;
286N/A }
286N/A if (done)
286N/A break;
286N/A pos++;
286N/A }
286N/A if (!u && !g && !o)
286N/A throw new IllegalArgumentException("Invalid mode");
286N/A
286N/A // get operator and permissions
286N/A char op = expr.charAt(pos++);
286N/A String mask = (expr.length() == pos) ? "" : expr.substring(pos);
286N/A
286N/A // operator
286N/A boolean add = (op == '+');
286N/A boolean remove = (op == '-');
286N/A boolean assign = (op == '=');
286N/A if (!add && !remove && !assign)
286N/A throw new IllegalArgumentException("Invalid mode");
286N/A
286N/A // who= means remove all
286N/A if (assign && mask.length() == 0) {
286N/A assign = false;
286N/A remove = true;
286N/A mask = "rwx";
286N/A }
286N/A
286N/A // permissions
286N/A boolean r = false;
286N/A boolean w = false;
286N/A boolean x = false;
286N/A for (int i=0; i<mask.length(); i++) {
286N/A switch (mask.charAt(i)) {
286N/A case 'r' : r = true; break;
286N/A case 'w' : w = true; break;
286N/A case 'x' : x = true; break;
286N/A default:
286N/A throw new IllegalArgumentException("Invalid mode");
286N/A }
286N/A }
286N/A
286N/A // update permissions set
286N/A if (add) {
286N/A if (u) {
286N/A if (r) toAdd.add(OWNER_READ);
286N/A if (w) toAdd.add(OWNER_WRITE);
286N/A if (x) toAdd.add(OWNER_EXECUTE);
286N/A }
286N/A if (g) {
286N/A if (r) toAdd.add(GROUP_READ);
286N/A if (w) toAdd.add(GROUP_WRITE);
286N/A if (x) toAdd.add(GROUP_EXECUTE);
286N/A }
286N/A if (o) {
286N/A if (r) toAdd.add(OTHERS_READ);
286N/A if (w) toAdd.add(OTHERS_WRITE);
286N/A if (x) toAdd.add(OTHERS_EXECUTE);
}
}
if (remove) {
if (u) {
if (r) toRemove.add(OWNER_READ);
if (w) toRemove.add(OWNER_WRITE);
if (x) toRemove.add(OWNER_EXECUTE);
}
if (g) {
if (r) toRemove.add(GROUP_READ);
if (w) toRemove.add(GROUP_WRITE);
if (x) toRemove.add(GROUP_EXECUTE);
}
if (o) {
if (r) toRemove.add(OTHERS_READ);
if (w) toRemove.add(OTHERS_WRITE);
if (x) toRemove.add(OTHERS_EXECUTE);
}
}
if (assign) {
if (u) {
if (r) toAdd.add(OWNER_READ);
else toRemove.add(OWNER_READ);
if (w) toAdd.add(OWNER_WRITE);
else toRemove.add(OWNER_WRITE);
if (x) toAdd.add(OWNER_EXECUTE);
else toRemove.add(OWNER_EXECUTE);
}
if (g) {
if (r) toAdd.add(GROUP_READ);
else toRemove.add(GROUP_READ);
if (w) toAdd.add(GROUP_WRITE);
else toRemove.add(GROUP_WRITE);
if (x) toAdd.add(GROUP_EXECUTE);
else toRemove.add(GROUP_EXECUTE);
}
if (o) {
if (r) toAdd.add(OTHERS_READ);
else toRemove.add(OTHERS_READ);
if (w) toAdd.add(OTHERS_WRITE);
else toRemove.add(OTHERS_WRITE);
if (x) toAdd.add(OTHERS_EXECUTE);
else toRemove.add(OTHERS_EXECUTE);
}
}
}
// return changer
return new Changer() {
@Override
public Set<PosixFilePermission> change(Set<PosixFilePermission> perms) {
perms.addAll(toAdd);
perms.removeAll(toRemove);
return perms;
}
};
}
/**
* A task that <i>changes</i> a set of {@link PosixFilePermission} elements.
*/
public interface Changer {
/**
* Applies the changes to the given set of permissions.
*
* @param perms
* The set of permissions to change
*
* @return The {@code perms} parameter
*/
Set<PosixFilePermission> change(Set<PosixFilePermission> perms);
}
/**
* Changes the permissions of the file using the given Changer.
*/
static void chmod(Path file, Changer changer) {
try {
Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
Files.setPosixFilePermissions(file, changer.change(perms));
} catch (IOException x) {
System.err.println(x);
}
}
/**
* Changes the permission of each file and directory visited
*/
static class TreeVisitor implements FileVisitor<Path> {
private final Changer changer;
TreeVisitor(Changer changer) {
this.changer = changer;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
chmod(dir, changer);
return CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
chmod(file, changer);
return CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (exc != null)
System.err.println("WARNING: " + exc);
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.err.println("WARNING: " + exc);
return CONTINUE;
}
}
static void usage() {
System.err.println("java Chmod [-R] symbolic-mode-list file...");
System.exit(-1);
}
public static void main(String[] args) throws IOException {
if (args.length < 2)
usage();
int argi = 0;
int maxDepth = 0;
if (args[argi].equals("-R")) {
if (args.length < 3)
usage();
argi++;
maxDepth = Integer.MAX_VALUE;
}
// compile the symbolic mode expressions
Changer changer = compile(args[argi++]);
TreeVisitor visitor = new TreeVisitor(changer);
Set<FileVisitOption> opts = Collections.emptySet();
while (argi < args.length) {
Path file = Paths.get(args[argi]);
Files.walkFileTree(file, opts, maxDepth, visitor);
argi++;
}
}
}