1 /*
2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */

25
26 package java.io;
27
28 import java.nio.file.*;
29 import java.security.*;
30 import java.util.Enumeration;
31 import java.util.Objects;
32 import java.util.StringJoiner;
33 import java.util.Vector;
34 import java.util.concurrent.ConcurrentHashMap;
35
36 import jdk.internal.misc.JavaIOFilePermissionAccess;
37 import jdk.internal.misc.SharedSecrets;
38 import sun.nio.fs.DefaultFileSystemProvider;
39 import sun.security.action.GetPropertyAction;
40 import sun.security.util.FilePermCompat;
41 import sun.security.util.SecurityConstants;
42
43 /**
44  * This class represents access to a file or directory.  A FilePermission consists
45  * of a pathname and a set of actions valid for that pathname.
46  * <P>
47  * Pathname is the pathname of the file or directory granted the specified
48  * actions. A pathname that ends in "/*" (where "/" is
49  * the file separator character, <code>File.separatorChar</code>) indicates
50  * all the files and directories contained in that directory. A pathname
51  * that ends with "/-" indicates (recursively) all files
52  * and subdirectories contained in that directory. Such a pathname is called
53  * a wildcard pathname. Otherwise, it's a simple pathname.
54  * <P>
55  * A pathname consisting of the special token {@literal "<<ALL FILES>>"}
56  * matches <b>any</b> file.
57  * <P>
58  * Note: A pathname consisting of a single "*" indicates all the files
59  * in the current directory, while a pathname consisting of a single "-"
60  * indicates all the files in the current directory and
61  * (recursively) all files and subdirectories contained in the current
62  * directory.
63  * <P>
64  * The actions to be granted are passed to the constructor in a string containing
65  * a list of one or more comma-separated keywords. The possible keywords are
66  * "read""write""execute""delete", and "readlink". Their meaning is
67  * defined as follows:
68  *
69  * <DL>
70  *    <DT> read <DD> read permission
71  *    <DT> write <DD> write permission
72  *    <DT> execute
73  *    <DD> execute permission. Allows <code>Runtime.exec</code> to
74  *         be called. Corresponds to <code>SecurityManager.checkExec</code>.
75  *    <DT> delete
76  *    <DD> delete permission. Allows <code>File.delete</code> to
77  *         be called. Corresponds to <code>SecurityManager.checkDelete</code>.
78  *    <DT> readlink
79  *    <DD> read link permission. Allows the target of a
80  *         <a href="../nio/file/package-summary.html#links">symbolic link</a>
81  *         to be read by invoking the {@link java.nio.file.Files#readSymbolicLink
82  *         readSymbolicLink } method.
83  * </DL>
84  * <P>
85  * The actions string is converted to lowercase before processing.
86  * <P>
87  * Be careful when granting FilePermissions. Think about the implications
88  * of granting read and especially write access to various files and
89  * directories. The {@literal "<<ALL FILES>>"} permission with write action is
90  * especially dangerous. This grants permission to write to the entire
91  * file system. One thing this effectively allows is replacement of the
92  * system binary, including the JVM runtime environment.
93  * <P>
94  * Please note: Code can always read a file from the same
95  * directory it's in (or a subdirectory of that directory); it does not
96  * need explicit permission to do so.
97  *
98  * @see java.security.Permission
99  * @see java.security.Permissions
100  * @see java.security.PermissionCollection
101  *
102  *
103  * @author Marianne Mueller
104  * @author Roland Schemers
105  * @since 1.2
106  *
107  * @serial exclude
108  */

