forked from apache/tomcat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebdavServlet.java
More file actions
3210 lines (2683 loc) · 122 KB
/
WebdavServlet.java
File metadata and controls
3210 lines (2683 loc) · 122 KB
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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.servlets;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serial;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Deque;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRegistration;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.WebResource;
import org.apache.catalina.connector.RequestFacade;
import org.apache.catalina.util.DOMWriter;
import org.apache.catalina.util.IOTools;
import org.apache.catalina.util.XMLWriter;
import org.apache.tomcat.PeriodicEventListener;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.http.ConcurrentDateFormat;
import org.apache.tomcat.util.http.FastHttpDateFormat;
import org.apache.tomcat.util.http.Method;
import org.apache.tomcat.util.http.RequestUtil;
import org.apache.tomcat.util.http.WebdavIfHeader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* This servlet adds support for <a href="https://tools.ietf.org/html/rfc4918">WebDAV</a>
* <a href="https://tools.ietf.org/html/rfc4918#section-18">level 3</a>. All the basic HTTP requests are handled by the
* DefaultServlet.
* <p>
* The WebDAV servlet is only designed for use with path mapping. The WebdavServlet must not be used as the default
* servlet (i.e. mapped to '/') or with any other mapping types as it will not work in those configurations.
* <p>
* By default, the entire web application is exposed via the WebDAV servlet. Mapping the WebDAV servlet to
* <code>/*</code> provides WebDAV access to all the resources within the web application. To aid separation of normal
* users and WebDAV users, the WebDAV servlet may be mounted at a sub-path (e.g. <code>/webdav/*</code>) which creates
* an additional mapping for the entire web application under that sub-path, with WebDAV access to all the resources.
* <p>
* By default, the <code>WEB-INF</code> and <code>META-INF</code> directories are not accessible via WebDAV. This may be
* changed by setting the <code>allowSpecialPaths</code> initialisation parameter to <code>true</code>.
* <p>
* It is also possible to enable WebDAV access to a sub-set of the standard web application URL space rather than
* creating an additional, WebDAV specific mapping. To do this, map the WebDAV servlet to the desired sub-path and set
* the <code>serveSubpathOnly</code> initialisation parameter to <code>true</code>.
* <p>
* Security constraints using the same URL pattern as the mapping (e.g. <code>/webdav/*</code>) can be used to limit the
* users with access to WebDAV functionality. Care is required if using security constraints to further limit WebDAV
* functionality. In particular, administrators should be aware that security constraints apply only to the request URL.
* Security constraints do not apply to any destination URL associated with the WebDAV operation (such as COPY or MOVE).
* <p>
* If WebDAV functionality is included in a web application where legitimate users may access it via a browser, it is
* recommended that the application include CORS protection.
* <p>
* To enable WebDAV for a context add the following to web.xml:
*
* <pre>
* <servlet>
* <servlet-name>webdav</servlet-name>
* <servlet-class>org.apache.catalina.servlets.WebdavServlet</servlet-class>
* <init-param>
* <param-name>debug</param-name>
* <param-value>0</param-value>
* </init-param>
* <init-param>
* <param-name>listings</param-name>
* <param-value>true</param-value>
* </init-param>
* </servlet>
* <servlet-mapping>
* <servlet-name>webdav</servlet-name>
* <url-pattern>/*</url-pattern>
* </servlet-mapping>
* </pre>
*
* This will enable read only access with folder listings enabled. To enable read-write access add:
*
* <pre>
* <init-param>
* <param-name>readonly</param-name>
* <param-value>false</param-value>
* </init-param>
* </pre>
*
* To make the content editable via a different URL, use the following mapping:
*
* <pre>
* <servlet-mapping>
* <servlet-name>webdav</servlet-name>
* <url-pattern>/webdavedit/*</url-pattern>
* </servlet-mapping>
* </pre>
*
* By default, access to /WEB-INF and META-INF are not available via WebDAV. To enable access to these URLs, add:
*
* <pre>
* <init-param>
* <param-name>allowSpecialPaths</param-name>
* <param-value>true</param-value>
* </init-param>
* </pre>
*
* Don't forget to secure access appropriately to the editing URLs, especially if allowSpecialPaths is used. With the
* mapping configuration above, the context will be accessible to normal users as before. Those users with the necessary
* access will be able to edit content available via http://host:port/context/content using
* http://host:port/context/webdavedit/content
* <p>
* The Servlet provides support for arbitrary dead properties on all resources (dead properties are properties whose
* values are not protected by the server, such as the content length of a resource). By default, the Servlet will use
* non persistent memory storage for them. Persistence can be achieved by implementing the <code>PropertyStore</code>
* interface and configuring the Servlet to use that store. The <code>propertyStore</code> init-param allows configuring
* the class name of the store to use, while the parameters in the form of <code>store.xxx</code> will be set on the
* store object as bean properties. For example, this would configure a store with class
* <code>com.MyPropertyStore</code>, and set its property <code>myName</code> to value <code>myValue</code>:
*
* <pre>
* <init-param>
* <param-name>propertyStore</param-name>
* <param-value>com.MyPropertyStore</param-value>
* </init-param>
* <init-param>
* <param-name>store.myName</param-name>
* <param-value>myValue</param-value>
* </init-param>
* </pre>
* <p>
*
* @see <a href="https://tools.ietf.org/html/rfc4918">RFC 4918</a>
*/
public class WebdavServlet extends DefaultServlet implements PeriodicEventListener {
@Serial
private static final long serialVersionUID = 1L;
/**
* Default lock timeout value.
*/
private static final int DEFAULT_TIMEOUT = 3600;
/**
* Maximum lock timeout.
*/
private static final int MAX_TIMEOUT = 604800;
/**
* Default maximum depth.
*/
private static final int MAX_DEPTH = 3;
/**
* Default namespace.
*/
protected static final String DEFAULT_NAMESPACE = "DAV:";
/**
* Pre generated raw XML for supported locks.
*/
protected static final String SUPPORTED_LOCKS =
"\n <D:lockentry><D:lockscope><D:exclusive/></D:lockscope><D:locktype><D:write/></D:locktype></D:lockentry>\n" +
" <D:lockentry><D:lockscope><D:shared/></D:lockscope><D:locktype><D:write/></D:locktype></D:lockentry>\n";
/**
* Simple date format for the creation date ISO representation (partial).
*/
protected static final ConcurrentDateFormat creationDateFormat =
new ConcurrentDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US, TimeZone.getTimeZone("GMT"));
/**
* Lock scheme used.
*/
protected static final String LOCK_SCHEME = "urn:uuid:";
// ----------------------------------------------------- Instance Variables
/**
* Repository of all locks, keyed by path.
*/
private final ConcurrentHashMap<String,LockInfo> resourceLocks = new ConcurrentHashMap<>();
/**
* Map of all shared locks, keyed by lock token.
*/
private final ConcurrentHashMap<String,LockInfo> sharedLocks = new ConcurrentHashMap<>();
/**
* Default depth in spec is infinite.
*/
private int maxDepth = MAX_DEPTH;
/**
* Is access allowed via WebDAV to the special paths (/WEB-INF and /META-INF)?
*/
private boolean allowSpecialPaths = false;
/**
* Is the if header processing strict.
*/
private boolean strictIfProcessing = true;
/**
* Serve resources from the mounted subpath only, restoring the behavior of {@code DefaultServlet}.
*/
private boolean serveSubpathOnly = false;
/**
* Property store used for storage of dead properties.
*/
private PropertyStore store = null;
// --------------------------------------------------------- Public Methods
@Override
public void init() throws ServletException {
super.init();
// Validate that the Servlet is only mapped to wildcard mappings
String servletName = getServletConfig().getServletName();
ServletRegistration servletRegistration =
getServletConfig().getServletContext().getServletRegistration(servletName);
Collection<String> servletMappings = servletRegistration.getMappings();
for (String mapping : servletMappings) {
if (!mapping.endsWith("/*")) {
log(sm.getString("webdavservlet.nonWildcardMapping", mapping));
}
}
if (getServletConfig().getInitParameter("maxDepth") != null) {
maxDepth = Integer.parseInt(getServletConfig().getInitParameter("maxDepth"));
}
if (getServletConfig().getInitParameter("allowSpecialPaths") != null) {
allowSpecialPaths = Boolean.parseBoolean(getServletConfig().getInitParameter("allowSpecialPaths"));
}
if (getServletConfig().getInitParameter("strictIfProcessing") != null) {
strictIfProcessing = Boolean.parseBoolean(getServletConfig().getInitParameter("strictIfProcessing"));
}
if (getServletConfig().getInitParameter("serveSubpathOnly") != null) {
serveSubpathOnly = Boolean.parseBoolean(getServletConfig().getInitParameter("serveSubpathOnly"));
}
String propertyStore = getServletConfig().getInitParameter("propertyStore");
if (propertyStore != null) {
try {
Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(propertyStore);
store = (PropertyStore) clazz.getConstructor().newInstance();
// Set init parameters as properties on the store
Enumeration<String> parameterNames = getServletConfig().getInitParameterNames();
while (parameterNames.hasMoreElements()) {
String parameterName = parameterNames.nextElement();
if (parameterName.startsWith("store.")) {
StringBuilder actualMethod = new StringBuilder();
String parameterValue = getServletConfig().getInitParameter(parameterName);
parameterName = parameterName.substring("store.".length());
if (!IntrospectionUtils.setProperty(store, parameterName, parameterValue, true, actualMethod)) {
log(sm.getString("webdavservlet.noStoreParameter", parameterName, parameterValue));
}
}
}
} catch (Exception e) {
log(sm.getString("webdavservlet.storeError"), e);
}
}
if (store == null) {
log(sm.getString("webdavservlet.memorystore"));
store = new MemoryPropertyStore();
}
store.init();
}
@Override
public void destroy() {
store.destroy();
}
@Override
public void periodicEvent() {
// Check expiration of all locks
for (LockInfo currentLock : sharedLocks.values()) {
if (currentLock.hasExpired()) {
sharedLocks.remove(currentLock.path);
}
}
for (LockInfo currentLock : resourceLocks.values()) {
if (currentLock.isExclusive()) {
if (currentLock.hasExpired()) {
resourceLocks.remove(currentLock.path);
}
} else {
currentLock.sharedTokens.removeIf(token -> sharedLocks.get(token) == null);
if (currentLock.sharedTokens.isEmpty()) {
resourceLocks.remove(currentLock.path);
}
}
}
store.periodicEvent();
}
// ------------------------------------------------ PropertyStore Interface
/**
* Handling of dead properties on resources. This interface allows providing storage for dead properties. Store
* configuration is done through the <code>propertyStore</code> init parameter of the WebDAV Servlet, which should
* contain the class name of the store.
*/
public interface PropertyStore {
/**
* Initialize the store. This is tied to the Servlet lifecycle and is called by its init method.
*/
void init();
/**
* Destroy the store. This is tied to the Servlet lifecycle and is called by its destroy method.
*/
void destroy();
/**
* Periodic event for maintenance tasks.
*/
void periodicEvent();
/**
* Copy resource. Dead properties should be copied to the destination path.
*
* @param source the copy source path
* @param destination the copy destination path
*/
void copy(String source, String destination);
/**
* Delete specified resource. Dead properties on a deleted resource should be deleted.
*
* @param resource the path of the resource to delete
*/
void delete(String resource);
/**
* Generate propfind XML fragments for dead properties.
*
* @param resource the resource path
* @param property the dead property, if null then all dead properties must be written
* @param nameOnly true if only the property name element should be generated
* @param generatedXML the current generated XML for the PROPFIND response
*
* @return true if a property was specified and a corresponding dead property was found on the resource, false
* otherwise
*/
boolean propfind(String resource, Node property, boolean nameOnly, XMLWriter generatedXML);
/**
* Apply proppatch to the specified resource.
*
* @param resource the resource path on which to apply the proppatch
* @param operations the set and remove to apply, the final status codes of the result should be set on each
* operation
*/
void proppatch(String resource, ArrayList<ProppatchOperation> operations);
}
// ----------------------------------------- ProppatchOperation Inner Class
/**
* Represents a PROPPATCH sub operation to be performed.
*/
public static class ProppatchOperation {
private final PropertyUpdateType updateType;
private final Node propertyNode;
private final boolean protectedProperty;
private int statusCode = HttpServletResponse.SC_OK;
/**
* PROPPATCH operation constructor.
*
* @param updateType the update type, either SET or REMOVE
* @param propertyNode the XML node that contains the property name (and value if SET)
*/
public ProppatchOperation(PropertyUpdateType updateType, Node propertyNode) {
this.updateType = updateType;
this.propertyNode = propertyNode;
String davName = getDAVNode(propertyNode);
// displayname and getcontentlanguage are the DAV: properties that should not be protected
protectedProperty =
davName != null && (!(davName.equals("displayname") || davName.equals("getcontentlanguage")));
}
/**
* @return the updateType for this operation
*/
public PropertyUpdateType getUpdateType() {
return this.updateType;
}
/**
* @return the propertyNode the XML node that contains the property name (and value if SET)
*/
public Node getPropertyNode() {
return this.propertyNode;
}
/**
* @return the statusCode to set as a result of the operation
*/
public int getStatusCode() {
return this.statusCode;
}
/**
* @param statusCode the statusCode to set as a result of the operation
*/
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
/**
* @return <code>true</code> if the property is protected
*/
public boolean getProtectedProperty() {
return this.protectedProperty;
}
}
/**
* Type of PROPFIND request.
*/
public enum PropfindType {
FIND_BY_PROPERTY,
FIND_ALL_PROP,
FIND_PROPERTY_NAMES
}
/**
* Type of property update in a PROPPATCH.
*/
public enum PropertyUpdateType {
SET,
REMOVE
}
// ------------------------------------------------------ Protected Methods
/**
* Return JAXP document builder instance.
*
* @return the document builder
*
* @throws ServletException document builder creation failed (wrapped <code>ParserConfigurationException</code>
* exception)
*/
protected DocumentBuilder getDocumentBuilder() throws ServletException {
DocumentBuilder documentBuilder;
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setExpandEntityReferences(false);
documentBuilder = documentBuilderFactory.newDocumentBuilder();
documentBuilder.setEntityResolver(new WebdavResolver(this.getServletContext()));
} catch (ParserConfigurationException e) {
throw new ServletException(sm.getString("webdavservlet.jaxpfailed"));
}
return documentBuilder;
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final String path = getRelativePath(req);
// Error page check needs to come before special path check since
// custom error pages are often located below WEB-INF so they are
// not directly accessible.
if (req.getDispatcherType() == DispatcherType.ERROR) {
doGet(req, resp);
return;
}
// Block access to special subdirectories.
// DefaultServlet assumes it services resources from the root of the web app
// and doesn't add any special path protection
// WebdavServlet remounts the webapp under a new path, so this check is
// necessary on all methods (including GET).
if (isSpecialPath(path)) {
resp.sendError(WebdavStatus.SC_NOT_FOUND);
return;
}
final String method = req.getMethod();
if (debug > 0) {
log("[" + method + "] " + path);
}
switch (method) {
case Method.PROPFIND -> doPropfind(req, resp);
case Method.PROPPATCH -> doProppatch(req, resp);
case Method.MKCOL -> doMkcol(req, resp);
case Method.COPY -> doCopy(req, resp);
case Method.MOVE -> doMove(req, resp);
case Method.LOCK -> doLock(req, resp);
case Method.UNLOCK -> doUnlock(req, resp);
// DefaultServlet processing
default -> super.service(req, resp);
}
}
@Override
protected boolean checkIfHeaders(HttpServletRequest request, HttpServletResponse response, WebResource resource)
throws IOException {
// Skip regular HTTP evaluation for a null resource
if (resource != null && !super.checkIfHeaders(request, response, resource)) {
return false;
}
// Process the WebDAV If header using Apache Jackrabbit code
String ifHeaderValue = request.getHeader("If");
if (ifHeaderValue != null) {
WebdavIfHeader ifHeader = new WebdavIfHeader(getUriPrefix(request), ifHeaderValue);
if (!ifHeader.hasValue()) {
// Allow bad if syntax, will only be used for lock tokens
return !strictIfProcessing;
}
String path = getRelativePath(request);
// Get all hrefs from the if header
Iterator<String> hrefs = ifHeader.getResources();
String currentPath;
String currentHref;
WebResource currentWebResource;
if (hrefs.hasNext()) {
currentHref = hrefs.next();
currentPath = getPathFromHref(currentHref, request);
if (currentPath == null) {
// The path was invalid
return false;
}
currentWebResource = resources.getResource(currentPath);
} else {
currentPath = path;
currentHref = getEncodedPath(path, resource, request);
currentWebResource = resource;
}
// Iterate over all resources
do {
boolean exists = currentWebResource != null && currentWebResource.exists();
String eTag = exists ? generateETag(currentWebResource) : "";
// Collect all locks active on resource
ArrayList<String> lockTokens = new ArrayList<>();
// No lock evaluation for non existing paths in strict mode
// Problem: when doing a put with a locked parent folder, need to submit a tagged production with
// the parent path and the token, simply submitting the token in the if would fail the precondition.
if (!strictIfProcessing || exists) {
String parentPath = currentPath;
do {
LockInfo parentLock = resourceLocks.get(parentPath);
if (parentLock != null) {
if (parentLock.hasExpired()) {
resourceLocks.remove(parentPath);
} else {
// parentPath == currentPath is a check for the first loop
if (parentPath == currentPath || parentLock.depth > 0) {
if (parentLock.isExclusive()) {
lockTokens.add(LOCK_SCHEME + parentLock.token);
} else {
parentLock.sharedTokens.removeIf(token -> sharedLocks.get(token) == null);
if (parentLock.sharedTokens.isEmpty()) {
resourceLocks.remove(parentLock.path);
}
for (String token : parentLock.sharedTokens) {
LockInfo sharedLock = sharedLocks.get(token);
if (sharedLock != null) {
if (parentPath == currentPath || sharedLock.depth > 0) {
lockTokens.add(LOCK_SCHEME + token);
}
}
}
}
}
}
}
int slash = parentPath.lastIndexOf('/');
if (slash < 0) {
break;
}
parentPath = parentPath.substring(0, slash);
} while (true);
}
// Evaluation
if (ifHeader.matches(currentHref, lockTokens, eTag)) {
return true;
}
if (hrefs.hasNext()) {
currentHref = hrefs.next();
currentPath = getPathFromHref(currentHref, request);
if (currentPath == null) {
// The path was invalid
return false;
}
currentWebResource = resources.getResource(currentPath);
} else {
break;
}
} while (true);
return false;
}
return true;
}
/**
* Override the DefaultServlet implementation and only use the PathInfo. If the ServletPath is non-null, it will be
* because the WebDAV servlet has been mapped to a url other than /* to configure editing at different url than
* normal viewing.
*
* @param request The servlet request we are processing
* @param allowEmptyPath Used only to identify a call from DefaultServlet, to avoid removing the trailing slash
*
* @return the relative path
*/
@Override
protected String getRelativePath(HttpServletRequest request, boolean allowEmptyPath) {
if (serveSubpathOnly) {
return super.getRelativePath(request, allowEmptyPath);
}
String pathInfo;
if (request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null) {
// For includes, get the info from the attributes
pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
} else {
pathInfo = request.getPathInfo();
}
StringBuilder result = new StringBuilder();
if (pathInfo != null) {
result.append(pathInfo);
}
if (result.isEmpty()) {
result.append('/');
}
String resultString = result.toString();
if (!allowEmptyPath && resultString.length() > 1 && resultString.endsWith("/")) {
resultString = resultString.substring(0, resultString.length() - 1);
}
return resultString;
}
@Override
protected String getPathPrefix(final HttpServletRequest request) {
if (serveSubpathOnly) {
return super.getPathPrefix(request);
}
// Repeat the servlet path (e.g. /webdav/) in the listing path
String contextPath = request.getContextPath();
if (request.getServletPath() != null) {
contextPath = contextPath + request.getServletPath();
}
return contextPath;
}
@Override
protected String determineMethodsAllowed(HttpServletRequest req) {
WebResource resource = resources.getResource(getRelativePath(req));
// These methods are always allowed. They may return a 404 (not a 405)
// if the resource does not exist.
StringBuilder methodsAllowed = new StringBuilder("OPTIONS, GET, POST, HEAD");
if (!isReadOnly()) {
methodsAllowed.append(", DELETE");
if (!resource.isDirectory()) {
methodsAllowed.append(", PUT");
}
}
// Trace - assume disabled unless we can prove otherwise
if (req instanceof RequestFacade && ((RequestFacade) req).getAllowTrace()) {
methodsAllowed.append(", TRACE");
}
methodsAllowed.append(", LOCK, UNLOCK, PROPPATCH, COPY, MOVE");
if (isListings()) {
methodsAllowed.append(", PROPFIND");
}
if (!resource.exists()) {
methodsAllowed.append(", MKCOL");
}
return methodsAllowed.toString();
}
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.addHeader("DAV", "1,2,3");
resp.addHeader("Allow", determineMethodsAllowed(req));
resp.addHeader("MS-Author-Via", "DAV");
}
/**
* PROPFIND Method.
*
* @param req The Servlet request
* @param resp The Servlet response
*
* @throws ServletException If an error occurs
* @throws IOException If an IO error occurs
*/
protected void doPropfind(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (!isListings()) {
sendNotAllowed(req, resp);
return;
}
String path = getRelativePath(req);
// Properties which are to be displayed.
List<Node> properties = new ArrayList<>();
// Propfind depth
int depth;
// Propfind type
PropfindType type = null;
String depthStr = req.getHeader("Depth");
if (depthStr == null) {
depth = maxDepth;
} else {
switch (depthStr) {
case "0" -> depth = 0;
case "1" -> depth = 1;
case "infinity" -> depth = maxDepth;
default -> {
resp.sendError(WebdavStatus.SC_BAD_REQUEST);
return;
}
}
}
byte[] body;
try (InputStream is = req.getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream()) {
IOTools.flow(is, os);
body = os.toByteArray();
} catch (IOException ioe) {
resp.sendError(WebdavStatus.SC_BAD_REQUEST);
return;
}
if (body.length > 0) {
DocumentBuilder documentBuilder = getDocumentBuilder();
try {
Document document = documentBuilder.parse(new InputSource(new ByteArrayInputStream(body)));
// Get the root element of the document
Element rootElement = document.getDocumentElement();
if (!"propfind".equals(getDAVNode(rootElement))) {
resp.sendError(WebdavStatus.SC_BAD_REQUEST);
return;
}
NodeList childList = rootElement.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
Node currentNode = childList.item(i);
switch (currentNode.getNodeType()) {
case Node.TEXT_NODE:
break;
case Node.ELEMENT_NODE:
String nodeName = getDAVNode(currentNode);
if ("prop".equals(nodeName)) {
if (type != null) {
// Another was already defined
resp.sendError(WebdavStatus.SC_BAD_REQUEST);
return;
}
type = PropfindType.FIND_BY_PROPERTY;
NodeList propChildList = currentNode.getChildNodes();
for (int j = 0; j < propChildList.getLength(); j++) {
Node currentNode2 = propChildList.item(j);
switch (currentNode2.getNodeType()) {
case Node.TEXT_NODE:
break;
case Node.ELEMENT_NODE:
properties.add(currentNode2);
break;
}
}
}
if ("propname".equals(nodeName)) {
if (type != null) {
// Another was already defined
resp.sendError(WebdavStatus.SC_BAD_REQUEST);
return;
}
type = PropfindType.FIND_PROPERTY_NAMES;
}
if ("allprop".equals(nodeName)) {
if (type != null) {
// Another was already defined
resp.sendError(WebdavStatus.SC_BAD_REQUEST);
return;
}
type = PropfindType.FIND_ALL_PROP;
}
break;
}
}
} catch (SAXException | IOException e) {
// Something went wrong - bad request
resp.sendError(WebdavStatus.SC_BAD_REQUEST);
return;
}
if (type == null) {
// Nothing meaningful in the propfind element
resp.sendError(WebdavStatus.SC_BAD_REQUEST);
return;
}
} else {
type = PropfindType.FIND_ALL_PROP;
}
WebResource resource = resources.getResource(path);
if (!checkIfHeaders(req, resp, resource)) {
resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
return;
}
if (!resource.exists()) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
resp.setStatus(WebdavStatus.SC_MULTI_STATUS);
resp.setContentType("text/xml; charset=UTF-8");
// Create multistatus object
XMLWriter generatedXML = new XMLWriter(resp.getWriter());
generatedXML.writeXMLHeader();
generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING);
if (depth == 0) {
propfindResource(generatedXML, getEncodedPath(path, resource, req), path, type, properties,
resource.isFile(), resource.getCreation(), resource.getLastModified(), resource.getContentLength(),
getServletContext().getMimeType(resource.getName()), generateETag(resource));
} else {
// The stack always contains the object of the current level
Deque<String> stack = new ArrayDeque<>();
stack.addFirst(path);
// Stack of the objects one level below
Deque<String> stackBelow = new ArrayDeque<>();
while ((!stack.isEmpty()) && (depth >= 0)) {
String currentPath = stack.remove();
// Exclude any resource in the /WEB-INF and /META-INF subdirectories
if (isSpecialPath(currentPath)) {
continue;
}
resource = resources.getResource(currentPath);
// File is in directory listing but doesn't appear to exist
// Broken symlink or odd permission settings?
if (resource.exists()) {
propfindResource(generatedXML, getEncodedPath(currentPath, resource, req), currentPath, type,
properties, resource.isFile(), resource.getCreation(), resource.getLastModified(),
resource.getContentLength(), getServletContext().getMimeType(resource.getName()),
generateETag(resource));
}
if (resource.isDirectory() && (depth > 0)) {
String[] entries = resources.list(currentPath);
for (String entry : entries) {
String newPath = currentPath;
if (!(newPath.endsWith("/"))) {
newPath += "/";
}
newPath += entry;
stackBelow.addFirst(newPath);
}
}
if (stack.isEmpty()) {
depth--;
stack = stackBelow;
stackBelow = new ArrayDeque<>();
}
generatedXML.sendData();
}
}
generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING);
generatedXML.sendData();
}
/**
* PROPPATCH Method. Dead properties support is a SHOULD in the specification and are not implemented.
*
* @param req The Servlet request