Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/java/io/FilePermission.java
41152 views
1
/*
2
* Copyright (c) 1997, 2021, 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.access.JavaIOFilePermissionAccess;
37
import jdk.internal.access.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}) 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} to
74
* be called. Corresponds to {@code SecurityManager.checkExec}.
75
* <DT> delete
76
* <DD> delete permission. Allows {@code File.delete} to
77
* be called. Corresponds to {@code SecurityManager.checkDelete}.
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
@java.io.Serial
199
private static final long serialVersionUID = 7930732926638008763L;
200
201
/**
202
* Use the platform's default file system to avoid recursive initialization
203
* issues when the VM is configured to use a custom file system provider.
204
*/
205
private static final java.nio.file.FileSystem builtInFS =
206
DefaultFileSystemProvider.theFileSystem();
207
208
private static final Path here = builtInFS.getPath(
209
GetPropertyAction.privilegedGetProperty("user.dir"));
210
211
private static final Path EMPTY_PATH = builtInFS.getPath("");
212
private static final Path DASH_PATH = builtInFS.getPath("-");
213
private static final Path DOTDOT_PATH = builtInFS.getPath("..");
214
215
/**
216
* A private constructor that clones some and updates some,
217
* always with a different name.
218
* @param input
219
*/
220
private FilePermission(String name,
221
FilePermission input,
222
Path npath,
223
Path npath2,
224
int mask,
225
String actions) {
226
super(name);
227
// Customizables
228
this.npath = npath;
229
this.npath2 = npath2;
230
this.actions = actions;
231
this.mask = mask;
232
// Cloneds
233
this.allFiles = input.allFiles;
234
this.invalid = input.invalid;
235
this.recursive = input.recursive;
236
this.directory = input.directory;
237
this.cpath = input.cpath;
238
}
239
240
/**
241
* Returns the alternative path as a Path object, i.e. absolute path
242
* for a relative one, or vice versa.
243
*
244
* @param in a real path w/o "-" or "*" at the end, and not <<ALL FILES>>.
245
* @return the alternative path, or null if cannot find one.
246
*/
247
private static Path altPath(Path in) {
248
try {
249
if (!in.isAbsolute()) {
250
return here.resolve(in).normalize();
251
} else {
252
return here.relativize(in).normalize();
253
}
254
} catch (IllegalArgumentException e) {
255
return null;
256
}
257
}
258
259
static {
260
SharedSecrets.setJavaIOFilePermissionAccess(
261
/**
262
* Creates FilePermission objects with special internals.
263
* See {@link FilePermCompat#newPermPlusAltPath(Permission)} and
264
* {@link FilePermCompat#newPermUsingAltPath(Permission)}.
265
*/
266
new JavaIOFilePermissionAccess() {
267
public FilePermission newPermPlusAltPath(FilePermission input) {
268
if (!input.invalid && input.npath2 == null && !input.allFiles) {
269
Path npath2 = altPath(input.npath);
270
if (npath2 != null) {
271
// Please note the name of the new permission is
272
// different than the original so that when one is
273
// added to a FilePermissionCollection it will not
274
// be merged with the original one.
275
return new FilePermission(input.getName() + "#plus",
276
input,
277
input.npath,
278
npath2,
279
input.mask,
280
input.actions);
281
}
282
}
283
return input;
284
}
285
public FilePermission newPermUsingAltPath(FilePermission input) {
286
if (!input.invalid && !input.allFiles) {
287
Path npath2 = altPath(input.npath);
288
if (npath2 != null) {
289
// New name, see above.
290
return new FilePermission(input.getName() + "#using",
291
input,
292
npath2,
293
null,
294
input.mask,
295
input.actions);
296
}
297
}
298
return null;
299
}
300
}
301
);
302
}
303
304
/**
305
* initialize a FilePermission object. Common to all constructors.
306
* Also called during de-serialization.
307
*
308
* @param mask the actions mask to use.
309
*
310
*/
311
@SuppressWarnings("removal")
312
private void init(int mask) {
313
if ((mask & ALL) != mask)
314
throw new IllegalArgumentException("invalid actions mask");
315
316
if (mask == NONE)
317
throw new IllegalArgumentException("invalid actions mask");
318
319
if (FilePermCompat.nb) {
320
String name = getName();
321
322
if (name == null)
323
throw new NullPointerException("name can't be null");
324
325
this.mask = mask;
326
327
if (name.equals("<<ALL FILES>>")) {
328
allFiles = true;
329
npath = EMPTY_PATH;
330
// other fields remain default
331
return;
332
}
333
334
boolean rememberStar = false;
335
if (name.endsWith("*")) {
336
rememberStar = true;
337
recursive = false;
338
name = name.substring(0, name.length()-1) + "-";
339
}
340
341
try {
342
// new File() can "normalize" some name, for example, "/C:/X" on
343
// Windows. Some JDK codes generate such illegal names.
344
npath = builtInFS.getPath(new File(name).getPath())
345
.normalize();
346
// lastName should always be non-null now
347
Path lastName = npath.getFileName();
348
if (lastName != null && lastName.equals(DASH_PATH)) {
349
directory = true;
350
recursive = !rememberStar;
351
npath = npath.getParent();
352
}
353
if (npath == null) {
354
npath = EMPTY_PATH;
355
}
356
invalid = false;
357
} catch (InvalidPathException ipe) {
358
// Still invalid. For compatibility reason, accept it
359
// but make this permission useless.
360
npath = builtInFS.getPath("-u-s-e-l-e-s-s-");
361
invalid = true;
362
}
363
364
} else {
365
if ((cpath = getName()) == null)
366
throw new NullPointerException("name can't be null");
367
368
this.mask = mask;
369
370
if (cpath.equals("<<ALL FILES>>")) {
371
allFiles = true;
372
directory = true;
373
recursive = true;
374
cpath = "";
375
return;
376
}
377
378
// Validate path by platform's default file system
379
try {
380
String name = cpath.endsWith("*") ? cpath.substring(0, cpath.length() - 1) + "-" : cpath;
381
builtInFS.getPath(new File(name).getPath());
382
} catch (InvalidPathException ipe) {
383
invalid = true;
384
return;
385
}
386
387
// store only the canonical cpath if possible
388
cpath = AccessController.doPrivileged(new PrivilegedAction<>() {
389
public String run() {
390
try {
391
String path = cpath;
392
if (cpath.endsWith("*")) {
393
// call getCanonicalPath with a path with wildcard character
394
// replaced to avoid calling it with paths that are
395
// intended to match all entries in a directory
396
path = path.substring(0, path.length() - 1) + "-";
397
path = new File(path).getCanonicalPath();
398
return path.substring(0, path.length() - 1) + "*";
399
} else {
400
return new File(path).getCanonicalPath();
401
}
402
} catch (IOException ioe) {
403
return cpath;
404
}
405
}
406
});
407
408
int len = cpath.length();
409
char last = ((len > 0) ? cpath.charAt(len - 1) : 0);
410
411
if (last == RECURSIVE_CHAR &&
412
cpath.charAt(len - 2) == File.separatorChar) {
413
directory = true;
414
recursive = true;
415
cpath = cpath.substring(0, --len);
416
} else if (last == WILD_CHAR &&
417
cpath.charAt(len - 2) == File.separatorChar) {
418
directory = true;
419
//recursive = false;
420
cpath = cpath.substring(0, --len);
421
} else {
422
// overkill since they are initialized to false, but
423
// commented out here to remind us...
424
//directory = false;
425
//recursive = false;
426
}
427
428
// XXX: at this point the path should be absolute. die if it isn't?
429
}
430
}
431
432
/**
433
* Creates a new FilePermission object with the specified actions.
434
* <i>path</i> is the pathname of a file or directory, and <i>actions</i>
435
* contains a comma-separated list of the desired actions granted on the
436
* file or directory. Possible actions are
437
* "read", "write", "execute", "delete", and "readlink".
438
*
439
* <p>A pathname that ends in "/*" (where "/" is
440
* the file separator character, {@code File.separatorChar})
441
* indicates all the files and directories contained in that directory.
442
* A pathname that ends with "/-" indicates (recursively) all files and
443
* subdirectories contained in that directory. The special pathname
444
* {@literal "<<ALL FILES>>"} matches any file.
445
*
446
* <p>A pathname consisting of a single "*" indicates all the files
447
* in the current directory, while a pathname consisting of a single "-"
448
* indicates all the files in the current directory and
449
* (recursively) all files and subdirectories contained in the current
450
* directory.
451
*
452
* <p>A pathname containing an empty string represents an empty path.
453
*
454
* @implNote In this implementation, the
455
* {@systemProperty jdk.io.permissionsUseCanonicalPath} system property
456
* dictates how the {@code path} argument is processed and stored.
457
* <P>
458
* If the value of the system property is set to {@code true}, {@code path}
459
* is canonicalized and stored as a String object named {@code cpath}.
460
* This means a relative path is converted to an absolute path, a Windows
461
* DOS-style 8.3 path is expanded to a long path, and a symbolic link is
462
* resolved to its target, etc.
463
* <P>
464
* If the value of the system property is set to {@code false}, {@code path}
465
* is converted to a {@link java.nio.file.Path} object named {@code npath}
466
* after {@link Path#normalize() normalization}. No canonicalization is
467
* performed which means the underlying file system is not accessed.
468
* If an {@link InvalidPathException} is thrown during the conversion,
469
* this {@code FilePermission} will be labeled as invalid.
470
* <P>
471
* In either case, the "*" or "-" character at the end of a wildcard
472
* {@code path} is removed before canonicalization or normalization.
473
* It is stored in a separate wildcard flag field.
474
* <P>
475
* The default value of the {@code jdk.io.permissionsUseCanonicalPath}
476
* system property is {@code false} in this implementation.
477
* <p>
478
* The value can also be set with a security property using the same name,
479
* but setting a system property will override the security property value.
480
*
481
* @param path the pathname of the file/directory.
482
* @param actions the action string.
483
*
484
* @throws IllegalArgumentException if actions is {@code null}, empty,
485
* malformed or contains an action other than the specified
486
* possible actions
487
*/
488
public FilePermission(String path, String actions) {
489
super(path);
490
init(getMask(actions));
491
}
492
493
/**
494
* Creates a new FilePermission object using an action mask.
495
* More efficient than the FilePermission(String, String) constructor.
496
* Can be used from within
497
* code that needs to create a FilePermission object to pass into the
498
* {@code implies} method.
499
*
500
* @param path the pathname of the file/directory.
501
* @param mask the action mask to use.
502
*/
503
// package private for use by the FilePermissionCollection add method
504
FilePermission(String path, int mask) {
505
super(path);
506
init(mask);
507
}
508
509
/**
510
* Checks if this FilePermission object "implies" the specified permission.
511
* <P>
512
* More specifically, this method returns true if:
513
* <ul>
514
* <li> <i>p</i> is an instanceof FilePermission,
515
* <li> <i>p</i>'s actions are a proper subset of this
516
* object's actions, and
517
* <li> <i>p</i>'s pathname is implied by this object's
518
* pathname. For example, "/tmp/*" implies "/tmp/foo", since
519
* "/tmp/*" encompasses all files in the "/tmp" directory,
520
* including the one named "foo".
521
* </ul>
522
* <P>
523
* Precisely, a simple pathname implies another simple pathname
524
* if and only if they are equal. A simple pathname never implies
525
* a wildcard pathname. A wildcard pathname implies another wildcard
526
* pathname if and only if all simple pathnames implied by the latter
527
* are implied by the former. A wildcard pathname implies a simple
528
* pathname if and only if
529
* <ul>
530
* <li>if the wildcard flag is "*", the simple pathname's path
531
* must be right inside the wildcard pathname's path.
532
* <li>if the wildcard flag is "-", the simple pathname's path
533
* must be recursively inside the wildcard pathname's path.
534
* </ul>
535
* <P>
536
* {@literal "<<ALL FILES>>"} implies every other pathname. No pathname,
537
* except for {@literal "<<ALL FILES>>"} itself, implies
538
* {@literal "<<ALL FILES>>"}.
539
*
540
* @implNote
541
* If {@code jdk.io.permissionsUseCanonicalPath} is {@code true}, a
542
* simple {@code cpath} is inside a wildcard {@code cpath} if and only if
543
* after removing the base name (the last name in the pathname's name
544
* sequence) from the former the remaining part is equal to the latter,
545
* a simple {@code cpath} is recursively inside a wildcard {@code cpath}
546
* if and only if the former starts with the latter.
547
* <p>
548
* If {@code jdk.io.permissionsUseCanonicalPath} is {@code false}, a
549
* simple {@code npath} is inside a wildcard {@code npath} if and only if
550
* {@code simple_npath.relativize(wildcard_npath)} is exactly "..",
551
* a simple {@code npath} is recursively inside a wildcard {@code npath}
552
* if and only if {@code simple_npath.relativize(wildcard_npath)} is a
553
* series of one or more "..". This means "/-" implies "/foo" but not "foo".
554
* <p>
555
* An invalid {@code FilePermission} does not imply any object except for
556
* itself. An invalid {@code FilePermission} is not implied by any object
557
* except for itself or a {@code FilePermission} on
558
* {@literal "<<ALL FILES>>"} whose actions is a superset of this
559
* invalid {@code FilePermission}. Even if two {@code FilePermission}
560
* are created with the same invalid path, one does not imply the other.
561
*
562
* @param p the permission to check against.
563
*
564
* @return {@code true} if the specified permission is not
565
* {@code null} and is implied by this object,
566
* {@code false} otherwise.
567
*/
568
@Override
569
public boolean implies(Permission p) {
570
if (!(p instanceof FilePermission that))
571
return false;
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} if obj is a FilePermission, and has the same
785
* pathname and actions as this FilePermission object,
786
* {@code false} otherwise.
787
*/
788
@Override
789
public boolean equals(Object obj) {
790
if (obj == this)
791
return true;
792
793
if (! (obj instanceof FilePermission that))
794
return false;
795
796
if (this.invalid || that.invalid) {
797
return false;
798
}
799
if (FilePermCompat.nb) {
800
return (this.mask == that.mask) &&
801
(this.allFiles == that.allFiles) &&
802
this.npath.equals(that.npath) &&
803
Objects.equals(npath2, that.npath2) &&
804
(this.directory == that.directory) &&
805
(this.recursive == that.recursive);
806
} else {
807
return (this.mask == that.mask) &&
808
(this.allFiles == that.allFiles) &&
809
this.cpath.equals(that.cpath) &&
810
(this.directory == that.directory) &&
811
(this.recursive == that.recursive);
812
}
813
}
814
815
/**
816
* Returns the hash code value for this object.
817
*
818
* @return a hash code value for this object.
819
*/
820
@Override
821
public int hashCode() {
822
if (FilePermCompat.nb) {
823
return Objects.hash(
824
mask, allFiles, directory, recursive, npath, npath2, invalid);
825
} else {
826
return 0;
827
}
828
}
829
830
/**
831
* Converts an actions String to an actions mask.
832
*
833
* @param actions the action string.
834
* @return the actions mask.
835
*/
836
private static int getMask(String actions) {
837
int mask = NONE;
838
839
// Null action valid?
840
if (actions == null) {
841
return mask;
842
}
843
844
// Use object identity comparison against known-interned strings for
845
// performance benefit (these values are used heavily within the JDK).
846
if (actions == SecurityConstants.FILE_READ_ACTION) {
847
return READ;
848
} else if (actions == SecurityConstants.FILE_WRITE_ACTION) {
849
return WRITE;
850
} else if (actions == SecurityConstants.FILE_EXECUTE_ACTION) {
851
return EXECUTE;
852
} else if (actions == SecurityConstants.FILE_DELETE_ACTION) {
853
return DELETE;
854
} else if (actions == SecurityConstants.FILE_READLINK_ACTION) {
855
return READLINK;
856
}
857
858
char[] a = actions.toCharArray();
859
860
int i = a.length - 1;
861
if (i < 0)
862
return mask;
863
864
while (i != -1) {
865
char c;
866
867
// skip whitespace
868
while ((i!=-1) && ((c = a[i]) == ' ' ||
869
c == '\r' ||
870
c == '\n' ||
871
c == '\f' ||
872
c == '\t'))
873
i--;
874
875
// check for the known strings
876
int matchlen;
877
878
if (i >= 3 && (a[i-3] == 'r' || a[i-3] == 'R') &&
879
(a[i-2] == 'e' || a[i-2] == 'E') &&
880
(a[i-1] == 'a' || a[i-1] == 'A') &&
881
(a[i] == 'd' || a[i] == 'D'))
882
{
883
matchlen = 4;
884
mask |= READ;
885
886
} else if (i >= 4 && (a[i-4] == 'w' || a[i-4] == 'W') &&
887
(a[i-3] == 'r' || a[i-3] == 'R') &&
888
(a[i-2] == 'i' || a[i-2] == 'I') &&
889
(a[i-1] == 't' || a[i-1] == 'T') &&
890
(a[i] == 'e' || a[i] == 'E'))
891
{
892
matchlen = 5;
893
mask |= WRITE;
894
895
} else if (i >= 6 && (a[i-6] == 'e' || a[i-6] == 'E') &&
896
(a[i-5] == 'x' || a[i-5] == 'X') &&
897
(a[i-4] == 'e' || a[i-4] == 'E') &&
898
(a[i-3] == 'c' || a[i-3] == 'C') &&
899
(a[i-2] == 'u' || a[i-2] == 'U') &&
900
(a[i-1] == 't' || a[i-1] == 'T') &&
901
(a[i] == 'e' || a[i] == 'E'))
902
{
903
matchlen = 7;
904
mask |= EXECUTE;
905
906
} else if (i >= 5 && (a[i-5] == 'd' || a[i-5] == 'D') &&
907
(a[i-4] == 'e' || a[i-4] == 'E') &&
908
(a[i-3] == 'l' || a[i-3] == 'L') &&
909
(a[i-2] == 'e' || a[i-2] == 'E') &&
910
(a[i-1] == 't' || a[i-1] == 'T') &&
911
(a[i] == 'e' || a[i] == 'E'))
912
{
913
matchlen = 6;
914
mask |= DELETE;
915
916
} else if (i >= 7 && (a[i-7] == 'r' || a[i-7] == 'R') &&
917
(a[i-6] == 'e' || a[i-6] == 'E') &&
918
(a[i-5] == 'a' || a[i-5] == 'A') &&
919
(a[i-4] == 'd' || a[i-4] == 'D') &&
920
(a[i-3] == 'l' || a[i-3] == 'L') &&
921
(a[i-2] == 'i' || a[i-2] == 'I') &&
922
(a[i-1] == 'n' || a[i-1] == 'N') &&
923
(a[i] == 'k' || a[i] == 'K'))
924
{
925
matchlen = 8;
926
mask |= READLINK;
927
928
} else {
929
// parse error
930
throw new IllegalArgumentException(
931
"invalid permission: " + actions);
932
}
933
934
// make sure we didn't just match the tail of a word
935
// like "ackbarfdelete". Also, skip to the comma.
936
boolean seencomma = false;
937
while (i >= matchlen && !seencomma) {
938
switch (c = a[i-matchlen]) {
939
case ' ': case '\r': case '\n':
940
case '\f': case '\t':
941
break;
942
default:
943
if (c == ',' && i > matchlen) {
944
seencomma = true;
945
break;
946
}
947
throw new IllegalArgumentException(
948
"invalid permission: " + actions);
949
}
950
i--;
951
}
952
953
// point i at the location of the comma minus one (or -1).
954
i -= matchlen;
955
}
956
957
return mask;
958
}
959
960
/**
961
* Return the current action mask. Used by the FilePermissionCollection.
962
*
963
* @return the actions mask.
964
*/
965
int getMask() {
966
return mask;
967
}
968
969
/**
970
* Return the canonical string representation of the actions.
971
* Always returns present actions in the following order:
972
* read, write, execute, delete, readlink.
973
*
974
* @return the canonical string representation of the actions.
975
*/
976
private static String getActions(int mask) {
977
StringJoiner sj = new StringJoiner(",");
978
979
if ((mask & READ) == READ) {
980
sj.add("read");
981
}
982
if ((mask & WRITE) == WRITE) {
983
sj.add("write");
984
}
985
if ((mask & EXECUTE) == EXECUTE) {
986
sj.add("execute");
987
}
988
if ((mask & DELETE) == DELETE) {
989
sj.add("delete");
990
}
991
if ((mask & READLINK) == READLINK) {
992
sj.add("readlink");
993
}
994
995
return sj.toString();
996
}
997
998
/**
999
* Returns the "canonical string representation" of the actions.
1000
* That is, this method always returns present actions in the following order:
1001
* read, write, execute, delete, readlink. For example, if this FilePermission
1002
* object allows both write and read actions, a call to {@code getActions}
1003
* will return the string "read,write".
1004
*
1005
* @return the canonical string representation of the actions.
1006
*/
1007
@Override
1008
public String getActions() {
1009
if (actions == null)
1010
actions = getActions(this.mask);
1011
1012
return actions;
1013
}
1014
1015
/**
1016
* Returns a new PermissionCollection object for storing FilePermission
1017
* objects.
1018
* <p>
1019
* FilePermission objects must be stored in a manner that allows them
1020
* to be inserted into the collection in any order, but that also enables the
1021
* PermissionCollection {@code implies}
1022
* method to be implemented in an efficient (and consistent) manner.
1023
*
1024
* <p>For example, if you have two FilePermissions:
1025
* <OL>
1026
* <LI> {@code "/tmp/-", "read"}
1027
* <LI> {@code "/tmp/scratch/foo", "write"}
1028
* </OL>
1029
*
1030
* <p>and you are calling the {@code implies} method with the FilePermission:
1031
*
1032
* <pre>
1033
* "/tmp/scratch/foo", "read,write",
1034
* </pre>
1035
*
1036
* then the {@code implies} function must
1037
* take into account both the "/tmp/-" and "/tmp/scratch/foo"
1038
* permissions, so the effective permission is "read,write",
1039
* and {@code implies} returns true. The "implies" semantics for
1040
* FilePermissions are handled properly by the PermissionCollection object
1041
* returned by this {@code newPermissionCollection} method.
1042
*
1043
* @return a new PermissionCollection object suitable for storing
1044
* FilePermissions.
1045
*/
1046
@Override
1047
public PermissionCollection newPermissionCollection() {
1048
return new FilePermissionCollection();
1049
}
1050
1051
/**
1052
* WriteObject is called to save the state of the FilePermission
1053
* to a stream. The actions are serialized, and the superclass
1054
* takes care of the name.
1055
*/
1056
@java.io.Serial
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
@java.io.Serial
1072
private void readObject(ObjectInputStream s)
1073
throws IOException, ClassNotFoundException
1074
{
1075
// Read in the actions, then restore everything else by calling init.
1076
s.defaultReadObject();
1077
init(getMask(actions));
1078
}
1079
1080
/**
1081
* Create a cloned FilePermission with a different actions.
1082
* @param effective the new actions
1083
* @return a new object
1084
*/
1085
FilePermission withNewActions(int effective) {
1086
return new FilePermission(this.getName(),
1087
this,
1088
this.npath,
1089
this.npath2,
1090
effective,
1091
null);
1092
}
1093
}
1094
1095
/**
1096
* A FilePermissionCollection stores a set of FilePermission permissions.
1097
* FilePermission objects
1098
* must be stored in a manner that allows them to be inserted in any
1099
* order, but enable the implies function to evaluate the implies
1100
* method.
1101
* For example, if you have two FilePermissions:
1102
* <OL>
1103
* <LI> "/tmp/-", "read"
1104
* <LI> "/tmp/scratch/foo", "write"
1105
* </OL>
1106
* And you are calling the implies function with the FilePermission:
1107
* "/tmp/scratch/foo", "read,write", then the implies function must
1108
* take into account both the /tmp/- and /tmp/scratch/foo
1109
* permissions, so the effective permission is "read,write".
1110
*
1111
* @see java.security.Permission
1112
* @see java.security.Permissions
1113
* @see java.security.PermissionCollection
1114
*
1115
*
1116
* @author Marianne Mueller
1117
* @author Roland Schemers
1118
*
1119
* @serial include
1120
*
1121
*/
1122
1123
final class FilePermissionCollection extends PermissionCollection
1124
implements Serializable
1125
{
1126
// Not serialized; see serialization section at end of class
1127
private transient ConcurrentHashMap<String, Permission> perms;
1128
1129
/**
1130
* Create an empty FilePermissionCollection object.
1131
*/
1132
public FilePermissionCollection() {
1133
perms = new ConcurrentHashMap<>();
1134
}
1135
1136
/**
1137
* Adds a permission to the FilePermissionCollection. The key for the hash is
1138
* permission.path.
1139
*
1140
* @param permission the Permission object to add.
1141
*
1142
* @throws IllegalArgumentException if the permission is not a
1143
* FilePermission
1144
*
1145
* @throws SecurityException if this FilePermissionCollection object
1146
* has been marked readonly
1147
*/
1148
@Override
1149
public void add(Permission permission) {
1150
if (! (permission instanceof FilePermission fp))
1151
throw new IllegalArgumentException("invalid permission: "+
1152
permission);
1153
if (isReadOnly())
1154
throw new SecurityException(
1155
"attempt to add a Permission to a readonly PermissionCollection");
1156
1157
// Add permission to map if it is absent, or replace with new
1158
// permission if applicable.
1159
perms.merge(fp.getName(), fp,
1160
new java.util.function.BiFunction<>() {
1161
@Override
1162
public Permission apply(Permission existingVal,
1163
Permission newVal) {
1164
int oldMask = ((FilePermission)existingVal).getMask();
1165
int newMask = ((FilePermission)newVal).getMask();
1166
if (oldMask != newMask) {
1167
int effective = oldMask | newMask;
1168
if (effective == newMask) {
1169
return newVal;
1170
}
1171
if (effective != oldMask) {
1172
return ((FilePermission)newVal)
1173
.withNewActions(effective);
1174
}
1175
}
1176
return existingVal;
1177
}
1178
}
1179
);
1180
}
1181
1182
/**
1183
* Check and see if this set of permissions implies the permissions
1184
* expressed in "permission".
1185
*
1186
* @param permission the Permission object to compare
1187
*
1188
* @return true if "permission" is a proper subset of a permission in
1189
* the set, false if not.
1190
*/
1191
@Override
1192
public boolean implies(Permission permission) {
1193
if (! (permission instanceof FilePermission fperm))
1194
return false;
1195
1196
int desired = fperm.getMask();
1197
int effective = 0;
1198
int needed = desired;
1199
1200
for (Permission perm : perms.values()) {
1201
FilePermission fp = (FilePermission)perm;
1202
if (((needed & fp.getMask()) != 0) && fp.impliesIgnoreMask(fperm)) {
1203
effective |= fp.getMask();
1204
if ((effective & desired) == desired) {
1205
return true;
1206
}
1207
needed = (desired & ~effective);
1208
}
1209
}
1210
return false;
1211
}
1212
1213
/**
1214
* Returns an enumeration of all the FilePermission objects in the
1215
* container.
1216
*
1217
* @return an enumeration of all the FilePermission objects.
1218
*/
1219
@Override
1220
public Enumeration<Permission> elements() {
1221
return perms.elements();
1222
}
1223
1224
@java.io.Serial
1225
private static final long serialVersionUID = 2202956749081564585L;
1226
1227
// Need to maintain serialization interoperability with earlier releases,
1228
// which had the serializable field:
1229
// private Vector permissions;
1230
1231
/**
1232
* @serialField permissions java.util.Vector
1233
* A list of FilePermission objects.
1234
*/
1235
@java.io.Serial
1236
private static final ObjectStreamField[] serialPersistentFields = {
1237
new ObjectStreamField("permissions", Vector.class),
1238
};
1239
1240
/**
1241
* @serialData "permissions" field (a Vector containing the FilePermissions).
1242
*/
1243
/**
1244
* Writes the contents of the perms field out as a Vector for
1245
* serialization compatibility with earlier releases.
1246
*
1247
* @param out the {@code ObjectOutputStream} to which data is written
1248
* @throws IOException if an I/O error occurs
1249
*/
1250
@java.io.Serial
1251
private void writeObject(ObjectOutputStream out) throws IOException {
1252
// Don't call out.defaultWriteObject()
1253
1254
// Write out Vector
1255
Vector<Permission> permissions = new Vector<>(perms.values());
1256
1257
ObjectOutputStream.PutField pfields = out.putFields();
1258
pfields.put("permissions", permissions);
1259
out.writeFields();
1260
}
1261
1262
/**
1263
* Reads in a Vector of FilePermissions and saves them in the perms field.
1264
*
1265
* @param in the {@code ObjectInputStream} from which data is read
1266
* @throws IOException if an I/O error occurs
1267
* @throws ClassNotFoundException if a serialized class cannot be loaded
1268
*/
1269
@java.io.Serial
1270
private void readObject(ObjectInputStream in)
1271
throws IOException, ClassNotFoundException
1272
{
1273
// Don't call defaultReadObject()
1274
1275
// Read in serialized fields
1276
ObjectInputStream.GetField gfields = in.readFields();
1277
1278
// Get the one we want
1279
@SuppressWarnings("unchecked")
1280
Vector<Permission> permissions = (Vector<Permission>)gfields.get("permissions", null);
1281
perms = new ConcurrentHashMap<>(permissions.size());
1282
for (Permission perm : permissions) {
1283
perms.put(perm.getName(), perm);
1284
}
1285
}
1286
}
1287
1288