109
110 public final class FilePermission extends Permission implements Serializable {
111
112     /**
113      * Execute action.
114      */

115     private static final int EXECUTE = 0x1;
116     /**
117      * Write action.
118      */

119     private static final int WRITE   = 0x2;
120     /**
121      * Read action.
122      */

123     private static final int READ    = 0x4;
124     /**
125      * Delete action.
126      */

127     private static final int DELETE  = 0x8;
128     /**
129      * Read link action.
130      */

131     private static final int READLINK    = 0x10;
132
133     /**
134      * All actions (read,write,execute,delete,readlink)
135      */

136     private static final int ALL     = READ|WRITE|EXECUTE|DELETE|READLINK;
137     /**
138      * No actions.
139      */

140     private static final int NONE    = 0x0;
141
142     // the actions mask
143     private transient int mask;
144
145     // does path indicate a directory? (wildcard or recursive)
146     private transient boolean directory;
147
148     // is it a recursive directory specification?
149     private transient boolean recursive;
150
151     /**
152      * the actions string.
153      *
154      * @serial
155      */

156     private String actions; // Left null as long as possible, then
157                             // created and re-used in the getAction function.
158
159     // canonicalized dir path. used by the "old" behavior (nb == false).
160     // In the case of directories, it is the name "/blah/*" or "/blah/-"
161     // without the last character (the "*" or "-").
162
163     private transient String cpath;
164
165     // Following fields used by the "new" behavior (nb == true), in which
166     // input path is not canonicalized. For compatibility (so that granting
167     // FilePermission on "x" allows reading "`pwd`/x", an alternative path
168     // can be added so that both can be used in an implies() check. Please note
169     // the alternative path only deals with absolute/relative path, and does
170     // not deal with symlink/target.
171
172     private transient Path npath;       // normalized dir path.
173     private transient Path npath2;      // alternative normalized dir path.
174     private transient boolean allFiles; // whether this is <<ALL FILES>>
175     private transient boolean invalid;  // whether input path is invalid
176
177     // static Strings used by init(int mask)
178     private static final char RECURSIVE_CHAR = '-';
179     private static final char WILD_CHAR = '*';
180
181 //    public String toString() {
182 //        StringBuffer sb = new StringBuffer();
183 //        sb.append("*** FilePermission on " + getName() + " ***");
184 //        for (Field f : FilePermission.class.getDeclaredFields()) {
185 //            if (!Modifier.isStatic(f.getModifiers())) {
186 //                try {
187 //                    sb.append(f.getName() + " = " + f.get(this));
188 //                } catch (Exception e) {
189 //                    sb.append(f.getName() + " = " + e.toString());
190 //                }
191 //                sb.append('\n');
192 //            }
193 //        }
194 //        sb.append("***\n");
195 //        return sb.toString();
196 //    }
197
198     private static final long serialVersionUID = 7930732926638008763L;
199
200     /**
201      * Use the platform's default file system to avoid recursive initialization
202      * issues when the VM is configured to use a custom file system provider.
203      */

204     private static final java.nio.file.FileSystem builtInFS =
205         DefaultFileSystemProvider.theFileSystem();
206
207     private static final Path here = builtInFS.getPath(
208             GetPropertyAction.privilegedGetProperty("user.dir"));
209
210     private static final Path EMPTY_PATH = builtInFS.getPath("");
211     private static final Path DASH_PATH = builtInFS.getPath("-");
212     private static final Path DOTDOT_PATH = builtInFS.getPath("..");
213
214     /**
215      * A private constructor that clones some and updates some,
216      * always with a different name.
217      * @param input
218      */

219     private FilePermission(String name,
220                            FilePermission input,
221                            Path npath,
222                            Path npath2,
223                            int mask,
224                            String actions) {
225         super(name);
226         // Customizables
227         this.npath = npath;
228         this.npath2 = npath2;
229         this.actions = actions;
230         this.mask = mask;
231         // Cloneds
232         this.allFiles = input.allFiles;
233         this.invalid = input.invalid;
234         this.recursive = input.recursive;
235         this.directory = input.directory;
236         this.cpath = input.cpath;
237     }
238
239     /**
240      * Returns the alternative path as a Path object, i.e. absolute path
241      * for a relative one, or vice versa.
242      *
243      * @param in a real path w/o "-" or "*" at the end, and not <<ALL FILES>>.
244      * @return the alternative path, or null if cannot find one.
245      */

246     private static Path altPath(Path in) {
247         try {
248             if (!in.isAbsolute()) {
249                 return here.resolve(in).normalize();
250             } else {
251                 return here.relativize(in).normalize();
252             }
253         } catch (IllegalArgumentException e) {
254             return null;
255         }
256     }
257
258     static {
259         SharedSecrets.setJavaIOFilePermissionAccess(
260             /**
261              * Creates FilePermission objects with special internals.
262              * See {@link FilePermCompat#newPermPlusAltPath(Permission)} and
263              * {@link FilePermCompat#newPermUsingAltPath(Permission)}.
264              */

265             new JavaIOFilePermissionAccess() {
266                 public FilePermission newPermPlusAltPath(FilePermission input) {
267                     if (!input.invalid && input.npath2 == null && !input.allFiles) {
268                         Path npath2 = altPath(input.npath);
269                         if (npath2 != null) {
270                             // Please note the name of the new permission is
271                             // different than the original so that when one is
272                             // added to a FilePermissionCollection it will not
273                             // be merged with the original one.
274                             return new FilePermission(input.getName() + "#plus",
275                                     input,
276                                     input.npath,
277                                     npath2,
278                                     input.mask,
279                                     input.actions);
280                         }
281                     }
282                     return input;
283                 }
284                 public FilePermission newPermUsingAltPath(FilePermission input) {
285                     if (!input.invalid && !input.allFiles) {
286                         Path npath2 = altPath(input.npath);
287                         if (npath2 != null) {
288                             // New name, see above.
289                             return new FilePermission(input.getName() + "#using",
290                                     input,
291                                     npath2,
292                                     null,
293                                     input.mask,
294                                     input.actions);
295                         }
296                     }
297                     return null;
298                 }
299             }
300         );
301     }
302
303     /**
304      * initialize a FilePermission object. Common to all constructors.
305      * Also called during de-serialization.
306      *
307      * @param mask the actions mask to use.
308      *
309      */

310     private void init(int mask) {
311         if ((mask & ALL) != mask)
312                 throw new IllegalArgumentException("invalid actions mask");
313
314         if (mask == NONE)
315                 throw new IllegalArgumentException("invalid actions mask");
316
317         if (FilePermCompat.nb) {
318             String name = getName();
319
320             if (name == null)
321                 throw new NullPointerException("name can't be null");
322
323             this.mask = mask;
324
325             if (name.equals("<<ALL FILES>>")) {
326                 allFiles = true;
327                 npath = EMPTY_PATH;
328                 // other fields remain default
329                 return;
330             }
331
332             boolean rememberStar = false;
333             if (name.endsWith("*")) {
334                 rememberStar = true;
335                 recursive = false;
336                 name = name.substring(0, name.length()-1) + "-";
337             }
338
339             try {
340                 // new File() can "normalize" some name, for example, "/C:/X" on
341                 // Windows. Some JDK codes generate such illegal names.
342                 npath = builtInFS.getPath(new File(name).getPath())
343                         .normalize();
344                 // lastName should always be non-null now
345                 Path lastName = npath.getFileName();
346                 if (lastName != null && lastName.equals(DASH_PATH)) {
347                     directory = true;
348                     recursive = !rememberStar;
349                     npath = npath.getParent();
350                 }
351                 if (npath == null) {
352                     npath = EMPTY_PATH;
353                 }
354                 invalid = false;
355             } catch (InvalidPathException ipe) {
356                 // Still invalid. For compatibility reason, accept it
357                 // but make this permission useless.
358                 npath = builtInFS.getPath("-u-s-e-l-e-s-s-");
359                 invalid = true;
360             }
361
362         } else {
363             if ((cpath = getName()) == null)
364                 throw new NullPointerException("name can't be null");
365
366             this.mask = mask;
367
368             if (cpath.equals("<<ALL FILES>>")) {
369                 allFiles = true;
370                 directory = true;
371                 recursive = true;
372                 cpath = "";
373                 return;
374             }
375
376             // Validate path by platform's default file system
377             try {
378                 String name = cpath.endsWith("*") ? cpath.substring(0, cpath.length() - 1) + "-" : cpath;
379                 builtInFS.getPath(new File(name).getPath());
380             } catch (InvalidPathException ipe) {
381                 invalid = true;
382                 return;
383             }
384
385             // store only the canonical cpath if possible
386             cpath = AccessController.doPrivileged(new PrivilegedAction<>() {
387                 public String run() {
388                     try {
389                         String path = cpath;
390                         if (cpath.endsWith("*")) {
391                             // call getCanonicalPath with a path with wildcard character
392                             // replaced to avoid calling it with paths that are
393                             // intended to match all entries in a directory
394                             path = path.substring(0, path.length() - 1) + "-";
395                             path = new File(path).getCanonicalPath();
396                             return path.substring(0, path.length() - 1) + "*";
397                         } else {
398                             return new File(path).getCanonicalPath();
399                         }
400                     } catch (IOException ioe) {
401                         return cpath;
402                     }
403                 }
404             });
405
406             int len = cpath.length();
407             char last = ((len > 0) ? cpath.charAt(len - 1) : 0);
408
409             if (last == RECURSIVE_CHAR &&
410                     cpath.charAt(len - 2) == File.separatorChar) {
411                 directory = true;
412                 recursive = true;
413                 cpath = cpath.substring(0, --len);
414             } else if (last == WILD_CHAR &&
415                     cpath.charAt(len - 2) == File.separatorChar) {
416                 directory = true;
417                 //recursive = false;
418                 cpath = cpath.substring(0, --len);
419             } else {
420                 // overkill since they are initialized to false, but
421                 // commented out here to remind us...
422                 //directory = false;
423                 //recursive = false;
424             }
425
426             // XXX: at this point the path should be absolute. die if it isn't?
427         }
428     }
429
430     /**
431      * Creates a new FilePermission object with the specified actions.
432      * <i>path</i> is the pathname of a file or directory, and <i>actions</i>
433      * contains a comma-separated list of the desired actions granted on the
434      * file or directory. Possible actions are
435      * "read""write""execute""delete", and "readlink".
436      *
437      * <p>A pathname that ends in "/*" (where "/" is
438      * the file separator character, <code>File.separatorChar</code>)
439      * indicates all the files and directories contained in that directory.
440      * A pathname that ends with "/-" indicates (recursively) all files and
441      * subdirectories contained in that directory. The special pathname
442      * {@literal "<<ALL FILES>>"} matches any file.
443      *
444      * <p>A pathname consisting of a single "*" indicates all the files
445      * in the current directory, while a pathname consisting of a single "-"
446      * indicates all the files in the current directory and
447      * (recursively) all files and subdirectories contained in the current
448      * directory.
449      *
450      * <p>A pathname containing an empty string represents an empty path.
451      *
452      * @implNote In this implementation, the
453      * {@code jdk.io.permissionsUseCanonicalPath} system property dictates how
454      * the {@code path} argument is processed and stored.
455      * <P>
456      * If the value of the system property is set to {@code true}, {@code path}
457      * is canonicalized and stored as a String object named {@code cpath}.
458      * This means a relative path is converted to an absolute path, a Windows
459      * DOS-style 8.3 path is expanded to a long path, and a symbolic link is
460      * resolved to its target, etc.
461      * <P>
462      * If the value of the system property is set to {@code false}, {@code path}
463      * is converted to a {@link java.nio.file.Path} object named {@code npath}
464      * after {@link Path#normalize() normalization}. No canonicalization is
465      * performed which means the underlying file system is not accessed.
466      * If an {@link InvalidPathException} is thrown during the conversion,
467      * this {@code FilePermission} will be labeled as invalid.
468      * <P>
469      * In either case, the "*" or "-" character at the end of a wildcard
470      * {@code path} is removed before canonicalization or normalization.
471      * It is stored in a separate wildcard flag field.
472      * <P>
473      * The default value of the {@code jdk.io.permissionsUseCanonicalPath}
474      * system property is {@code false} in this implementation.
475      * <p>
476      * The value can also be set with a security property using the same name,
477      * but setting a system property will override the security property value.
478      *
479      * @param path the pathname of the file/directory.
480      * @param actions the action string.
481      *
482      * @throws IllegalArgumentException
483      *          If actions is <code>null</code>, empty or contains an action
484      *          other than the specified possible actions.
485      */

486     public FilePermission(String path, String actions) {
487         super(path);
488         init(getMask(actions));
489     }
490
491     /**
492      * Creates a new FilePermission object using an action mask.
493      * More efficient than the FilePermission(String, String) constructor.
494      * Can be used from within
495      * code that needs to create a FilePermission object to pass into the
496      * <code>implies</code> method.
497      *
498      * @param path the pathname of the file/directory.
499      * @param mask the action mask to use.
500      */

501     // package private for use by the FilePermissionCollection add method
502     FilePermission(String path, int mask) {
503         super(path);
504         init(mask);
505     }
506
507     /**
508      * Checks if this FilePermission object "implies" the specified permission.
509      * <P>
510      * More specifically, this method returns true if:
511      * <ul>
512      * <li> <i>p</i> is an instanceof FilePermission,
513      * <li> <i>p</i>'s actions are a proper subset of this
514      * object's actions, and
515      * <li> <i>p</i>'s pathname is implied by this object's
516      *      pathname. For example, "/tmp/*" implies "/tmp/foo", since
517      *      "/tmp/*" encompasses all files in the "/tmp" directory,
518      *      including the one named "foo".
519      * </ul>
520      * <P>
521      * Precisely, a simple pathname implies another simple pathname
522      * if and only if they are equal. A simple pathname never implies
523      * a wildcard pathname. A wildcard pathname implies another wildcard
524      * pathname if and only if all simple pathnames implied by the latter
525      * are implied by the former. A wildcard pathname implies a simple
526      * pathname if and only if
527      * <ul>
528      *     <li>if the wildcard flag is "*", the simple pathname's path
529      *     must be right inside the wildcard pathname's path.
530      *     <li>if the wildcard flag is "-", the simple pathname's path
531      *     must be recursively inside the wildcard pathname's path.
532      * </ul>
533      * <P>
534      * {@literal "<<ALL FILES>>"} implies every other pathname. No pathname,
535      * except for {@literal "<<ALL FILES>>"} itself, implies
536      * {@literal "<<ALL FILES>>"}.
537      *
538      * @implNote
539      * If {@code jdk.io.permissionsUseCanonicalPath} is {@code true}, a
540      * simple {@code cpath} is inside a wildcard {@code cpath} if and only if
541      * after removing the base name (the last name in the pathname's name
542      * sequence) from the former the remaining part equals to the latter,
543      * a simple {@code cpath} is recursively inside a wildcard {@code cpath}
544      * if and only if the former starts with the latter.
545      * <p>
546      * If {@code jdk.io.permissionsUseCanonicalPath} is {@code false}, a
547      * simple {@code npath} is inside a wildcard {@code npath} if and only if
548      * {@code  simple_npath.relativize(wildcard_npath)} is exactly "..",
549      * a simple {@code npath} is recursively inside a wildcard {@code npath}
550      * if and only if {@code simple_npath.relativize(wildcard_npath)} is a
551      * series of one or more "..". This means "/-" implies "/foo" but not "foo".
552      * <p>
553      * An invalid {@code FilePermission} does not imply any object except for
554      * itself. An invalid {@code FilePermission} is not implied by any object
555      * except for itself or a {@code FilePermission} on
556      * {@literal "<<ALL FILES>>"} whose actions is a superset of this
557      * invalid {@code FilePermission}. Even if two {@code FilePermission}
558      * are created with the same invalid path, one does not imply the other.
559      *
560      * @param p the permission to check against.
561      *
562      * @return <code>true</code> if the specified permission is not
563      *                  <code>null</code> and is implied by this object,
564      *                  <code>false</code> otherwise.
565      */

566     @Override
567     public boolean implies(Permission p) {
568         if (!(p instanceof FilePermission))
569             return false;
570
571         FilePermission that = (FilePermission) p;
572
573         // we get the effective mask. i.e., the "and" of this and that.
574         // They must be equal to that.mask for implies to return true.
575
576         return ((this.mask & that.mask) == that.mask) && impliesIgnoreMask(that);
577     }
578
579     /**
580      * Checks if the Permission's actions are a proper subset of the
581      * this object's actions. Returns the effective mask iff the
582      * this FilePermission's path also implies that FilePermission's path.
583      *
584      * @param that the FilePermission to check against.
585      * @return the effective mask
586      */

587     boolean impliesIgnoreMask(FilePermission that) {
588         if (this == that) {
589             return true;
590         }
591         if (allFiles) {
592             return true;
593         }
594         if (this.invalid || that.invalid) {
595             return false;
596         }
597         if (that.allFiles) {
598             return false;
599         }
600         if (FilePermCompat.nb) {
601             // Left at least same level of wildness as right
602             if ((this.recursive && that.recursive) != that.recursive
603                     || (this.directory && that.directory) != that.directory) {
604                 return false;
605             }
606             // Same npath is good as long as both or neither are directories
607             if (this.npath.equals(that.npath)
608                     && this.directory == that.directory) {
609                 return true;
610             }
611             int diff = containsPath(this.npath, that.npath);
612             // Right inside left is good if recursive
613             if (diff >= 1 && recursive) {
614                 return true;
615             }
616             // Right right inside left if it is element in set
617             if (diff == 1 && directory && !that.directory) {
618                 return true;
619             }
620
621             // Hack: if a npath2 field exists, apply the same checks
622             // on it as a fallback.
623             if (this.npath2 != null) {
624                 if (this.npath2.equals(that.npath)
625                         && this.directory == that.directory) {
626                     return true;
627                 }
628                 diff = containsPath(this.npath2, that.npath);
629                 if (diff >= 1 && recursive) {
630                     return true;
631                 }
632                 if (diff == 1 && directory && !that.directory) {
633                     return true;
634                 }
635             }
636
637             return false;
638         } else {
639             if (this.directory) {
640                 if (this.recursive) {
641                     // make sure that.path is longer then path so
642                     // something like /foo/- does not imply /foo
643                     if (that.directory) {
644                         return (that.cpath.length() >= this.cpath.length()) &&
645                                 that.cpath.startsWith(this.cpath);
646                     } else {
647                         return ((that.cpath.length() > this.cpath.length()) &&
648                                 that.cpath.startsWith(this.cpath));
649                     }
650                 } else {
651                     if (that.directory) {
652                         // if the permission passed in is a directory
653                         // specification, make sure that a non-recursive
654                         // permission (i.e., this object) can't imply a recursive
655                         // permission.
656                         if (that.recursive)
657                             return false;
658                         else
659                             return (this.cpath.equals(that.cpath));
660                     } else {
661                         int last = that.cpath.lastIndexOf(File.separatorChar);
662                         if (last == -1)
663                             return false;
664                         else {
665                             // this.cpath.equals(that.cpath.substring(0, last+1));
666                             // Use regionMatches to avoid creating new string
667                             return (this.cpath.length() == (last + 1)) &&
668                                     this.cpath.regionMatches(0, that.cpath, 0, last + 1);
669                         }
670                     }
671                 }
672             } else if (that.directory) {
673                 // if this is NOT recursive/wildcarded,
674                 // do not let it imply a recursive/wildcarded permission
675                 return false;
676             } else {
677                 return (this.cpath.equals(that.cpath));
678             }
679         }
680     }
681
682     /**
683      * Returns the depth between an outer path p1 and an inner path p2. -1
684      * is returned if
685      *
686      * - p1 does not contains p2.
687      * - this is not decidable. For example, p1="../x", p2="y".
688      * - the depth is not decidable. For example, p1="/", p2="x".
689      *
690      * This method can return 2 if the depth is greater than 2.
691      *
692      * @param p1 the expected outer path, normalized
693      * @param p2 the expected inner path, normalized
694      * @return the depth in between
695      */

696     private static int containsPath(Path p1, Path p2) {
697
698         // Two paths must have the same root. For example,
699         // there is no contains relation between any two of
700         // "/x""x""C:/x""C:x", and "//host/share/x".
701         if (!Objects.equals(p1.getRoot(), p2.getRoot())) {
702             return -1;
703         }
704
705         // Empty path (i.e. "." or "") is a strange beast,
706         // because its getNameCount()==1 but getName(0) is null.
707         // It's better to deal with it separately.
708         if (p1.equals(EMPTY_PATH)) {
709             if (p2.equals(EMPTY_PATH)) {
710                 return 0;
711             } else if (p2.getName(0).equals(DOTDOT_PATH)) {
712                 // "." contains p2 iff p2 has no "..". Since
713                 // a normalized path can only have 0 or more
714                 // ".." at the beginning. We only need to look
715                 // at the head.
716                 return -1;
717             } else {
718                 // and the distance is p2's name count. i.e.
719                 // 3 between "." and "a/b/c".
720                 return p2.getNameCount();
721             }
722         } else if (p2.equals(EMPTY_PATH)) {
723             int c1 = p1.getNameCount();
724             if (!p1.getName(c1 - 1).equals(DOTDOT_PATH)) {
725                 // "." is inside p1 iff p1 is 1 or more "..".
726                 // For the same reason above, we only need to
727                 // look at the tail.
728                 return -1;
729             }
730             // and the distance is the count of ".."
731             return c1;
732         }
733
734         // Good. No more empty paths.
735
736         // Common heads are removed
737
738         int c1 = p1.getNameCount();
739         int c2 = p2.getNameCount();
740
741         int n = Math.min(c1, c2);
742         int i = 0;
743         while (i < n) {
744             if (!p1.getName(i).equals(p2.getName(i)))
745                 break;
746             i++;
747         }
748
749         // for p1 containing p2, p1 must be 0-or-more "..",
750         // and p2 cannot have "..". For the same reason, we only
751         // check tail of p1 and head of p2.
752         if (i < c1 && !p1.getName(c1 - 1).equals(DOTDOT_PATH)) {
753             return -1;
754         }
755
756         if (i < c2 && p2.getName(i).equals(DOTDOT_PATH)) {
757             return -1;
758         }
759
760         // and the distance is the name counts added (after removing
761         // the common heads).
762
763         // For example: p1 = "../../..", p2 = "../a".
764         // After removing the common heads, they become "../.." and "a",
765         // and the distance is (3-1)+(2-1) = 3.
766         return c1 - i + c2 - i;
767     }
768
769     /**
770      * Checks two FilePermission objects for equality. Checks that <i>obj</i> is
771      * a FilePermission, and has the same pathname and actions as this object.
772      *
773      * @implNote More specifically, two pathnames are the same if and only if
774      * they have the same wildcard flag and their {@code cpath}
775      * (if {@code jdk.io.permissionsUseCanonicalPath} is {@code true}) or
776      * {@code npath} (if {@code jdk.io.permissionsUseCanonicalPath}
777      * is {@code false}) are equal. Or they are both {@literal "<<ALL FILES>>"}.
778      * <p>
779      * When {@code jdk.io.permissionsUseCanonicalPath} is {@code false}, an
780      * invalid {@code FilePermission} does not equal to any object except
781      * for itself, even if they are created using the same invalid path.
782      *
783      * @param obj the object we are testing for equality with this object.
784      * @return <code>true</code> if obj is a FilePermission, and has the same
785      *          pathname and actions as this FilePermission object,
786      *          <code>false</code> otherwise.
787      */

788     @Override
789     public boolean equals(Object obj) {
790         if (obj == this)
791             return true;
792
793         if (! (obj instanceof FilePermission))
794             return false;
795
796         FilePermission that = (FilePermission) obj;
797
798         if (this.invalid || that.invalid) {
799             return false;
800         }
801         if (FilePermCompat.nb) {
802             return (this.mask == that.mask) &&
803                     (this.allFiles == that.allFiles) &&
804                     this.npath.equals(that.npath) &&
805                     Objects.equals(npath2, that.npath2) &&
806                     (this.directory == that.directory) &&
807                     (this.recursive == that.recursive);
808         } else {
809             return (this.mask == that.mask) &&
810                     (this.allFiles == that.allFiles) &&
811                     this.cpath.equals(that.cpath) &&
812                     (this.directory == that.directory) &&
813                     (this.recursive == that.recursive);
814         }
815     }
816
817     /**
818      * Returns the hash code value for this object.
819      *
820      * @return a hash code value for this object.
821      */

822     @Override
823     public int hashCode() {
824         if (FilePermCompat.nb) {
825             return Objects.hash(
826                     mask, allFiles, directory, recursive, npath, npath2, invalid);
827         } else {
828             return 0;
829         }
830     }
831
832     /**
833      * Converts an actions String to an actions mask.
834      *
835      * @param actions the action string.
836      * @return the actions mask.
837      */

838     private static int getMask(String actions) {
839         int mask = NONE;
840
841         // Null action valid?
842         if (actions == null) {
843             return mask;
844         }
845
846         // Use object identity comparison against known-interned strings for
847         // performance benefit (these values are used heavily within the JDK).
848         if (actions == SecurityConstants.FILE_READ_ACTION) {
849             return READ;
850         } else if (actions == SecurityConstants.FILE_WRITE_ACTION) {
851             return WRITE;
852         } else if (actions == SecurityConstants.FILE_EXECUTE_ACTION) {
853             return EXECUTE;
854         } else if (actions == SecurityConstants.FILE_DELETE_ACTION) {
855             return DELETE;
856         } else if (actions == SecurityConstants.FILE_READLINK_ACTION) {
857             return READLINK;
858         }
859
860         char[] a = actions.toCharArray();
861
862         int i = a.length - 1;
863         if (i < 0)
864             return mask;
865
866         while (i != -1) {
867             char c;
868
869             // skip whitespace
870             while ((i!=-1) && ((c = a[i]) == ' ' ||
871                                c == '\r' ||
872                                c == '\n' ||
873                                c == '\f' ||
874                                c == '\t'))
875                 i--;
876
877             // check for the known strings
878             int matchlen;
879
880             if (i >= 3 && (a[i-3] == 'r' || a[i-3] == 'R') &&
881                           (a[i-2] == 'e' || a[i-2] == 'E') &&
882                           (a[i-1] == 'a' || a[i-1] == 'A') &&
883                           (a[i] == 'd' || a[i] == 'D'))
884             {
885                 matchlen = 4;
886                 mask |= READ;
887
888             } else if (i >= 4 && (a[i-4] == 'w' || a[i-4] == 'W') &&
889                                  (a[i-3] == 'r' || a[i-3] == 'R') &&
890                                  (a[i-2] == 'i' || a[i-2] == 'I') &&
891                                  (a[i-1] == 't' || a[i-1] == 'T') &&
892                                  (a[i] == 'e' || a[i] == 'E'))
893             {
894                 matchlen = 5;
895                 mask |= WRITE;
896
897             } else if (i >= 6 && (a[i-6] == 'e' || a[i-6] == 'E') &&
898                                  (a[i-5] == 'x' || a[i-5] == 'X') &&
899                                  (a[i-4] == 'e' || a[i-4] == 'E') &&
900                                  (a[i-3] == 'c' || a[i-3] == 'C') &&
901                                  (a[i-2] == 'u' || a[i-2] == 'U') &&
902                                  (a[i-1] == 't' || a[i-1] == 'T') &&
903                                  (a[i] == 'e' || a[i] == 'E'))
904             {
905                 matchlen = 7;
906                 mask |= EXECUTE;
907
908             } else if (i >= 5 && (a[i-5] == 'd' || a[i-5] == 'D') &&
909                                  (a[i-4] == 'e' || a[i-4] == 'E') &&
910                                  (a[i-3] == 'l' || a[i-3] == 'L') &&
911                                  (a[i-2] == 'e' || a[i-2] == 'E') &&
912                                  (a[i-1] == 't' || a[i-1] == 'T') &&
913                                  (a[i] == 'e' || a[i] == 'E'))
914             {
915                 matchlen = 6;
916                 mask |= DELETE;
917
918             } else if (i >= 7 && (a[i-7] == 'r' || a[i-7] == 'R') &&
919                                  (a[i-6] == 'e' || a[i-6] == 'E') &&
920                                  (a[i-5] == 'a' || a[i-5] == 'A') &&
921                                  (a[i-4] == 'd' || a[i-4] == 'D') &&
922                                  (a[i-3] == 'l' || a[i-3] == 'L') &&
923                                  (a[i-2] == 'i' || a[i-2] == 'I') &&
924                                  (a[i-1] == 'n' || a[i-1] == 'N') &&
925                                  (a[i] == 'k' || a[i] == 'K'))
926             {
927                 matchlen = 8;
928                 mask |= READLINK;
929
930             } else {
931                 // parse error
932                 throw new IllegalArgumentException(
933                         "invalid permission: " + actions);
934             }
935
936             // make sure we didn't just match the tail of a word
937             // like "ackbarfaccept".  Also, skip to the comma.
938             boolean seencomma = false;
939             while (i >= matchlen && !seencomma) {
940                 switch(a[i-matchlen]) {
941                 case ',':
942                     seencomma = true;
943                     break;
944                 case ' ': case '\r': case '\n':
945                 case '\f': case '\t':
946                     break;
947                 default:
948                     throw new IllegalArgumentException(
949                             "invalid permission: " + actions);
950                 }
951                 i--;
952             }
953
954             // point i at the location of the comma minus one (or -1).
955             i -= matchlen;
956         }
957
958         return mask;
959     }
960
961     /**
962      * Return the current action mask. Used by the FilePermissionCollection.
963      *
964      * @return the actions mask.
965      */

966     int getMask() {
967         return mask;
968     }
969
970     /**
971      * Return the canonical string representation of the actions.
972      * Always returns present actions in the following order:
973      * read, write, execute, delete, readlink.
974      *
975      * @return the canonical string representation of the actions.
976      */

977     private static String getActions(int mask) {
978         StringJoiner sj = new StringJoiner(",");
979
980         if ((mask & READ) == READ) {
981             sj.add("read");
982         }
983         if ((mask & WRITE) == WRITE) {
984             sj.add("write");
985         }
986         if ((mask & EXECUTE) == EXECUTE) {
987             sj.add("execute");
988         }
989         if ((mask & DELETE) == DELETE) {
990             sj.add("delete");
991         }
992         if ((mask & READLINK) == READLINK) {
993             sj.add("readlink");
994         }
995
996         return sj.toString();
997     }
998
999     /**
1000      * Returns the "canonical string representation" of the actions.
1001      * That is, this method always returns present actions in the following order:
1002      * read, write, execute, delete, readlink. For example, if this FilePermission
1003      * object allows both write and read actions, a call to <code>getActions</code>
1004      * will return the string "read,write".
1005      *
1006      * @return the canonical string representation of the actions.
1007      */

1008     @Override
1009     public String getActions() {
1010         if (actions == null)
1011             actions = getActions(this.mask);
1012
1013         return actions;
1014     }
1015
1016     /**
1017      * Returns a new PermissionCollection object for storing FilePermission
1018      * objects.
1019      * <p>
1020      * FilePermission objects must be stored in a manner that allows them
1021      * to be inserted into the collection in any order, but that also enables the
1022      * PermissionCollection <code>implies</code>
1023      * method to be implemented in an efficient (and consistent) manner.
1024      *
1025      * <p>For example, if you have two FilePermissions:
1026      * <OL>
1027      * <LI>  <code>"/tmp/-""read"</code>
1028      * <LI>  <code>"/tmp/scratch/foo""write"</code>
1029      * </OL>
1030      *
1031      * <p>and you are calling the <code>implies</code> method with the FilePermission:
1032      *
1033      * <pre>
1034      *   "/tmp/scratch/foo""read,write",
1035      * </pre>
1036      *
1037      * then the <code>implies</code> function must
1038      * take into account both the "/tmp/-" and "/tmp/scratch/foo"
1039      * permissions, so the effective permission is "read,write",
1040      * and <code>implies</code> returns true. The "implies" semantics for
1041      * FilePermissions are handled properly by the PermissionCollection object
1042      * returned by this <code>newPermissionCollection</code> method.
1043      *
1044      * @return a new PermissionCollection object suitable for storing
1045      * FilePermissions.
1046      */

1047     @Override
1048     public PermissionCollection newPermissionCollection() {
1049         return new FilePermissionCollection();
1050     }
1051
1052     /**
1053      * WriteObject is called to save the state of the FilePermission
1054      * to a stream. The actions are serialized, and the superclass
1055      * takes care of the name.
1056      */

1057     private void writeObject(ObjectOutputStream s)
1058         throws IOException
1059     {
1060         // Write out the actions. The superclass takes care of the name
1061         // call getActions to make sure actions field is initialized
1062         if (actions == null)
1063             getActions();
1064         s.defaultWriteObject();
1065     }
1066
1067     /**
1068      * readObject is called to restore the state of the FilePermission from
1069      * a stream.
1070      */

1071     private void readObject(ObjectInputStream s)
1072          throws IOException, ClassNotFoundException
1073     {
1074         // Read in the actions, then restore everything else by calling init.
1075         s.defaultReadObject();
1076         init(getMask(actions));
1077     }
1078
1079     /**
1080      * Create a cloned FilePermission with a different actions.
1081      * @param effective the new actions
1082      * @return a new object
1083      */

1084     FilePermission withNewActions(int effective) {
1085         return new FilePermission(this.getName(),
1086                 this,
1087                 this.npath,
1088                 this.npath2,
1089                 effective,
1090                 null);
1091     }
1092 }
1093
1094 /**
1095  * A FilePermissionCollection stores a set of FilePermission permissions.
1096  * FilePermission objects
1097  * must be stored in a manner that allows them to be inserted in any
1098  * order, but enable the implies function to evaluate the implies
1099  * method.
1100  * For example, if you have two FilePermissions:
1101  * <OL>
1102  * <LI> "/tmp/-""read"
1103  * <LI> "/tmp/scratch/foo""write"
1104  * </OL>
1105  * And you are calling the implies function with the FilePermission:
1106  * "/tmp/scratch/foo""read,write", then the implies function must
1107  * take into account both the /tmp/- and /tmp/scratch/foo
1108  * permissions, so the effective permission is "read,write".
1109  *
1110  * @see java.security.Permission
1111  * @see java.security.Permissions
1112  * @see java.security.PermissionCollection
1113  *
1114  *
1115  * @author Marianne Mueller
1116  * @author Roland Schemers
1117  *
1118  * @serial include
1119  *
1120  */

