-
Notifications
You must be signed in to change notification settings - Fork 138
/
DefaultServlet.java
2420 lines (2033 loc) · 84.8 KB
/
DefaultServlet.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
/*
* Copyright (c) 2022 Contributors to the Eclipse Foundation
* Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved.
* Copyright 2004 The Apache Software Foundation
*
* 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 static org.glassfish.api.naming.SimpleJndiName.JNDI_CTX_JAVA_COMPONENT;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.UnavailableException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.security.AccessController;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.catalina.Globals;
import org.apache.catalina.LogFacade;
import org.apache.catalina.core.ContextsAdapterUtility;
import org.apache.catalina.util.ServerInfo;
import org.apache.catalina.util.URLEncoder;
import org.apache.naming.resources.CacheEntry;
import org.apache.naming.resources.ProxyDirContext;
import org.apache.naming.resources.Resource;
import org.apache.naming.resources.ResourceAttributes;
import org.apache.tomcat.util.security.PrivilegedGetTccl;
import org.apache.tomcat.util.security.PrivilegedSetTccl;
import org.glassfish.grizzly.http.server.util.AlternateDocBase;
import org.glassfish.web.util.HtmlEntityEncoder;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.ext.EntityResolver2;
/**
* <p>
* The default resource-serving servlet for most web applications, used to serve static resources such as HTML pages and
* images.
* </p>
* <p>
* This servlet is intended to be mapped to <em>/</em> e.g.:
* </p>
*
* <pre>
* <servlet-mapping>
* <servlet-name>default</servlet-name>
* <url-pattern>/</url-pattern>
* </servlet-mapping>
* </pre>
* <p>
* It can be mapped to sub-paths, however in all cases resources are served from the web appplication resource root
* using the full path from the root of the web application context. <br/>
* e.g. given a web application structure:
* </p>
*
* <pre>
* /context
* /images
* tomcat2.jpg
* /static
* /images
* tomcat.jpg
* </pre>
* <p>
* ... and a servlet mapping that maps only <code>/static/*</code> to the default servlet:
* </p>
*
* <pre>
* <servlet-mapping>
* <servlet-name>default</servlet-name>
* <url-pattern>/static/*</url-pattern>
* </servlet-mapping>
* </pre>
* <p>
* Then a request to <code>/context/static/images/tomcat.jpg</code> will succeed while a request to
* <code>/context/images/tomcat2.jpg</code> will fail.
* </p>
*
* @author Craig R. McClanahan
* @author Remy Maucherat
* @version $Revision: 1.16 $ $Date: 2007/06/06 16:01:12 $
*/
public class DefaultServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected static final ResourceBundle rb = LogFacade.getLogger().getResourceBundle();
private static final DocumentBuilderFactory factory;
private static final SecureEntityResolver secureEntityResolver;
// ----------------------------------------------------- Instance Variables
/**
* The debugging detail level for this servlet.
*/
protected int debug = 0;
/**
* The input buffer size to use when serving resources.
*/
protected int input = 2048;
/**
* Should we generate directory listings?
*/
protected volatile boolean listings = false;
/**
* The sorting mechanism for directory listings
*/
protected SortedBy sortedBy = SortedBy.NAME;
/**
* Read only flag. By default, it's set to true.
*/
protected boolean readOnly = true;
/**
* The output buffer size to use when serving resources.
*/
protected int output = 2048;
/**
* Array containing the safe characters set.
*/
protected static final URLEncoder urlEncoder;
/**
* Allow customized directory listing per directory.
*/
protected String localXsltFile = null;
/**
* Allow customized directory listing per context.
*/
protected String contextXsltFile = null;
/**
* Allow customized directory listing per instance.
*/
protected String globalXsltFile = null;
/**
* Allow a readme file to be included.
*/
protected String readmeFile = null;
/**
* Proxy directory context.
*/
protected transient ProxyDirContext resources = null;
/**
* Alternate doc bases
*/
protected transient ArrayList<AlternateDocBase> alternateDocBases = null;
/**
* File encoding to be used when reading static files. If none is specified the platform default is used.
*/
protected String fileEncoding = null;
/**
* Minimum size for sendfile usage in bytes.
*/
protected int sendfileSize = 48 * 1024;
/**
* Should the Accept-Ranges: bytes header be send with static resources?
*/
protected boolean useAcceptRanges = true;
/**
* Full range marker.
*/
protected static final ArrayList<Range> FULL = new ArrayList<>();
/**
* The maximum number of items allowed in Range header. -1 means unbounded.
*/
protected int maxHeaderRangeItems = 10;
// ----------------------------------------------------- Static Initializer
/**
* GMT timezone - all HTTP dates are on GMT
*/
static {
urlEncoder = new URLEncoder();
urlEncoder.addSafeCharacter('-');
urlEncoder.addSafeCharacter('_');
urlEncoder.addSafeCharacter('.');
urlEncoder.addSafeCharacter('*');
urlEncoder.addSafeCharacter('/');
factory = null;
secureEntityResolver = null;
}
/**
* MIME multipart separation string
*/
protected static final String mimeSeparation = "CATALINA_MIME_BOUNDARY";
/**
* JNDI resources name.
*/
protected static final String RESOURCES_JNDI_NAME = JNDI_CTX_JAVA_COMPONENT + "Resources";
/**
* Size of file transfer buffer in bytes.
*/
protected static final int BUFFER_SIZE = 4096;
// --------------------------------------------------------- Public Methods
/**
* Finalize this servlet.
*/
@Override
public void destroy() {
// NOOP
}
/**
* Initialize this servlet.
*/
@Override
public void init() throws ServletException {
ServletConfig sc = getServletConfig();
if (sc.getInitParameter("debug") != null) {
debug = Integer.parseInt(sc.getInitParameter("debug"));
}
if (sc.getInitParameter("input") != null) {
input = Integer.parseInt(sc.getInitParameter("input"));
}
if (sc.getInitParameter("output") != null) {
output = Integer.parseInt(sc.getInitParameter("output"));
}
listings = Boolean.parseBoolean(sc.getInitParameter("listings"));
String sortedByInitParam = sc.getInitParameter("sortedBy");
if (sortedByInitParam != null) {
sortedBy = Enum.valueOf(SortedBy.class, sortedByInitParam);
}
if (sc.getInitParameter("readonly") != null) {
readOnly = Boolean.parseBoolean(sc.getInitParameter("readonly"));
}
if (sc.getInitParameter("sendfileSize") != null) {
sendfileSize = Integer.parseInt(sc.getInitParameter("sendfileSize")) * 1024;
}
if (sc.getInitParameter("maxHeaderRangeItems") != null) {
maxHeaderRangeItems = Integer.parseInt(sc.getInitParameter("maxHeaderRangeItems"));
}
fileEncoding = sc.getInitParameter("fileEncoding");
globalXsltFile = sc.getInitParameter("globalXsltFile");
contextXsltFile = sc.getInitParameter("contextXsltFile");
localXsltFile = sc.getInitParameter("localXsltFile");
readmeFile = sc.getInitParameter("readmeFile");
if (sc.getInitParameter("useAcceptRanges") != null) {
useAcceptRanges = Boolean.parseBoolean(sc.getInitParameter("useAcceptRanges"));
}
// Sanity check on the specified buffer sizes
if (input < 256) {
input = 256;
}
if (output < 256) {
output = 256;
}
if (debug > 0) {
log("DefaultServlet.init: input buffer size=" + input + ", output buffer size=" + output);
}
// Load the proxy dir context.
resources = (ProxyDirContext) getServletContext().getAttribute(Globals.RESOURCES_ATTR);
if (resources == null) {
try {
resources = (ProxyDirContext) new InitialContext().lookup(RESOURCES_JNDI_NAME);
} catch (NamingException e) {
throw new ServletException("No resources", e);
} catch (ClassCastException e) {
// Failed : Not the right type
}
}
if (resources == null) {
throw new UnavailableException("No resources");
}
try {
alternateDocBases = getAlternateDocBases();
} catch (ClassCastException e) {
// Failed : Not the right type
}
}
@SuppressWarnings("unchecked")
private ArrayList<AlternateDocBase> getAlternateDocBases() {
return (ArrayList<AlternateDocBase>) getServletContext().getAttribute(Globals.ALTERNATE_RESOURCES_ATTR);
}
/**
* Return if directory listings are enabled
*/
public boolean isListings() {
return this.listings;
}
/**
* Enables or disables directory listings for this DefaultServlet.
*
* @param listings true if directory listings are to be enabled, false otherwise
*/
public void setListings(boolean listings) {
this.listings = listings;
}
// ------------------------------------------------------ Protected Methods
/**
* Return the relative path associated with this servlet.
*
* @param request The servlet request we are processing
*/
protected String getRelativePath(HttpServletRequest request) {
// IMPORTANT: DefaultServlet can be mapped to '/' or '/path/*' but always
// serves resources from the web app root with context rooted paths.
// i.e. it can not be used to mount the web app root under a sub-path
// This method must construct a complete context rooted path, although
// subclasses can change this behaviour.
// Are we being processed by a RequestDispatcher.include()?
if (request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null) {
String result = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
if (result == null) {
result = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
}
if ((result == null) || (result.equals(""))) {
result = "/";
}
return (result);
}
// No, extract the desired path directly from the request
String result = request.getPathInfo();
if (result == null) {
result = request.getServletPath();
} else {
result = request.getServletPath() + result;
}
if ((result == null) || (result.equals(""))) {
result = "/";
}
return (result);
}
/**
* Process a GET request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Serve the requested resource, including the data content
serveResource(request, response, true);
}
/**
* Process a HEAD request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doHead(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Serve the requested resource, without the data content
serveResource(request, response, false);
}
/**
* Process a POST request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doGet(request, response);
}
/**
* Process a POST request for the specified resource.
*
* @param req The servlet request we are processing
* @param resp The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (readOnly) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String path = getRelativePath(req);
boolean exists = true;
try {
resources.lookup(path);
} catch (NamingException e) {
exists = false;
}
boolean result = true;
// Temp. content file used to support partial PUT
File contentFile = null;
Range range = parseContentRange(req, resp);
InputStream resourceInputStream = null;
// Append data specified in ranges to existing content for this
// resource - create a temp. file on the local filesystem to
// perform this operation
// Assume just one range is specified for now
if (range != null) {
contentFile = executePartialPut(req, range, path);
resourceInputStream = new FileInputStream(contentFile);
} else {
resourceInputStream = req.getInputStream();
}
try {
Resource newResource = new Resource(resourceInputStream);
// FIXME: Add attributes
if (exists) {
resources.rebind(path, newResource);
} else {
resources.bind(path, newResource);
}
} catch (NamingException e) {
result = false;
}
if (result) {
if (exists) {
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
resp.setStatus(HttpServletResponse.SC_CREATED);
}
} else {
resp.sendError(HttpServletResponse.SC_CONFLICT);
}
}
/**
* Handle a partial PUT. New content specified in request is appended to existing content in oldRevisionContent (if
* present). This code does not support simultaneous partial updates to the same resource.
*/
protected File executePartialPut(HttpServletRequest req, Range range, String path) throws IOException {
// Append data specified in ranges to existing content for this
// resource - create a temp. file on the local filesystem to
// perform this operation
File tempDir = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
// Convert all '/' characters to '.' in resourcePath
String convertedResourcePath = path.replace('/', '.');
File contentFile = new File(tempDir, convertedResourcePath);
if (contentFile.createNewFile()) {
// Clean up contentFile when Tomcat is terminated
contentFile.deleteOnExit();
}
Resource oldResource = null;
try {
Object obj = resources.lookup(path);
if (obj instanceof Resource) {
oldResource = (Resource) obj;
}
} catch (NamingException e) {
// Ignore
}
RandomAccessFile randAccessContentFile = new RandomAccessFile(contentFile, "rw");
try {
// Copy data in oldRevisionContent to contentFile
if (oldResource != null) {
BufferedInputStream bufOldRevStream = null;
try {
bufOldRevStream = new BufferedInputStream(oldResource.streamContent(), BUFFER_SIZE);
int numBytesRead;
byte[] copyBuffer = new byte[BUFFER_SIZE];
while ((numBytesRead = bufOldRevStream.read(copyBuffer)) != -1) {
randAccessContentFile.write(copyBuffer, 0, numBytesRead);
}
} finally {
if (bufOldRevStream != null) {
bufOldRevStream.close();
}
}
}
randAccessContentFile.setLength(range.length);
// Append data in request input stream to contentFile
randAccessContentFile.seek(range.start);
int numBytesRead;
byte[] transferBuffer = new byte[BUFFER_SIZE];
BufferedInputStream requestBufInStream = null;
try {
requestBufInStream = new BufferedInputStream(req.getInputStream(), BUFFER_SIZE);
while ((numBytesRead = requestBufInStream.read(transferBuffer)) != -1) {
randAccessContentFile.write(transferBuffer, 0, numBytesRead);
}
} finally {
if (requestBufInStream != null) {
requestBufInStream.close();
}
}
} finally {
randAccessContentFile.close();
}
return contentFile;
}
/**
* Process a POST request for the specified resource.
*
* @param req The servlet request we are processing
* @param resp The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (readOnly) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String path = getRelativePath(req);
boolean exists = true;
try {
resources.lookup(path);
} catch (NamingException e) {
exists = false;
}
if (exists) {
boolean result = true;
try {
resources.unbind(path);
} catch (NamingException e) {
result = false;
}
if (result) {
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
} else {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Check if the conditions specified in the optional If headers are satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resourceAttributes The resource information
* @return boolean true if the resource meets all the specified conditions, and false if any of the conditions is not
* satisfied, in which case request processing is stopped
*/
protected boolean checkIfHeaders(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes)
throws IOException {
return checkIfMatch(request, response, resourceAttributes) && checkIfModifiedSince(request, response, resourceAttributes)
&& checkIfNoneMatch(request, response, resourceAttributes) && checkIfUnmodifiedSince(request, response, resourceAttributes);
}
/**
* URL rewriter.
*
* @param path Path which has to be rewritten
*/
protected String rewriteUrl(String path) {
return urlEncoder.encode(path);
}
/**
* Display the size of a file.
*/
protected void displaySize(StringBuilder buf, int filesize) {
int leftside = filesize / 1024;
int rightside = (filesize % 1024) / 103; // makes 1 digit
// To avoid 0.0 for non-zero file, we bump to 0.1
if (leftside == 0 && rightside == 0 && filesize != 0) {
rightside = 1;
}
buf.append(leftside).append(".").append(rightside);
buf.append(" KB");
}
/**
* Serve the specified resource, optionally including the data content.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param content Should the content be included?
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content)
throws IOException, ServletException {
// Identify the requested resource path
String path = getRelativePath(request);
if (debug > 0) {
if (content) {
log("DefaultServlet.serveResource: Serving resource '" + path + "' headers and data");
} else {
log("DefaultServlet.serveResource: Serving resource '" + path + "' headers only");
}
}
CacheEntry cacheEntry = null;
ProxyDirContext proxyDirContext = resources;
if (alternateDocBases == null || alternateDocBases.size() == 0) {
cacheEntry = proxyDirContext.lookupCache(path);
} else {
AlternateDocBase match = AlternateDocBase.findMatch(path, alternateDocBases);
if (match != null) {
cacheEntry = ((ProxyDirContext) ContextsAdapterUtility.unwrap(match.getResources())).lookupCache(path);
} else {
// None of the url patterns for alternate docbases matched
cacheEntry = proxyDirContext.lookupCache(path);
}
}
if (!cacheEntry.exists) {
// Check if we're included so we can return the appropriate
// missing resource name in the error
String requestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
/*
* IASRI 4878272 if (requestUri == null) { requestUri = request.getRequestURI(); } else {
*/
if (requestUri != null) {
/*
* We're included, and the response.sendError() below is going to be ignored by the including resource (see SRV.8.3,
* "The Include Method"). Therefore, the only way we can let the including resource know about the missing resource is
* by throwing an exception
*/
throw new FileNotFoundException(requestUri);
}
/*
* IASRI 4878272 response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri);
*/
// BEGIN IASRI 4878272
response.sendError(HttpServletResponse.SC_NOT_FOUND);
// END IASRI 4878272
return;
}
// If the resource is not a collection, and the resource path
// ends with "/" or "\", return NOT FOUND
if (cacheEntry.context == null) {
if (path.endsWith("/") || (path.endsWith("\\"))) {
/*
* IASRI 4878272 // Check if we're included so we can return the appropriate // missing resource name in the error
* String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) {
* requestUri = request.getRequestURI(); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri);
*/
// BEGIN IASRI 4878272
response.sendError(HttpServletResponse.SC_NOT_FOUND);
// END IASRI 4878272
return;
}
}
// Check if the conditions specified in the optional If headers are
// satisfied.
if (cacheEntry.context == null) {
// Checking If headers
boolean included = (request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH) != null);
if (!included && !checkIfHeaders(request, response, cacheEntry.attributes)) {
return;
}
}
// Find content type.
String contentType = cacheEntry.attributes.getMimeType();
if (contentType == null && !cacheEntry.attributes.isMimeTypeInitialized()) {
contentType = getServletContext().getMimeType(cacheEntry.name);
cacheEntry.attributes.setMimeType(contentType);
}
ArrayList<Range> ranges = null;
long contentLength = -1L;
if (cacheEntry.context != null) {
// Skip directory listings if we have been configured to
// suppress them
if (!listings) {
/*
* IASRI 4878272 response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
*/
// BEGIN IASRI 4878272
response.sendError(HttpServletResponse.SC_NOT_FOUND);
// END IASRI 4878272
return;
}
contentType = "text/html;charset=UTF-8";
} else {
if (useAcceptRanges) {
// Accept ranges header
response.setHeader("Accept-Ranges", "bytes");
}
// Parse range specifier
ranges = parseRange(request, response, cacheEntry.attributes);
// ETag header
response.setHeader("ETag", cacheEntry.attributes.getETag());
// Last-Modified header
response.setHeader("Last-Modified", cacheEntry.attributes.getLastModifiedHttp());
// Get content length
contentLength = cacheEntry.attributes.getContentLength();
// Special case for zero length files, which would cause a
// (silent) ISE when setting the output buffer size
if (contentLength == 0L) {
content = false;
}
}
ServletOutputStream ostream = null;
PrintWriter writer = null;
if (content) {
// Trying to retrieve the servlet output stream
try {
ostream = response.getOutputStream();
} catch (IllegalStateException e) {
// If it fails, we try to get a Writer instead if we're
// trying to serve a text file
if ((contentType == null) || (contentType.startsWith("text")) || (contentType.startsWith("xml"))) {
writer = response.getWriter();
} else {
throw e;
}
}
}
if ((cacheEntry.context != null) || (((ranges == null) || (ranges.isEmpty())) && (request.getHeader("Range") == null))
|| (ranges == FULL)) {
// Set the appropriate output headers
if (contentType != null) {
if (debug > 0) {
log("DefaultServlet.serveFile: contentType='" + contentType + "'");
}
response.setContentType(contentType);
}
if ((cacheEntry.resource != null) && (contentLength >= 0)) {
if (debug > 0) {
log("DefaultServlet.serveFile: contentLength=" + contentLength);
}
if (contentLength < Integer.MAX_VALUE) {
response.setContentLength((int) contentLength);
} else {
// Set the content-length as String to be able to use a long
response.setHeader("content-length", "" + contentLength);
}
}
InputStream renderResult = null;
if (cacheEntry.context != null) {
if (content) {
// Serve the directory browser
renderResult = render(request.getContextPath(), cacheEntry, proxyDirContext);
}
}
// Copy the input stream to our output stream (if requested)
if (content) {
try {
response.setBufferSize(output);
} catch (IllegalStateException e) {
// Silent catch
}
if (ostream != null) {
if (!checkSendfile(request, response, cacheEntry, contentLength, null)) {
copy(cacheEntry, renderResult, ostream);
}
} else {
copy(cacheEntry, renderResult, writer);
}
}
} else {
if ((ranges == null) || (ranges.isEmpty())) {
return;
}
if (maxHeaderRangeItems >= 0 && ranges.size() > maxHeaderRangeItems) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
// Partial content response.
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
if (ranges.size() == 1) {
Range range = ranges.get(0);
response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length);
long length = range.end - range.start + 1;
if (length < Integer.MAX_VALUE) {
response.setContentLength((int) length);
} else {
// Set the content-length as String to be able to use a long
response.setHeader("content-length", "" + length);
}
if (contentType != null) {
if (debug > 0) {
log("DefaultServlet.serveFile: contentType='" + contentType + "'");
}
response.setContentType(contentType);
}
if (content) {
try {
response.setBufferSize(output);
} catch (IllegalStateException e) {
// Silent catch
}
if (ostream != null) {
if (!checkSendfile(request, response, cacheEntry, range.end - range.start + 1, range)) {
copy(cacheEntry, ostream, range);
}
} else {
copy(cacheEntry, writer, range);
}
}
} else {
response.setContentType("multipart/byteranges; boundary=" + mimeSeparation);
if (content) {
try {
response.setBufferSize(output);
} catch (IllegalStateException e) {
// Silent catch
}
if (ostream != null) {
copy(cacheEntry, ostream, ranges.iterator(), contentType);
} else {
copy(cacheEntry, writer, ranges.iterator(), contentType);
}
}
}
}
}
/**
* Parse the content-range header.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @return Range
*/
protected Range parseContentRange(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Retrieving the content-range header (if any is specified
String rangeHeader = request.getHeader("Content-Range");