001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018 package org.apache.hadoop.fs.permission;
019
020 import java.io.DataInput;
021 import java.io.DataOutput;
022 import java.io.IOException;
023
024 import org.apache.commons.logging.Log;
025 import org.apache.commons.logging.LogFactory;
026 import org.apache.hadoop.classification.InterfaceAudience;
027 import org.apache.hadoop.classification.InterfaceStability;
028 import org.apache.hadoop.conf.Configuration;
029 import org.apache.hadoop.fs.CommonConfigurationKeys;
030 import org.apache.hadoop.io.Writable;
031 import org.apache.hadoop.io.WritableFactories;
032 import org.apache.hadoop.io.WritableFactory;
033
034 /**
035 * A class for file/directory permissions.
036 */
037 @InterfaceAudience.Public
038 @InterfaceStability.Stable
039 public class FsPermission implements Writable {
040 private static final Log LOG = LogFactory.getLog(FsPermission.class);
041
042 static final WritableFactory FACTORY = new WritableFactory() {
043 @Override
044 public Writable newInstance() { return new FsPermission(); }
045 };
046 static { // register a ctor
047 WritableFactories.setFactory(FsPermission.class, FACTORY);
048 WritableFactories.setFactory(ImmutableFsPermission.class, FACTORY);
049 }
050
051 /** Maximum acceptable length of a permission string to parse */
052 public static final int MAX_PERMISSION_LENGTH = 10;
053
054 /** Create an immutable {@link FsPermission} object. */
055 public static FsPermission createImmutable(short permission) {
056 return new ImmutableFsPermission(permission);
057 }
058
059 //POSIX permission style
060 private FsAction useraction = null;
061 private FsAction groupaction = null;
062 private FsAction otheraction = null;
063 private boolean stickyBit = false;
064
065 private FsPermission() {}
066
067 /**
068 * Construct by the given {@link FsAction}.
069 * @param u user action
070 * @param g group action
071 * @param o other action
072 */
073 public FsPermission(FsAction u, FsAction g, FsAction o) {
074 this(u, g, o, false);
075 }
076
077 public FsPermission(FsAction u, FsAction g, FsAction o, boolean sb) {
078 set(u, g, o, sb);
079 }
080
081 /**
082 * Construct by the given mode.
083 * @param mode
084 * @see #toShort()
085 */
086 public FsPermission(short mode) { fromShort(mode); }
087
088 /**
089 * Copy constructor
090 *
091 * @param other other permission
092 */
093 public FsPermission(FsPermission other) {
094 this.useraction = other.useraction;
095 this.groupaction = other.groupaction;
096 this.otheraction = other.otheraction;
097 this.stickyBit = other.stickyBit;
098 }
099
100 /**
101 * Construct by given mode, either in octal or symbolic format.
102 * @param mode mode as a string, either in octal or symbolic format
103 * @throws IllegalArgumentException if <code>mode</code> is invalid
104 */
105 public FsPermission(String mode) {
106 this(new UmaskParser(mode).getUMask());
107 }
108
109 /** Return user {@link FsAction}. */
110 public FsAction getUserAction() {return useraction;}
111
112 /** Return group {@link FsAction}. */
113 public FsAction getGroupAction() {return groupaction;}
114
115 /** Return other {@link FsAction}. */
116 public FsAction getOtherAction() {return otheraction;}
117
118 private void set(FsAction u, FsAction g, FsAction o, boolean sb) {
119 useraction = u;
120 groupaction = g;
121 otheraction = o;
122 stickyBit = sb;
123 }
124
125 public void fromShort(short n) {
126 FsAction[] v = FSACTION_VALUES;
127 set(v[(n >>> 6) & 7], v[(n >>> 3) & 7], v[n & 7], (((n >>> 9) & 1) == 1) );
128 }
129
130 @Override
131 public void write(DataOutput out) throws IOException {
132 out.writeShort(toShort());
133 }
134
135 @Override
136 public void readFields(DataInput in) throws IOException {
137 fromShort(in.readShort());
138 }
139
140 /**
141 * Create and initialize a {@link FsPermission} from {@link DataInput}.
142 */
143 public static FsPermission read(DataInput in) throws IOException {
144 FsPermission p = new FsPermission();
145 p.readFields(in);
146 return p;
147 }
148
149 /**
150 * Encode the object to a short.
151 */
152 public short toShort() {
153 int s = (stickyBit ? 1 << 9 : 0) |
154 (useraction.ordinal() << 6) |
155 (groupaction.ordinal() << 3) |
156 otheraction.ordinal();
157
158 return (short)s;
159 }
160
161 @Override
162 public boolean equals(Object obj) {
163 if (obj instanceof FsPermission) {
164 FsPermission that = (FsPermission)obj;
165 return this.useraction == that.useraction
166 && this.groupaction == that.groupaction
167 && this.otheraction == that.otheraction
168 && this.stickyBit == that.stickyBit;
169 }
170 return false;
171 }
172
173 @Override
174 public int hashCode() {return toShort();}
175
176 @Override
177 public String toString() {
178 String str = useraction.SYMBOL + groupaction.SYMBOL + otheraction.SYMBOL;
179 if(stickyBit) {
180 StringBuilder str2 = new StringBuilder(str);
181 str2.replace(str2.length() - 1, str2.length(),
182 otheraction.implies(FsAction.EXECUTE) ? "t" : "T");
183 str = str2.toString();
184 }
185
186 return str;
187 }
188
189 /**
190 * Apply a umask to this permission and return a new one.
191 *
192 * The umask is used by create, mkdir, and other Hadoop filesystem operations.
193 * The mode argument for these operations is modified by removing the bits
194 * which are set in the umask. Thus, the umask limits the permissions which
195 * newly created files and directories get.
196 *
197 * @param umask The umask to use
198 *
199 * @return The effective permission
200 */
201 public FsPermission applyUMask(FsPermission umask) {
202 return new FsPermission(useraction.and(umask.useraction.not()),
203 groupaction.and(umask.groupaction.not()),
204 otheraction.and(umask.otheraction.not()));
205 }
206
207 /** umask property label deprecated key and code in getUMask method
208 * to accommodate it may be removed in version .23 */
209 public static final String DEPRECATED_UMASK_LABEL = "dfs.umask";
210 public static final String UMASK_LABEL =
211 CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY;
212 public static final int DEFAULT_UMASK =
213 CommonConfigurationKeys.FS_PERMISSIONS_UMASK_DEFAULT;
214
215 private static final FsAction[] FSACTION_VALUES = FsAction.values();
216
217 /**
218 * Get the user file creation mask (umask)
219 *
220 * {@code UMASK_LABEL} config param has umask value that is either symbolic
221 * or octal.
222 *
223 * Symbolic umask is applied relative to file mode creation mask;
224 * the permission op characters '+' clears the corresponding bit in the mask,
225 * '-' sets bits in the mask.
226 *
227 * Octal umask, the specified bits are set in the file mode creation mask.
228 *
229 * {@code DEPRECATED_UMASK_LABEL} config param has umask value set to decimal.
230 */
231 public static FsPermission getUMask(Configuration conf) {
232 int umask = DEFAULT_UMASK;
233
234 // To ensure backward compatibility first use the deprecated key.
235 // If the deprecated key is not present then check for the new key
236 if(conf != null) {
237 String confUmask = conf.get(UMASK_LABEL);
238 int oldUmask = conf.getInt(DEPRECATED_UMASK_LABEL, Integer.MIN_VALUE);
239 try {
240 if(confUmask != null) {
241 umask = new UmaskParser(confUmask).getUMask();
242 }
243 } catch(IllegalArgumentException iae) {
244 // Provide more explanation for user-facing message
245 String type = iae instanceof NumberFormatException ? "decimal"
246 : "octal or symbolic";
247 String error = "Unable to parse configuration " + UMASK_LABEL
248 + " with value " + confUmask + " as " + type + " umask.";
249 LOG.warn(error);
250
251 // If oldUmask is not set, then throw the exception
252 if (oldUmask == Integer.MIN_VALUE) {
253 throw new IllegalArgumentException(error);
254 }
255 }
256
257 if(oldUmask != Integer.MIN_VALUE) { // Property was set with old key
258 if (umask != oldUmask) {
259 LOG.warn(DEPRECATED_UMASK_LABEL
260 + " configuration key is deprecated. " + "Convert to "
261 + UMASK_LABEL + ", using octal or symbolic umask "
262 + "specifications.");
263 // Old and new umask values do not match - Use old umask
264 umask = oldUmask;
265 }
266 }
267 }
268
269 return new FsPermission((short)umask);
270 }
271
272 public boolean getStickyBit() {
273 return stickyBit;
274 }
275
276 /** Set the user file creation mask (umask) */
277 public static void setUMask(Configuration conf, FsPermission umask) {
278 conf.set(UMASK_LABEL, String.format("%1$03o", umask.toShort()));
279 conf.setInt(DEPRECATED_UMASK_LABEL, umask.toShort());
280 }
281
282 /**
283 * Get the default permission for directory and symlink.
284 * In previous versions, this default permission was also used to
285 * create files, so files created end up with ugo+x permission.
286 * See HADOOP-9155 for detail.
287 * Two new methods are added to solve this, please use
288 * {@link FsPermission#getDirDefault()} for directory, and use
289 * {@link FsPermission#getFileDefault()} for file.
290 * This method is kept for compatibility.
291 */
292 public static FsPermission getDefault() {
293 return new FsPermission((short)00777);
294 }
295
296 /**
297 * Get the default permission for directory.
298 */
299 public static FsPermission getDirDefault() {
300 return new FsPermission((short)00777);
301 }
302
303 /**
304 * Get the default permission for file.
305 */
306 public static FsPermission getFileDefault() {
307 return new FsPermission((short)00666);
308 }
309
310 /**
311 * Get the default permission for cache pools.
312 */
313 public static FsPermission getCachePoolDefault() {
314 return new FsPermission((short)00755);
315 }
316
317 /**
318 * Create a FsPermission from a Unix symbolic permission string
319 * @param unixSymbolicPermission e.g. "-rw-rw-rw-"
320 */
321 public static FsPermission valueOf(String unixSymbolicPermission) {
322 if (unixSymbolicPermission == null) {
323 return null;
324 }
325 else if (unixSymbolicPermission.length() != MAX_PERMISSION_LENGTH) {
326 throw new IllegalArgumentException(String.format(
327 "length != %d(unixSymbolicPermission=%s)", MAX_PERMISSION_LENGTH,
328 unixSymbolicPermission));
329 }
330
331 int n = 0;
332 for(int i = 1; i < unixSymbolicPermission.length(); i++) {
333 n = n << 1;
334 char c = unixSymbolicPermission.charAt(i);
335 n += (c == '-' || c == 'T' || c == 'S') ? 0: 1;
336 }
337
338 // Add sticky bit value if set
339 if(unixSymbolicPermission.charAt(9) == 't' ||
340 unixSymbolicPermission.charAt(9) == 'T')
341 n += 01000;
342
343 return new FsPermission((short)n);
344 }
345
346 private static class ImmutableFsPermission extends FsPermission {
347 public ImmutableFsPermission(short permission) {
348 super(permission);
349 }
350 @Override
351 public FsPermission applyUMask(FsPermission umask) {
352 throw new UnsupportedOperationException();
353 }
354 @Override
355 public void readFields(DataInput in) throws IOException {
356 throw new UnsupportedOperationException();
357 }
358 }
359 }