1121
1122 final class FilePermissionCollection extends PermissionCollection
1123     implements Serializable
1124 {
1125     // Not serialized; see serialization section at end of class
1126     private transient ConcurrentHashMap<String, Permission> perms;
1127
1128     /**
1129      * Create an empty FilePermissionCollection object.
1130      */

1131     public FilePermissionCollection() {
1132         perms = new ConcurrentHashMap<>();
1133     }
1134
1135     /**
1136      * Adds a permission to the FilePermissionCollection. The key for the hash is
1137      * permission.path.
1138      *
1139      * @param permission the Permission object to add.
1140      *
1141      * @exception IllegalArgumentException - if the permission is not a
1142      *                                       FilePermission
1143      *
1144      * @exception SecurityException - if this FilePermissionCollection object
1145      *                                has been marked readonly
1146      */

1147     @Override
1148     public void add(Permission permission) {
1149         if (! (permission instanceof FilePermission))
1150             throw new IllegalArgumentException("invalid permission: "+
1151                                                permission);
1152         if (isReadOnly())
1153             throw new SecurityException(
1154                 "attempt to add a Permission to a readonly PermissionCollection");
1155
1156         FilePermission fp = (FilePermission)permission;
1157
1158         // Add permission to map if it is absent, or replace with new
1159         // permission if applicable.
1160         perms.merge(fp.getName(), fp,
1161             new java.util.function.BiFunction<>() {
1162                 @Override
1163                 public Permission apply(Permission existingVal,
1164                                         Permission newVal) {
1165                     int oldMask = ((FilePermission)existingVal).getMask();
1166                     int newMask = ((FilePermission)newVal).getMask();
1167                     if (oldMask != newMask) {
1168                         int effective = oldMask | newMask;
1169                         if (effective == newMask) {
1170                             return newVal;
1171                         }
1172                         if (effective != oldMask) {
1173                             return ((FilePermission)newVal)
1174                                     .withNewActions(effective);
1175                         }
1176                     }
1177                     return existingVal;
1178                 }
1179             }
1180         );
1181     }
1182
1183     /**
1184      * Check and see if this set of permissions implies the permissions
1185      * expressed in "permission".
1186      *
1187      * @param permission the Permission object to compare
1188      *
1189      * @return true if "permission" is a proper subset of a permission in
1190      * the set, false if not.
1191      */

1192     @Override
1193     public boolean implies(Permission permission) {
1194         if (! (permission instanceof FilePermission))
1195             return false;
1196
1197         FilePermission fperm = (FilePermission) permission;
1198
1199         int desired = fperm.getMask();
1200         int effective = 0;
1201         int needed = desired;
1202
1203         for (Permission perm : perms.values()) {
1204             FilePermission fp = (FilePermission)perm;
1205             if (((needed & fp.getMask()) != 0) && fp.impliesIgnoreMask(fperm)) {
1206                 effective |= fp.getMask();
1207                 if ((effective & desired) == desired) {
1208                     return true;
1209                 }
1210                 needed = (desired ^ effective);
1211             }
1212         }
1213         return false;
1214     }
1215
1216     /**
1217      * Returns an enumeration of all the FilePermission objects in the
1218      * container.
1219      *
1220      * @return an enumeration of all the FilePermission objects.
1221      */

1222     @Override
1223     public Enumeration<Permission> elements() {
1224         return perms.elements();
1225     }
1226
1227     private static final long serialVersionUID = 2202956749081564585L;
1228
1229     // Need to maintain serialization interoperability with earlier releases,
1230     // which had the serializable field:
1231     //    private Vector permissions;
1232
1233     /**
1234      * @serialField permissions java.util.Vector
1235      *     A list of FilePermission objects.
1236      */

1237     private static final ObjectStreamField[] serialPersistentFields = {
1238         new ObjectStreamField("permissions", Vector.class),
1239     };
1240
1241     /**
1242      * @serialData "permissions" field (a Vector containing the FilePermissions).
1243      */

1244     /*
1245      * Writes the contents of the perms field out as a Vector for
1246      * serialization compatibility with earlier releases.
1247      */

1248     private void writeObject(ObjectOutputStream out) throws IOException {
1249         // Don't call out.defaultWriteObject()
1250
1251         // Write out Vector
1252         Vector<Permission> permissions = new Vector<>(perms.values());
1253
1254         ObjectOutputStream.PutField pfields = out.putFields();
1255         pfields.put("permissions", permissions);
1256         out.writeFields();
1257     }
1258
1259     /*
1260      * Reads in a Vector of FilePermissions and saves them in the perms field.
1261      */

1262     private void readObject(ObjectInputStream in)
1263         throws IOException, ClassNotFoundException
1264     {
1265         // Don't call defaultReadObject()
1266
1267         // Read in serialized fields
1268         ObjectInputStream.GetField gfields = in.readFields();
1269
1270         // Get the one we want
1271         @SuppressWarnings("unchecked")
1272         Vector<Permission> permissions = (Vector<Permission>)gfields.get("permissions"null);
1273         perms = new ConcurrentHashMap<>(permissions.size());
1274         for (Permission perm : permissions) {
1275             perms.put(perm.getName(), perm);
1276         }
1277     }
1278 }
1279