/
FilePath.java
3733 lines (3402 loc) · 147 KB
/
FilePath.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Eric Lefevre-Ardant, Erik Ramfelt, Michael B. Donohue, Alan Harder,
* Manufacture Francaise des Pneumatiques Michelin, Romain Seguy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson;
import static hudson.FilePath.TarCompression.GZIP;
import static hudson.Util.fileToPath;
import static hudson.Util.fixEmpty;
import com.google.common.annotations.VisibleForTesting;
import com.jcraft.jzlib.GZIPInputStream;
import com.jcraft.jzlib.GZIPOutputStream;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Launcher.LocalLauncher;
import hudson.Launcher.RemoteLauncher;
import hudson.model.AbstractProject;
import hudson.model.Computer;
import hudson.model.Item;
import hudson.model.TaskListener;
import hudson.os.PosixException;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
import hudson.remoting.DelegatingCallable;
import hudson.remoting.Future;
import hudson.remoting.LocalChannel;
import hudson.remoting.Pipe;
import hudson.remoting.RemoteInputStream;
import hudson.remoting.RemoteInputStream.Flag;
import hudson.remoting.RemoteOutputStream;
import hudson.remoting.VirtualChannel;
import hudson.remoting.Which;
import hudson.security.AccessControlled;
import hudson.slaves.WorkspaceList;
import hudson.util.DaemonThreadFactory;
import hudson.util.DirScanner;
import hudson.util.ExceptionCatchingThreadFactory;
import hudson.util.FileVisitor;
import hudson.util.FormValidation;
import hudson.util.HeadBufferingStream;
import hudson.util.IOUtils;
import hudson.util.NamingThreadFactory;
import hudson.util.io.Archiver;
import hudson.util.io.ArchiverFactory;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.FileSystemException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jenkins.FilePathFilter;
import jenkins.MasterToSlaveFileCallable;
import jenkins.SlaveToMasterFileCallable;
import jenkins.SoloFilePathFilter;
import jenkins.model.Jenkins;
import jenkins.security.MasterToSlaveCallable;
import jenkins.util.ContextResettingExecutorService;
import jenkins.util.SystemProperties;
import jenkins.util.VirtualFile;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.input.CountingInputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.jenkinsci.remoting.RoleChecker;
import org.jenkinsci.remoting.RoleSensitive;
import org.jenkinsci.remoting.SerializableOnlyOverRemoting;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Stapler;
/**
* {@link File} like object with remoting support.
*
* <p>
* Unlike {@link File}, which always implies a file path on the current computer,
* {@link FilePath} represents a file path on a specific agent or the controller.
*
* Despite that, {@link FilePath} can be used much like {@link File}. It exposes
* a bunch of operations (and we should add more operations as long as they are
* generally useful), and when invoked against a file on a remote node, {@link FilePath}
* executes the necessary code remotely, thereby providing semi-transparent file
* operations.
*
* <h2>Using {@link FilePath} smartly</h2>
* <p>
* The transparency makes it easy to write plugins without worrying too much about
* remoting, by making it works like NFS, where remoting happens at the file-system
* layer.
*
* <p>
* But one should note that such use of remoting may not be optional. Sometimes,
* it makes more sense to move some computation closer to the data, as opposed to
* move the data to the computation. For example, if you are just computing a MD5
* digest of a file, then it would make sense to do the digest on the host where
* the file is located, as opposed to send the whole data to the controller and do MD5
* digesting there.
*
* <p>
* {@link FilePath} supports this "code migration" by in the
* {@link #act(FileCallable)} method. One can pass in a custom implementation
* of {@link FileCallable}, to be executed on the node where the data is located.
* The following code shows the example:
*
* <pre>
* void someMethod(FilePath file) {
* // make 'file' a fresh empty directory.
* file.act(new Freshen());
* }
* // if 'file' is on a different node, this FileCallable will
* // be transferred to that node and executed there.
* private static final class Freshen implements FileCallable<Void> {
* private static final long serialVersionUID = 1;
* @Override public Void invoke(File f, VirtualChannel channel) {
* // f and file represent the same thing
* f.deleteContents();
* f.mkdirs();
* return null;
* }
* }
* </pre>
*
* <p>
* When {@link FileCallable} is transferred to a remote node, it will be done so
* by using the same Java serialization scheme that the remoting module uses.
* See {@link Channel} for more about this.
*
* <p>
* {@link FilePath} itself can be sent over to a remote node as a part of {@link Callable}
* serialization. For example, sending a {@link FilePath} of a remote node to that
* node causes {@link FilePath} to become "local". Similarly, sending a
* {@link FilePath} that represents the local computer causes it to become "remote."
*
* @author Kohsuke Kawaguchi
* @see VirtualFile
*/
public final class FilePath implements SerializableOnlyOverRemoting {
/**
* Maximum http redirects we will follow. This defaults to the same number as Firefox/Chrome tolerates.
*/
private static final int MAX_REDIRECTS = 20;
/**
* Escape hatch for some additional protections against sending callables intended to be locally used only
*/
private static /* non-final for Groovy */ boolean REJECT_LOCAL_CALLABLE_DESERIALIZATION = SystemProperties.getBoolean(FilePath.class.getName() + ".rejectLocalCallableDeserialization", true);
/**
* When this {@link FilePath} represents the remote path,
* this field is always non-null on the controller (the field represents
* the channel to the remote agent.) When transferred to a agent via remoting,
* this field reverts back to null, since it's transient.
*
* When this {@link FilePath} represents a path on the controller,
* this field is null on the controller. When transferred to a agent via remoting,
* this field becomes non-null, representing the {@link Channel}
* back to the controller.
*
* This is used to determine whether we are running on the controller / the built-in node, or an agent.
*/
private transient VirtualChannel channel;
/**
* Represent the path to the file in the controller or the agent
* Since the platform of the agent might be different, can't use java.io.File
*
* The field could not be final since it's modified in {@link #readResolve()}
*/
private /*final*/ String remote;
/**
* Creates a {@link FilePath} that represents a path on the given node.
*
* @param channel
* To create a path that represents a remote path, pass in a {@link Channel}
* that's connected to that machine. If {@code null}, that means the local file path.
*/
public FilePath(@CheckForNull VirtualChannel channel, @NonNull String remote) {
this.channel = channel instanceof LocalChannel ? null : channel;
this.remote = normalize(remote);
}
/**
* To create {@link FilePath} that represents a "local" path.
*
* <p>
* A "local" path means a file path on the computer where the
* constructor invocation happened.
*/
public FilePath(@NonNull File localPath) {
this.channel = null;
this.remote = normalize(localPath.getPath());
}
/**
* Construct a path starting with a base location.
* @param base starting point for resolution, and defines channel
* @param rel a path which if relative will be resolved against base
*/
public FilePath(@NonNull FilePath base, @NonNull String rel) {
this.channel = base.channel;
this.remote = normalize(resolvePathIfRelative(base, rel));
}
private Object readResolve() {
this.remote = normalize(this.remote);
return this;
}
private String resolvePathIfRelative(@NonNull FilePath base, @NonNull String rel) {
if(isAbsolute(rel)) return rel;
if(base.isUnix()) {
// shouldn't need this replace, but better safe than sorry
return base.remote+'/'+rel.replace('\\','/');
} else {
// need this replace, see Slave.getWorkspaceFor and AbstractItem.getFullName, nested jobs on Windows
// agents will always have a rel containing at least one '/' character. JENKINS-13649
return base.remote+'\\'+rel.replace('/','\\');
}
}
/**
* Is the given path name an absolute path?
*/
private static boolean isAbsolute(@NonNull String rel) {
return rel.startsWith("/") || DRIVE_PATTERN.matcher(rel).matches() || UNC_PATTERN.matcher(rel).matches();
}
private static final Pattern DRIVE_PATTERN = Pattern.compile("[A-Za-z]:[\\\\/].*"),
UNC_PATTERN = Pattern.compile("^\\\\\\\\.*"),
ABSOLUTE_PREFIX_PATTERN = Pattern.compile("^(\\\\\\\\|(?:[A-Za-z]:)?[\\\\/])[\\\\/]*");
/**
* {@link File#getParent()} etc cannot handle ".." and "." in the path component very well,
* so remove them.
*/
@Restricted(NoExternalUse.class)
public static String normalize(@NonNull String path) {
StringBuilder buf = new StringBuilder();
// Check for prefix designating absolute path
Matcher m = ABSOLUTE_PREFIX_PATTERN.matcher(path);
if (m.find()) {
buf.append(m.group(1));
path = path.substring(m.end());
}
boolean isAbsolute = buf.length() > 0;
// Split remaining path into tokens, trimming any duplicate or trailing separators
List<String> tokens = new ArrayList<>();
int s = 0, end = path.length();
for (int i = 0; i < end; i++) {
char c = path.charAt(i);
if (c == '/' || c == '\\') {
tokens.add(path.substring(s, i));
s = i;
// Skip any extra separator chars
//noinspection StatementWithEmptyBody
while (++i < end && ((c = path.charAt(i)) == '/' || c == '\\'))
;
// Add token for separator unless we reached the end
if (i < end) tokens.add(path.substring(s, s+1));
s = i;
}
}
if (s < end) tokens.add(path.substring(s));
// Look through tokens for "." or ".."
for (int i = 0; i < tokens.size();) {
String token = tokens.get(i);
if (token.equals(".")) {
tokens.remove(i);
if (tokens.size() > 0)
tokens.remove(i > 0 ? i - 1 : i);
} else if (token.equals("..")) {
if (i == 0) {
// If absolute path, just remove: /../something
// If relative path, not collapsible so leave as-is
tokens.remove(0);
if (tokens.size() > 0) token += tokens.remove(0);
if (!isAbsolute) buf.append(token);
} else {
// Normalize: remove something/.. plus separator before/after
i -= 2;
for (int j = 0; j < 3; j++) tokens.remove(i);
if (i > 0) tokens.remove(i-1);
else if (tokens.size() > 0) tokens.remove(0);
}
} else
i += 2;
}
// Recombine tokens
for (String token : tokens) buf.append(token);
if (buf.length() == 0) buf.append('.');
return buf.toString();
}
/**
* Checks if the remote path is Unix.
*/
boolean isUnix() {
// if the path represents a local path, there' no need to guess.
if(!isRemote())
return File.pathSeparatorChar!=';';
// note that we can't use the usual File.pathSeparator and etc., as the OS of
// the machine where this code runs and the OS that this FilePath refers to may be different.
// Windows absolute path is 'X:\...', so this is usually a good indication of Windows path
if(remote.length()>3 && remote.charAt(1)==':' && remote.charAt(2)=='\\')
return false;
// Windows can handle '/' as a path separator but Unix can't,
// so err on Unix side
return !remote.contains("\\");
}
/**
* Gets the full path of the file on the remote machine.
*
*/
public String getRemote() {
return remote;
}
/**
* Creates a zip file from this directory or a file and sends that to the given output stream.
*
* @deprecated as of 1.315. Use {@link #zip(OutputStream)} that has more consistent name.
*/
@Deprecated
public void createZipArchive(OutputStream os) throws IOException, InterruptedException {
zip(os);
}
/**
* Creates a zip file from this directory or a file and sends that to the given output stream.
*/
public void zip(OutputStream os) throws IOException, InterruptedException {
zip(os,(FileFilter)null);
}
public void zip(FilePath dst) throws IOException, InterruptedException {
try (OutputStream os = dst.write()) {
zip(os);
}
}
/**
* Creates a zip file from this directory by using the specified filter,
* and sends the result to the given output stream.
*
* @param filter
* Must be serializable since it may be executed remotely. Can be null to add all files.
*
* @since 1.315
*/
public void zip(OutputStream os, FileFilter filter) throws IOException, InterruptedException {
archive(ArchiverFactory.ZIP,os,filter);
}
/**
* Creates a zip file from this directory by only including the files that match the given glob.
*
* @param glob
* Ant style glob, like "**/*.xml". If empty or null, this method
* works like {@link #createZipArchive(OutputStream)}
*
* @since 1.129
* @deprecated as of 1.315
* Use {@link #zip(OutputStream,String)} that has more consistent name.
*/
@Deprecated
public void createZipArchive(OutputStream os, final String glob) throws IOException, InterruptedException {
archive(ArchiverFactory.ZIP,os,glob);
}
/**
* Creates a zip file from this directory by only including the files that match the given glob.
*
* @param glob
* Ant style glob, like "**/*.xml". If empty or null, this method
* works like {@link #createZipArchive(OutputStream)}, inserting a top-level directory into the ZIP.
*
* @since 1.315
*/
public void zip(OutputStream os, final String glob) throws IOException, InterruptedException {
archive(ArchiverFactory.ZIP,os,glob);
}
/**
* Uses the given scanner on 'this' directory to list up files and then archive it to a zip stream.
*/
public int zip(OutputStream out, DirScanner scanner) throws IOException, InterruptedException {
return archive(ArchiverFactory.ZIP, out, scanner);
}
/**
* Uses the given scanner on 'this' directory to list up files and then archive it to a zip stream.
*
* @param out The OutputStream to write the zip into.
* @param scanner A DirScanner for scanning the directory and filtering its contents.
* @param verificationRoot A root or base directory for checking for any symlinks in this files parentage.
* Any symlinks between a file and root should be ignored.
* Symlinks in the parentage outside root will not be checked.
* @param noFollowLinks true if it should not follow links.
* @param prefix The portion of file path that will be added at the beginning of the relative path inside the archive.
* If non-empty, a trailing forward slash will be enforced.
*
* @return The number of files/directories archived.
* This is only really useful to check for a situation where nothing
*/
@Restricted(NoExternalUse.class)
public int zip(OutputStream out, DirScanner scanner, String verificationRoot, boolean noFollowLinks, String prefix) throws IOException, InterruptedException {
ArchiverFactory archiverFactory = noFollowLinks ? ArchiverFactory.createZipWithoutSymlink(prefix) : ArchiverFactory.ZIP;
return archive(archiverFactory, out, scanner, verificationRoot, noFollowLinks);
}
/**
* Archives this directory into the specified archive format, to the given {@link OutputStream}, by using
* {@link DirScanner} to choose what files to include.
*
* @return
* number of files/directories archived. This is only really useful to check for a situation where nothing
* is archived.
*/
public int archive(final ArchiverFactory factory, OutputStream os, final DirScanner scanner) throws IOException, InterruptedException {
return archive(factory, os, scanner, null, false);
}
/**
* Archives this directory into the specified archive format, to the given {@link OutputStream}, by using
* {@link DirScanner} to choose what files to include.
*
* @param factory The ArchiverFactory for creating the archive.
* @param os The OutputStream to write the zip into.
* @param verificationRoot A root or base directory for checking for any symlinks in this files parentage.
* Any symlinks between a file and root should be ignored.
* Symlinks in the parentage outside root will not be checked.
* @param noFollowLinks true if it should not follow links.
*
* @return The number of files/directories archived.
* This is only really useful to check for a situation where nothing
*/
@Restricted(NoExternalUse.class)
public int archive(final ArchiverFactory factory, OutputStream os, final DirScanner scanner,
String verificationRoot, boolean noFollowLinks) throws IOException, InterruptedException {
final OutputStream out = channel != null ? new RemoteOutputStream(os) : os;
return act(new Archive(factory, out, scanner, verificationRoot, noFollowLinks));
}
private static class Archive extends SecureFileCallable<Integer> {
private final ArchiverFactory factory;
private final OutputStream out;
private final DirScanner scanner;
private final String verificationRoot;
private final boolean noFollowLinks;
Archive(ArchiverFactory factory, OutputStream out, DirScanner scanner, String verificationRoot, boolean noFollowLinks) {
this.factory = factory;
this.out = out;
this.scanner = scanner;
this.verificationRoot = verificationRoot;
this.noFollowLinks = noFollowLinks;
}
@Override
public Integer invoke(File f, VirtualChannel channel) throws IOException {
Archiver a = factory.create(out);
try {
scanner.scan(f, ignoringSymlinks(reading(a), verificationRoot, noFollowLinks));
} finally {
a.close();
}
return a.countEntries();
}
private static final long serialVersionUID = 1L;
}
public int archive(final ArchiverFactory factory, OutputStream os, final FileFilter filter) throws IOException, InterruptedException {
return archive(factory,os,new DirScanner.Filter(filter));
}
public int archive(final ArchiverFactory factory, OutputStream os, final String glob) throws IOException, InterruptedException {
return archive(factory,os,new DirScanner.Glob(glob,null));
}
/**
* When this {@link FilePath} represents a zip file, extracts that zip file.
*
* @param target
* Target directory to expand files to. All the necessary directories will be created.
* @since 1.248
* @see #unzipFrom(InputStream)
*/
public void unzip(final FilePath target) throws IOException, InterruptedException {
// TODO: post release, re-unite two branches by introducing FileStreamCallable that resolves InputStream
if (channel != target.channel) {// local -> remote or remote->local
final RemoteInputStream in = new RemoteInputStream(read(), Flag.GREEDY);
target.act(new UnzipRemote(in));
} else {// local -> local or remote->remote
target.act(new UnzipLocal(this));
}
}
private static class UnzipRemote extends SecureFileCallable<Void> {
private final RemoteInputStream in;
UnzipRemote(RemoteInputStream in) {
this.in = in;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
unzip(dir, in);
return null;
}
private static final long serialVersionUID = 1L;
}
private static class UnzipLocal extends SecureFileCallable<Void> {
private final FilePath filePath;
private UnzipLocal(FilePath filePath) {
this.filePath = filePath;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
if (this.filePath.isRemote()) {
throw new IllegalStateException("Expected local path for file: " + filePath); // this.channel==target.channel above
}
unzip(dir, reading(new File(this.filePath.getRemote()))); // shortcut to local file
return null;
}
private static final long serialVersionUID = 1L;
protected Object readResolve() {
if (REJECT_LOCAL_CALLABLE_DESERIALIZATION) {
throw new IllegalStateException("This callable is not intended to be sent through a channel");
}
return this;
}
}
/**
* When this {@link FilePath} represents a tar file, extracts that tar file.
*
* @param target
* Target directory to expand files to. All the necessary directories will be created.
* @param compression
* Compression mode of this tar file.
* @since 1.292
* @see #untarFrom(InputStream, TarCompression)
*/
public void untar(final FilePath target, final TarCompression compression) throws IOException, InterruptedException {
final FilePath source = FilePath.this;
// TODO: post release, re-unite two branches by introducing FileStreamCallable that resolves InputStream
if (source.channel != target.channel) {// local -> remote or remote->local
final RemoteInputStream in = new RemoteInputStream(source.read(), Flag.GREEDY);
target.act(new UntarRemote(source.getName(), compression, in));
} else {// local -> local or remote->remote
target.act(new UntarLocal(source, compression));
}
}
private static class UntarRemote extends SecureFileCallable<Void> {
private final TarCompression compression;
private final RemoteInputStream in;
private final String name;
UntarRemote(String name, TarCompression compression, RemoteInputStream in) {
this.compression = compression;
this.in = in;
this.name = name;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
readFromTar(name, dir, compression.extract(in));
return null;
}
private static final long serialVersionUID = 1L;
}
private static class UntarLocal extends SecureFileCallable<Void> {
private final TarCompression compression;
private final FilePath filePath;
UntarLocal(FilePath source, TarCompression compression) {
this.filePath = source;
this.compression = compression;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
readFromTar(this.filePath.getName(), dir, compression.extract(this.filePath.read()));
return null;
}
private static final long serialVersionUID = 1L;
protected Object readResolve() {
if (REJECT_LOCAL_CALLABLE_DESERIALIZATION) {
throw new IllegalStateException("This callable is not intended to be sent through a channel");
}
return this;
}
}
/**
* Reads the given InputStream as a zip file and extracts it into this directory.
*
* @param _in
* The stream will be closed by this method after it's fully read.
* @since 1.283
* @see #unzip(FilePath)
*/
public void unzipFrom(InputStream _in) throws IOException, InterruptedException {
final InputStream in = new RemoteInputStream(_in, Flag.GREEDY);
act(new UnzipFrom(in));
}
private static class UnzipFrom extends SecureFileCallable<Void> {
private final InputStream in;
UnzipFrom(InputStream in) {
this.in = in;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException {
unzip(dir, in);
return null;
}
private static final long serialVersionUID = 1L;
}
private static void unzip(File dir, InputStream in) throws IOException {
File tmpFile = File.createTempFile("tmpzip", null); // uses java.io.tmpdir
try {
// TODO why does this not simply use ZipInputStream?
IOUtils.copy(in, tmpFile);
unzip(dir,tmpFile);
}
finally {
tmpFile.delete();
}
}
private static void unzip(File dir, File zipFile) throws IOException {
dir = dir.getAbsoluteFile(); // without absolutization, getParentFile below seems to fail
ZipFile zip = new ZipFile(zipFile);
Enumeration<ZipEntry> entries = zip.getEntries();
try {
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
File f = new File(dir, e.getName());
if (!f.getCanonicalFile().toPath().startsWith(dir.getCanonicalPath())) {
throw new IOException(
"Zip " + zipFile.getPath() + " contains illegal file name that breaks out of the target directory: " + e.getName());
}
if (e.isDirectory()) {
mkdirs(f);
} else {
File p = f.getParentFile();
if (p != null) {
mkdirs(p);
}
try (InputStream input = zip.getInputStream(e)) {
IOUtils.copy(input, writing(f));
}
try {
FilePath target = new FilePath(f);
int mode = e.getUnixMode();
if (mode!=0) // Ant returns 0 if the archive doesn't record the access mode
target.chmod(mode);
} catch (InterruptedException ex) {
LOGGER.log(Level.WARNING, "unable to set permissions", ex);
}
f.setLastModified(e.getTime());
}
}
} finally {
zip.close();
}
}
/**
* Absolutizes this {@link FilePath} and returns the new one.
*/
public FilePath absolutize() throws IOException, InterruptedException {
return new FilePath(channel, act(new Absolutize()));
}
private static class Absolutize extends SecureFileCallable<String> {
private static final long serialVersionUID = 1L;
@Override
public String invoke(File f, VirtualChannel channel) throws IOException {
return stating(f).getAbsolutePath();
}
}
@Restricted(NoExternalUse.class)
public boolean hasSymlink(FilePath verificationRoot, boolean noFollowLinks) throws IOException, InterruptedException {
return act(new HasSymlink(verificationRoot == null ? null : verificationRoot.remote, noFollowLinks));
}
private static class HasSymlink extends SecureFileCallable<Boolean> {
private static final long serialVersionUID = 1L;
private final String verificationRoot;
private final boolean noFollowLinks;
HasSymlink(String verificationRoot, boolean noFollowLinks) {
this.verificationRoot = verificationRoot;
this.noFollowLinks = noFollowLinks;
}
@Override
public Boolean invoke(File f, VirtualChannel channel) throws IOException {
return isSymlink(stating(f), verificationRoot, noFollowLinks);
}
}
@Restricted(NoExternalUse.class)
public boolean containsSymlink(FilePath verificationRoot, boolean noFollowLinks) throws IOException, InterruptedException {
return !list(new SymlinkRetainingFileFilter(verificationRoot, noFollowLinks)).isEmpty();
}
private static class SymlinkRetainingFileFilter implements FileFilter, Serializable {
private final String verificationRoot;
private final boolean noFollowLinks;
SymlinkRetainingFileFilter(FilePath verificationRoot, boolean noFollowLinks) {
this.verificationRoot = verificationRoot == null ? null : verificationRoot.remote;
this.noFollowLinks = noFollowLinks;
}
@Override
public boolean accept(File file) {
return isSymlink(file, verificationRoot, noFollowLinks);
}
private static final long serialVersionUID = 1L;
}
/**
* Creates a symlink to the specified target.
*
* @param target
* The file that the symlink should point to.
* @param listener
* If symlink creation requires a help of an external process, the error will be reported here.
* @since 1.456
*/
public void symlinkTo(final String target, final TaskListener listener) throws IOException, InterruptedException {
act(new SymlinkTo(target, listener));
}
private static class SymlinkTo extends SecureFileCallable<Void> {
private final String target;
private final TaskListener listener;
SymlinkTo(String target, TaskListener listener) {
this.target = target;
this.listener = listener;
}
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
Util.createSymlink(symlinking(f).getParentFile(), target, f.getName(), listener);
return null;
}
}
/**
* Resolves symlink, if the given file is a symlink. Otherwise return null.
* <p>
* If the resolution fails, report an error.
*
* @since 1.456
*/
public String readLink() throws IOException, InterruptedException {
return act(new ReadLink());
}
private static class ReadLink extends SecureFileCallable<String> {
private static final long serialVersionUID = 1L;
@Override
public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
return Util.resolveSymlink(reading(f));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FilePath that = (FilePath) o;
if (!Objects.equals(channel, that.channel)) return false;
return remote.equals(that.remote);
}
@Override
public int hashCode() {
return 31 * (channel != null ? channel.hashCode() : 0) + remote.hashCode();
}
/**
* Supported tar file compression methods.
*/
public enum TarCompression {
NONE {
@Override
public InputStream extract(InputStream in) {
return new BufferedInputStream(in);
}
@Override
public OutputStream compress(OutputStream out) {
return new BufferedOutputStream(out);
}
},
GZIP {
@Override
public InputStream extract(InputStream _in) throws IOException {
HeadBufferingStream in = new HeadBufferingStream(_in,SIDE_BUFFER_SIZE);
try {
return new GZIPInputStream(in, 8192, true);
} catch (IOException e) {
// various people reported "java.io.IOException: Not in GZIP format" here, so diagnose this problem better
in.fillSide();
throw new IOException(e.getMessage()+"\nstream="+Util.toHexString(in.getSideBuffer()),e);
}
}
@Override
public OutputStream compress(OutputStream out) throws IOException {
return new GZIPOutputStream(new BufferedOutputStream(out));
}
};
public abstract InputStream extract(InputStream in) throws IOException;
public abstract OutputStream compress(OutputStream in) throws IOException;
}
/**
* Reads the given InputStream as a tar file and extracts it into this directory.
*
* @param _in
* The stream will be closed by this method after it's fully read.
* @param compression
* The compression method in use.
* @since 1.292
*/
public void untarFrom(InputStream _in, final TarCompression compression) throws IOException, InterruptedException {
try {
final InputStream in = new RemoteInputStream(_in, Flag.GREEDY);
act(new UntarFrom(compression, in));
} finally {
_in.close();
}
}
private static class UntarFrom extends SecureFileCallable<Void> {
private final TarCompression compression;
private final InputStream in;
UntarFrom(TarCompression compression, InputStream in) {
this.compression = compression;
this.in = in;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException {
readFromTar("input stream",dir, compression.extract(in)); // #writing etc. are called in #readFromTar
return null;
}
private static final long serialVersionUID = 1L;
}
/**
* Given a tgz/zip file, extracts it to the given target directory, if necessary.
*
* <p>
* This method is a convenience method designed for installing a binary package to a location
* that supports upgrade and downgrade. Specifically,
*
* <ul>
* <li>If the target directory doesn't exist {@linkplain #mkdirs() it will be created}.
* <li>The timestamp of the archive is left in the installation directory upon extraction.
* <li>If the timestamp left in the directory does not match the timestamp of the current archive file,
* the directory contents will be discarded and the archive file will be re-extracted.
* <li>If the connection is refused but the target directory already exists, it is left alone.
* </ul>
*
* @param archive
* The resource that represents the tgz/zip file. This URL must support the {@code Last-Modified} header.
* (For example, you could use {@link ClassLoader#getResource}.)
* @param listener
* If non-null, a message will be printed to this listener once this method decides to
* extract an archive, or if there is any issue.
* @param message a message to be printed in case extraction will proceed.
* @return
* true if the archive was extracted. false if the extraction was skipped because the target directory
* was considered up to date.
* @since 1.299
*/
public boolean installIfNecessaryFrom(@NonNull URL archive, @CheckForNull TaskListener listener, @NonNull String message) throws IOException, InterruptedException {
if (listener == null) {
listener = TaskListener.NULL;
}
return installIfNecessaryFrom(archive, listener, message, MAX_REDIRECTS);
}
private boolean installIfNecessaryFrom(@NonNull URL archive, @NonNull TaskListener listener, @NonNull String message, int maxRedirects) throws InterruptedException, IOException {
try {
FilePath timestamp = this.child(".timestamp");
long lastModified = timestamp.lastModified();
URLConnection con;
try {
con = ProxyConfiguration.open(archive);
if (lastModified != 0) {
con.setIfModifiedSince(lastModified);
}
con.connect();
} catch (IOException x) {
if (this.exists()) {
// Cannot connect now, so assume whatever was last unpacked is still OK.
listener.getLogger().println("Skipping installation of " + archive + " to " + remote + ": " + x);
return false;
} else {
throw x;
}
}
if (con instanceof HttpURLConnection) {
HttpURLConnection httpCon = (HttpURLConnection) con;
int responseCode = httpCon.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
// follows redirect
if (maxRedirects > 0) {
String location = httpCon.getHeaderField("Location");
listener.getLogger().println("Following redirect " + archive.toExternalForm() + " -> " + location);
return installIfNecessaryFrom(getUrlFactory().newURL(location), listener, message, maxRedirects - 1);
} else {
listener.getLogger().println("Skipping installation of " + archive + " to " + remote + " due to too many redirects.");