-
Notifications
You must be signed in to change notification settings - Fork 51
/
SmbFile.java
2415 lines (2089 loc) · 82.3 KB
/
SmbFile.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
/* jcifs smb client library in Java
* Copyright (C) 2000 "Michael B. Allen" <jcifs at samba dot org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package jcifs.smb;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jcifs.CIFSContext;
import jcifs.CIFSException;
import jcifs.CloseableIterator;
import jcifs.Configuration;
import jcifs.ResourceFilter;
import jcifs.ResourceNameFilter;
import jcifs.SmbConstants;
import jcifs.SmbFileHandle;
import jcifs.SmbResource;
import jcifs.SmbResourceLocator;
import jcifs.SmbTreeHandle;
import jcifs.SmbWatchHandle;
import jcifs.context.SingletonContext;
import jcifs.dcerpc.DcerpcHandle;
import jcifs.dcerpc.msrpc.MsrpcShareGetInfo;
import jcifs.internal.AllocInfo;
import jcifs.internal.SmbBasicFileInfo;
import jcifs.internal.dtyp.ACE;
import jcifs.internal.dtyp.SecurityDescriptor;
import jcifs.internal.dtyp.SecurityInfo;
import jcifs.internal.fscc.BasicFileInformation;
import jcifs.internal.fscc.FileBasicInfo;
import jcifs.internal.fscc.FileInformation;
import jcifs.internal.fscc.FileInternalInfo;
import jcifs.internal.fscc.FileRenameInformation2;
import jcifs.internal.fscc.FileStandardInfo;
import jcifs.internal.fscc.FileSystemInformation;
import jcifs.internal.smb1.com.SmbComBlankResponse;
import jcifs.internal.smb1.com.SmbComCreateDirectory;
import jcifs.internal.smb1.com.SmbComDelete;
import jcifs.internal.smb1.com.SmbComDeleteDirectory;
import jcifs.internal.smb1.com.SmbComNTCreateAndX;
import jcifs.internal.smb1.com.SmbComNTCreateAndXResponse;
import jcifs.internal.smb1.com.SmbComOpenAndX;
import jcifs.internal.smb1.com.SmbComOpenAndXResponse;
import jcifs.internal.smb1.com.SmbComQueryInformation;
import jcifs.internal.smb1.com.SmbComQueryInformationResponse;
import jcifs.internal.smb1.com.SmbComRename;
import jcifs.internal.smb1.com.SmbComSeek;
import jcifs.internal.smb1.com.SmbComSeekResponse;
import jcifs.internal.smb1.com.SmbComSetInformation;
import jcifs.internal.smb1.com.SmbComSetInformationResponse;
import jcifs.internal.smb1.trans.nt.NtTransQuerySecurityDesc;
import jcifs.internal.smb1.trans.nt.NtTransQuerySecurityDescResponse;
import jcifs.internal.smb1.trans2.Trans2QueryFSInformation;
import jcifs.internal.smb1.trans2.Trans2QueryFSInformationResponse;
import jcifs.internal.smb1.trans2.Trans2QueryPathInformation;
import jcifs.internal.smb1.trans2.Trans2QueryPathInformationResponse;
import jcifs.internal.smb1.trans2.Trans2SetFileInformation;
import jcifs.internal.smb1.trans2.Trans2SetFileInformationResponse;
import jcifs.internal.smb2.ServerMessageBlock2Request;
import jcifs.internal.smb2.ServerMessageBlock2Response;
import jcifs.internal.smb2.Smb2Constants;
import jcifs.internal.smb2.create.Smb2CloseRequest;
import jcifs.internal.smb2.create.Smb2CloseResponse;
import jcifs.internal.smb2.create.Smb2CreateRequest;
import jcifs.internal.smb2.create.Smb2CreateResponse;
import jcifs.internal.smb2.info.Smb2QueryInfoRequest;
import jcifs.internal.smb2.info.Smb2QueryInfoResponse;
import jcifs.internal.smb2.info.Smb2SetInfoRequest;
import jcifs.util.Strings;
/**
* This class represents a resource on an SMB network. Mainly these
* resources are files and directories however an <code>SmbFile</code>
* may also refer to servers and workgroups. If the resource is a file or
* directory the methods of <code>SmbFile</code> follow the behavior of
* the well known {@link java.io.File} class. One fundamental difference
* is the usage of a URL scheme [1] to specify the target file or
* directory. SmbFile URLs have the following syntax:
*
* <blockquote>
*
* <pre>
* smb://[[[domain;]username[:password]@]server[:port]/[[share/[dir/]file]]][?param=value[param2=value2[...]]]
* </pre>
*
* </blockquote>
*
* This example:
*
* <blockquote>
*
* <pre>
* smb://storage15/public/foo.txt
* </pre>
*
* </blockquote>
*
* would reference the file <code>foo.txt</code> in the share
* <code>public</code> on the server <code>storage15</code>. In addition
* to referencing files and directories, jCIFS can also address servers,
* and workgroups.
* <p>
* <font color="#800000"><i>Important: all SMB URLs that represent
* workgroups, servers, shares, or directories require a trailing slash '/'.
* </i></font>
* <p>
* When using the <tt>java.net.URL</tt> class with
* 'smb://' URLs it is necessary to first call the static
* <tt>jcifs.Config.registerSmbURLHandler();</tt> method. This is required
* to register the SMB protocol handler.
* <p>
* The userinfo component of the SMB URL (<tt>domain;user:pass</tt>) must
* be URL encoded if it contains reserved characters. According to RFC 2396
* these characters are non US-ASCII characters and most meta characters
* however jCIFS will work correctly with anything but '@' which is used
* to delimit the userinfo component from the server and '%' which is the
* URL escape character itself.
* <p>
* The server
* component may a traditional NetBIOS name, a DNS name, or IP
* address. These name resolution mechanisms and their resolution order
* can be changed (See <a href="../../../resolver.html">Setting Name
* Resolution Properties</a>). The servername and path components are
* not case sensitive but the domain, username, and password components
* are. It is also likely that properties must be specified for jcifs
* to function (See <a href="../../overview-summary.html#scp">Setting
* JCIFS Properties</a>). Here are some examples of SMB URLs with brief
* descriptions of what they do:
*
* <p>
* [1] This URL scheme is based largely on the <i>SMB
* Filesharing URL Scheme</i> IETF draft.
*
* <p>
* <table border="1" cellpadding="3" cellspacing="0" width="100%" summary="URL examples">
* <tr bgcolor="#ccccff">
* <td colspan="2"><b>SMB URL Examples</b></td>
* <tr>
* <td width="20%"><b>URL</b></td>
* <td><b>Description</b></td>
* </tr>
*
* <tr>
* <td width="20%"><code>smb://users-nyc;miallen:mypass@angus/tmp/</code></td>
* <td>
* This URL references a share called <code>tmp</code> on the server
* <code>angus</code> as user <code>miallen</code> who's password is
* <code>mypass</code>.
* </td>
* </tr>
*
* <tr>
* <td width="20%">
* <code>smb://Administrator:P%40ss@msmith1/c/WINDOWS/Desktop/foo.txt</code></td>
* <td>
* A relatively sophisticated example that references a file
* <code>msmith1</code>'s desktop as user <code>Administrator</code>. Notice the '@' is URL encoded with the '%40'
* hexcode escape.
* </td>
* </tr>
*
* <tr>
* <td width="20%"><code>smb://angus/</code></td>
* <td>
* This references only a server. The behavior of some methods is different
* in this context(e.g. you cannot <code>delete</code> a server) however
* as you might expect the <code>list</code> method will list the available
* shares on this server.
* </td>
* </tr>
*
* <tr>
* <td width="20%"><code>smb://angus.foo.net/d/jcifs/pipes.doc</code></td>
* <td>
* The server name may also be a DNS name as it is in this example. See
* <a href="../../../resolver.html">Setting Name Resolution Properties</a>
* for details.
* </td>
* </tr>
*
* <tr>
* <td width="20%"><code>smb://192.168.1.15/ADMIN$/</code></td>
* <td>
* The server name may also be an IP address. See <a
* href="../../../resolver.html">Setting Name Resolution Properties</a>
* for details.
* </td>
* </tr>
*
* <tr>
* <td width="20%">
* <code>smb://domain;username:password@server/share/path/to/file.txt</code></td>
* <td>
* A prototypical example that uses all the fields.
* </td>
* </tr>
*
* <tr>
* <td width="20%">
* <code>smb://server/share/path/to/dir <-- ILLEGAL </code></td>
* <td>
* URLs that represent servers, shares, or directories require a trailing slash '/'.
* </td>
* </tr>
*
* </table>
*
* <p>
* A second constructor argument may be specified to augment the URL
* for better programmatic control when processing many files under
* a common base. This is slightly different from the corresponding
* <code>java.io.File</code> usage; a '/' at the beginning of the second
* parameter will still use the server component of the first parameter. The
* examples below illustrate the resulting URLs when this second constructor
* argument is used.
*
* <p>
* <table border="1" cellpadding="3" cellspacing="0" width="100%" summary="Usage examples">
* <tr bgcolor="#ccccff">
* <td colspan="3">
* <b>Examples Of SMB URLs When Augmented With A Second Constructor Parameter</b></td>
* <tr>
* <td width="20%">
* <b>First Parameter</b></td>
* <td><b>Second Parameter</b></td>
* <td><b>Result</b></td>
* </tr>
*
* <tr>
* <td width="20%"><code>
* smb://host/share/a/b/
* </code></td>
* <td width="20%"><code>
* c/d/
* </code></td>
* <td><code>
* smb://host/share/a/b/c/d/
* </code></td>
* </tr>
*
* <tr>
* <td width="20%"><code>
* smb://host/share/foo/bar/
* </code></td>
* <td width="20%"><code>
* /share2/zig/zag
* </code></td>
* <td><code>
* smb://host/share2/zig/zag
* </code></td>
* </tr>
*
* <tr>
* <td width="20%"><code>
* smb://host/share/foo/bar/
* </code></td>
* <td width="20%"><code>
* ../zip/
* </code></td>
* <td><code>
* smb://host/share/foo/zip/
* </code></td>
* </tr>
*
* <tr>
* <td width="20%"><code>
* smb://host/share/zig/zag
* </code></td>
* <td width="20%"><code>
* smb://foo/bar/
* </code></td>
* <td><code>
* smb://foo/bar/
* </code></td>
* </tr>
*
* <tr>
* <td width="20%"><code>
* smb://host/share/foo/
* </code></td>
* <td width="20%"><code>
* ../.././.././../foo/
* </code></td>
* <td><code>
* smb://host/foo/
* </code></td>
* </tr>
*
* <tr>
* <td width="20%"><code>
* smb://host/share/zig/zag
* </code></td>
* <td width="20%"><code>
* /
* </code></td>
* <td><code>
* smb://host/
* </code></td>
* </tr>
*
* <tr>
* <td width="20%"><code>
* smb://server/
* </code></td>
* <td width="20%"><code>
* ../
* </code></td>
* <td><code>
* smb://server/
* </code></td>
* </tr>
*
* </table>
*
* <p>
* Instances of the <code>SmbFile</code> class are immutable; that is,
* once created, the abstract pathname represented by an SmbFile object
* will never change.
*
* @see java.io.File
*/
public class SmbFile extends URLConnection implements SmbResource, SmbConstants {
protected static final int ATTR_GET_MASK = 0x7FFF;
protected static final int ATTR_SET_MASK = 0x30A7;
protected static final int DEFAULT_ATTR_EXPIRATION_PERIOD = 5000;
protected static final int HASH_DOT = ".".hashCode();
protected static final int HASH_DOT_DOT = "..".hashCode();
private static Logger log = LoggerFactory.getLogger(SmbFile.class);
private long createTime;
private long lastModified;
private long lastAccess;
private int attributes;
private long attrExpiration;
private long size;
private long sizeExpiration;
private boolean isExists;
private CIFSContext transportContext;
private SmbTreeConnection treeConnection;
protected final SmbResourceLocatorImpl fileLocator;
private SmbTreeHandleImpl treeHandle;
/**
* Constructs an SmbFile representing a resource on an SMB network such as
* a file or directory. See the description and examples of smb URLs above.
*
* @param url
* A URL string
* @throws MalformedURLException
* If the <code>parent</code> and <code>child</code> parameters
* do not follow the prescribed syntax
*/
@Deprecated
public SmbFile ( String url ) throws MalformedURLException {
this(new URL(null, url, SingletonContext.getInstance().getUrlHandler()));
}
/**
* Constructs an SmbFile representing a resource on an SMB network such
* as a file or directory from a <tt>URL</tt> object.
*
* @param url
* The URL of the target resource
* @throws MalformedURLException
*/
@Deprecated
public SmbFile ( URL url ) throws MalformedURLException {
this(url, SingletonContext.getInstance().withCredentials(new NtlmPasswordAuthentication(SingletonContext.getInstance(), url.getUserInfo())));
}
/**
* Constructs an SmbFile representing a resource on an SMB network such
* as a file or directory. The second parameter is a relative path from
* the <code>parent SmbFile</code>. See the description above for examples
* of using the second <code>name</code> parameter.
*
* @param context
* A base <code>SmbFile</code>
* @param name
* A path string relative to the <code>parent</code> parameter
* @throws MalformedURLException
* If the <code>parent</code> and <code>child</code> parameters
* do not follow the prescribed syntax
* @throws UnknownHostException
* If the server or workgroup of the <tt>context</tt> file cannot be determined
*/
public SmbFile ( SmbResource context, String name ) throws MalformedURLException, UnknownHostException {
this(
isWorkgroup(context) ? new URL(null, "smb://" + checkName(name), context.getContext().getUrlHandler())
: new URL(context.getLocator().getURL(), encodeRelativePath(checkName(name)), context.getContext().getUrlHandler()),
context.getContext());
setContext(context, name);
}
/**
* Construct from string URL
*
* @param url
* @param tc
* context to use
* @throws MalformedURLException
*/
public SmbFile ( String url, CIFSContext tc ) throws MalformedURLException {
this(new URL(null, url, tc.getUrlHandler()), tc);
}
/**
* Construct from URL
*
* @param url
* @param tc
* context to use
* @throws MalformedURLException
*/
public SmbFile ( URL url, CIFSContext tc ) throws MalformedURLException {
super(url);
if ( url.getPath() != null && !url.getPath().isEmpty() && url.getPath().charAt(0) != '/' ) {
throw new MalformedURLException("Invalid SMB URL: " + url);
}
this.transportContext = tc;
this.fileLocator = new SmbResourceLocatorImpl(tc, url);
this.treeConnection = SmbTreeConnection.create(tc);
}
SmbFile ( SmbResource context, String name, boolean loadedAttributes, int type, int attributes, long createTime, long lastModified,
long lastAccess, long size ) throws MalformedURLException {
this(
isWorkgroup(context) ? new URL(null, "smb://" + checkName(name) + "/", context.getContext().getUrlHandler())
: new URL(
context.getLocator().getURL(),
encodeRelativePath(checkName(name)) + ( ( attributes & ATTR_DIRECTORY ) > 0 ? "/" : "" )),
context.getContext());
if ( !isWorkgroup(context) ) {
setContext(context, name + ( ( attributes & ATTR_DIRECTORY ) > 0 ? "/" : "" ));
}
/*
* why? am I going around in circles?
* this.type = type == TYPE_WORKGROUP ? 0 : type;
*/
this.fileLocator.updateType(type);
this.attributes = attributes;
this.createTime = createTime;
this.lastModified = lastModified;
this.lastAccess = lastAccess;
this.size = size;
this.isExists = true;
if ( loadedAttributes ) {
this.attrExpiration = this.sizeExpiration = System.currentTimeMillis() + getContext().getConfig().getAttributeCacheTimeout();
}
}
private static String encodeRelativePath ( String name ) {
// workaround fix
if (name == null) {
return null;
}
if (name.endsWith(" ")) {
final StringBuilder suffix = new StringBuilder();
for (int i = name.length() - 1; i >= 0; i--) {
if (name.charAt(i) != ' ') {
break;
}
suffix.append("%20");
}
name = name.replaceAll(" +$", suffix.toString());
}
return "URL:" + name.replace("?", "%3f");
}
/**
* @return
*/
private static boolean isWorkgroup ( SmbResource r ) {
try {
return r.getLocator().isWorkgroup();
}
catch ( CIFSException e ) {
log.debug("Failed to check for workgroup", e);
return false;
}
}
/**
* {@inheritDoc}
*
* @see java.net.URLConnection#connect()
*/
@Override
public void connect () throws IOException {
try ( SmbTreeHandle th = ensureTreeConnected() ) {}
}
/**
*
* @return a tree handle
* @throws CIFSException
*/
public SmbTreeHandle getTreeHandle () throws CIFSException {
return ensureTreeConnected();
}
/**
* {@inheritDoc}
*
* @see java.lang.AutoCloseable#close()
*/
@Override
public synchronized void close () {
SmbTreeHandleImpl th = this.treeHandle;
if ( th != null ) {
this.treeHandle = null;
if ( this.transportContext.getConfig().isStrictResourceLifecycle() ) {
th.close();
}
}
}
/**
* @return
* @throws CIFSException
*
*/
synchronized SmbTreeHandleImpl ensureTreeConnected () throws CIFSException {
if ( this.treeHandle == null || !this.treeHandle.isConnected() ) {
if ( this.treeHandle != null && this.transportContext.getConfig().isStrictResourceLifecycle() ) {
this.treeHandle.release();
}
this.treeHandle = this.treeConnection.connectWrapException(this.fileLocator);
this.treeHandle.ensureDFSResolved();
if ( this.transportContext.getConfig().isStrictResourceLifecycle() ) {
// one extra share to keep the tree alive
return this.treeHandle.acquire();
}
return this.treeHandle;
}
return this.treeHandle.acquire();
}
/**
* @param context
* @param name
*/
private void setContext ( SmbResource context, String name ) {
this.fileLocator.resolveInContext(context.getLocator(), name);
if ( context.getLocator().getShare() != null && ( context instanceof SmbFile ) ) {
this.treeConnection = SmbTreeConnection.create( ( (SmbFile) context ).treeConnection);
}
else {
this.treeConnection = SmbTreeConnection.create(context.getContext());
}
}
private static String checkName ( String name ) throws MalformedURLException {
if ( name == null || name.length() == 0 ) {
throw new MalformedURLException("Name must not be empty");
}
return name;
}
/**
* @param nonPooled
* whether this file will use an exclusive connection
*/
protected void setNonPooled ( boolean nonPooled ) {
this.treeConnection.setNonPooled(nonPooled);
}
/**
* @return the transportContext
*/
@Deprecated
public CIFSContext getTransportContext () {
return this.getContext();
}
@Override
public CIFSContext getContext () {
return this.transportContext;
}
@Override
public SmbResourceLocator getLocator () {
return this.fileLocator;
}
@Override
public SmbResource resolve ( String name ) throws CIFSException {
try {
if ( name == null || name.length() == 0 ) {
throw new SmbException("Name must not be empty");
}
return new SmbFile(this, name);
}
catch (
MalformedURLException |
UnknownHostException e ) {
// this should not actually happen
throw new SmbException("Failed to resolve child element", e);
}
}
SmbFileHandleImpl openUnshared ( int flags, int access, int sharing, int attrs, int options ) throws CIFSException {
return openUnshared(getUncPath(), flags, access, sharing, attrs, options);
}
SmbFileHandleImpl openUnshared ( String uncPath, int flags, int access, int sharing, int attrs, int options ) throws CIFSException {
SmbFileHandleImpl fh = null;
try ( SmbTreeHandleImpl h = ensureTreeConnected() ) {
if ( log.isDebugEnabled() ) {
log.debug(String.format("openUnshared: %s flags: %x access: %x attrs: %x options: %x", uncPath, flags, access, attrs, options));
}
Configuration config = h.getConfig();
SmbBasicFileInfo info;
boolean haveSize = true, haveAttributes = true;
long fileSize = 0;
if ( h.isSMB2() ) {
Smb2CreateRequest req = new Smb2CreateRequest(config, uncPath);
req.setDesiredAccess(access);
if ( ( flags & SmbConstants.O_TRUNC ) == O_TRUNC && ( flags & SmbConstants.O_CREAT ) == O_CREAT ) {
req.setCreateDisposition(Smb2CreateRequest.FILE_OVERWRITE_IF);
}
else if ( ( flags & SmbConstants.O_TRUNC ) == O_TRUNC ) {
req.setCreateDisposition(Smb2CreateRequest.FILE_OVERWRITE);
}
else if ( ( flags & SmbConstants.O_EXCL ) == O_EXCL ) {
req.setCreateDisposition(Smb2CreateRequest.FILE_CREATE);
}
else if ( ( flags & SmbConstants.O_CREAT ) == O_CREAT ) {
req.setCreateDisposition(Smb2CreateRequest.FILE_OPEN_IF);
}
else {
req.setCreateDisposition(Smb2CreateRequest.FILE_OPEN);
}
req.setShareAccess(sharing);
req.setFileAttributes(attrs);
Smb2CreateResponse resp = h.send(req);
info = resp;
fileSize = resp.getEndOfFile();
fh = new SmbFileHandleImpl(config, resp.getFileId(), h, uncPath, flags, access, 0, 0, resp.getEndOfFile());
}
else if ( h.hasCapability(SmbConstants.CAP_NT_SMBS) ) {
SmbComNTCreateAndXResponse resp = new SmbComNTCreateAndXResponse(config);
SmbComNTCreateAndX req = new SmbComNTCreateAndX(config, uncPath, flags, access, sharing, attrs, options, null);
customizeCreate(req, resp);
h.send(req, resp);
info = resp;
fileSize = resp.getEndOfFile();
this.fileLocator.updateType(resp.getFileType());
fh = new SmbFileHandleImpl(config, resp.getFid(), h, uncPath, flags, access, attrs, options, resp.getEndOfFile());
}
else {
SmbComOpenAndXResponse response = new SmbComOpenAndXResponse(config);
h.send(new SmbComOpenAndX(config, uncPath, access, sharing, flags, attrs, null), response);
this.fileLocator.updateType(response.getFileType());
info = response;
fileSize = response.getDataSize();
// this is so damn unreliable, needs another race-prone query if required
haveAttributes = false;
// This seems to be the only way to obtain a reliable (with respect to locking) file size here
// It is more critical than other attributes because append mode depends on it.
// We do only really care if we open for writing and not shared for writing
// otherwise there are no guarantees anyway, but this stuff is legacy anyways.
SmbComSeek seekReq = new SmbComSeek(config, 0);
seekReq.setMode(0x2); // from EOF
SmbComSeekResponse seekResp = new SmbComSeekResponse(config);
seekReq.setFid(response.getFid());
try {
h.send(seekReq, seekResp);
if ( log.isDebugEnabled() && seekResp.getOffset() != fileSize ) {
log.debug(String.format("Open returned wrong size %d != %d", fileSize, seekResp.getOffset()));
}
fileSize = seekResp.getOffset();
}
catch ( Exception e ) {
log.debug("Seek failed", e);
haveSize = false;
}
fh = new SmbFileHandleImpl(config, response.getFid(), h, uncPath, flags, access, 0, 0, fileSize);
}
long attrTimeout = System.currentTimeMillis() + config.getAttributeCacheTimeout();
if ( haveSize ) {
this.size = fileSize;
this.sizeExpiration = attrTimeout;
}
if ( haveAttributes ) {
this.createTime = info.getCreateTime();
this.lastModified = info.getLastWriteTime();
this.lastAccess = info.getLastAccessTime();
this.attributes = info.getAttributes() & ATTR_GET_MASK;
this.attrExpiration = attrTimeout;
}
this.isExists = true;
return fh;
}
}
/**
* @return this file's unc path below the share
*/
public String getUncPath () {
return this.fileLocator.getUNCPath();
}
/**
* @param request
* @param response
*/
protected void customizeCreate ( SmbComNTCreateAndX request, SmbComNTCreateAndXResponse response ) {}
SmbBasicFileInfo queryPath ( SmbTreeHandleImpl th, String path, int infoLevel ) throws CIFSException {
if ( log.isDebugEnabled() ) {
log.debug("queryPath: " + path);
}
/*
* We really should do the referral before this in case
* the redirected target has different capabilities. But
* the way we have been doing that is to call exists() which
* calls this method so another technique will be necessary
* to support DFS referral _to_ Win95/98/ME.
*/
if ( th.isSMB2() ) {
// just open and close. withOpen will store the attributes
return (SmbBasicFileInfo) withOpen(
th,
Smb2CreateRequest.FILE_OPEN,
SmbConstants.FILE_READ_ATTRIBUTES,
SmbConstants.FILE_SHARE_READ | SmbConstants.FILE_SHARE_WRITE,
null);
}
else if ( th.hasCapability(SmbConstants.CAP_NT_SMBS) ) {
/*
* Trans2 Query Path Information Request / Response
*/
Trans2QueryPathInformationResponse response = new Trans2QueryPathInformationResponse(th.getConfig(), infoLevel);
response = th.send(new Trans2QueryPathInformation(th.getConfig(), path, infoLevel), response);
if ( log.isDebugEnabled() ) {
log.debug("Path information " + response);
}
BasicFileInformation info = response.getInfo(BasicFileInformation.class);
this.isExists = true;
if ( info instanceof FileBasicInfo ) {
this.attributes = info.getAttributes() & ATTR_GET_MASK;
this.createTime = info.getCreateTime();
this.lastModified = info.getLastWriteTime();
this.lastAccess = info.getLastAccessTime();
this.attrExpiration = System.currentTimeMillis() + th.getConfig().getAttributeCacheTimeout();
}
else if ( info instanceof FileStandardInfo ) {
this.size = info.getSize();
this.sizeExpiration = System.currentTimeMillis() + th.getConfig().getAttributeCacheTimeout();
}
return info;
}
/*
* Query Information Request / Response
*/
SmbComQueryInformationResponse response = new SmbComQueryInformationResponse(th.getConfig(), th.getServerTimeZoneOffset());
response = th.send(new SmbComQueryInformation(th.getConfig(), path), response);
if ( log.isDebugEnabled() ) {
log.debug("Legacy path information " + response);
}
this.isExists = true;
this.attributes = response.getAttributes() & ATTR_GET_MASK;
this.lastModified = response.getLastWriteTime();
this.attrExpiration = System.currentTimeMillis() + th.getConfig().getAttributeCacheTimeout();
this.size = response.getSize();
this.sizeExpiration = System.currentTimeMillis() + th.getConfig().getAttributeCacheTimeout();
return response;
}
@Override
public boolean exists () throws SmbException {
if ( this.attrExpiration > System.currentTimeMillis() ) {
log.trace("Using cached attributes");
return this.isExists;
}
this.attributes = ATTR_READONLY | ATTR_DIRECTORY;
this.createTime = 0L;
this.lastModified = 0L;
this.lastAccess = 0L;
this.isExists = false;
try {
if ( this.url.getHost().length() == 0 ) {}
else if ( this.fileLocator.getShare() == null ) {
if ( this.fileLocator.getType() == TYPE_WORKGROUP ) {
getContext().getNameServiceClient().getByName(this.url.getHost(), true);
}
else {
getContext().getNameServiceClient().getByName(this.url.getHost()).getHostName();
}
}
else {
// queryPath on a share root will fail, we only know whether this is one after we have resolved DFS
// referrals.
try ( SmbTreeHandleImpl th = ensureTreeConnected() ) {
if ( this.fileLocator.getType() == TYPE_SHARE ) {
// treeConnect is good enough, but we need to do this after resolving DFS
try ( SmbTreeHandleImpl th2 = ensureTreeConnected() ) {}
}
else {
queryPath(th, this.fileLocator.getUNCPath(), FileInformation.FILE_BASIC_INFO);
}
}
}
/*
* If any of the above fail, isExists will not be set true
*/
this.isExists = true;
}
catch ( UnknownHostException uhe ) {
log.debug("Unknown host", uhe);
}
catch ( SmbException se ) {
log.trace("exists:", se);
switch ( se.getNtStatus() ) {
case NtStatus.NT_STATUS_NO_SUCH_FILE:
case NtStatus.NT_STATUS_OBJECT_NAME_INVALID:
case NtStatus.NT_STATUS_OBJECT_NAME_NOT_FOUND:
case NtStatus.NT_STATUS_OBJECT_PATH_NOT_FOUND:
break;
default:
throw se;
}
}
catch ( CIFSException e ) {
throw SmbException.wrap(e);
}
this.attrExpiration = System.currentTimeMillis() + getContext().getConfig().getAttributeCacheTimeout();
return this.isExists;
}
@Override
public int getType () throws SmbException {
try {
int t = this.fileLocator.getType();
if ( t == TYPE_SHARE ) {
try ( SmbTreeHandle th = ensureTreeConnected() ) {
this.fileLocator.updateType(th.getTreeType());
}
}
return t;
}
catch ( CIFSException e ) {
throw SmbException.wrap(e);
}
}
@Override
public String getName () {
return this.fileLocator.getName();
}
/**
* Everything but the last component of the URL representing this SMB
* resource is effectively it's parent. The root URL <code>smb://</code>
* does not have a parent. In this case <code>smb://</code> is returned.
*
* @return The parent directory of this SMB resource or
* <code>smb://</code> if the resource refers to the root of the URL
* hierarchy which incidentally is also <code>smb://</code>.
*/
public String getParent () {
return this.fileLocator.getParent();
}
/**
* Returns the full uncanonicalized URL of this SMB resource. An
* <code>SmbFile</code> constructed with the result of this method will
* result in an <code>SmbFile</code> that is equal to the original.
*
* @return The uncanonicalized full URL of this SMB resource.
*/
public String getPath () {
return this.fileLocator.getPath();
}
/**
* Returns the Windows UNC style path with backslashes instead of forward slashes.
*
* @return The UNC path.
*/
public String getCanonicalUncPath () {
return this.fileLocator.getCanonicalURL();
}
/**
* If the path of this <code>SmbFile</code> falls within a DFS volume,
* this method will return the referral path to which it maps. Otherwise
* <code>null</code> is returned.
*
* @return URL to the DFS volume
* @throws SmbException
*/
public String getDfsPath () throws SmbException {
try {
String path = this.treeConnection.ensureDFSResolved(this.fileLocator).getDfsPath();
if ( path != null && isDirectory() ) {
path += '/';
}
return path;
}
catch ( CIFSException e ) {
throw SmbException.wrap(e);
}
}
/**
* Returns the full URL of this SMB resource with '.' and '..' components
* factored out. An <code>SmbFile</code> constructed with the result of
* this method will result in an <code>SmbFile</code> that is equal to