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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
|
/*
* 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.connector;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.SessionTrackingMode;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import org.apache.catalina.Context;
import org.apache.catalina.Session;
import org.apache.catalina.security.SecurityUtil;
import org.apache.catalina.util.SessionConfig;
import org.apache.coyote.ActionCode;
import org.apache.coyote.ContinueResponseTiming;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.buf.CharChunk;
import org.apache.tomcat.util.buf.UEncoder;
import org.apache.tomcat.util.buf.UEncoder.SafeCharsSet;
import org.apache.tomcat.util.buf.UriUtil;
import org.apache.tomcat.util.http.FastHttpDateFormat;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.parser.MediaTypeCache;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.util.security.Escape;
/**
* Wrapper object for the Coyote response.
*/
public class Response implements HttpServletResponse {
private static final Log log = LogFactory.getLog(Response.class);
protected static final StringManager sm = StringManager.getManager(Response.class);
private static final MediaTypeCache MEDIA_TYPE_CACHE = new MediaTypeCache(100);
protected static final int SC_EARLY_HINTS = 103;
// ----------------------------------------------------- Instance Variables
public Response() {
this(OutputBuffer.DEFAULT_BUFFER_SIZE);
}
public Response(int outputBufferSize) {
outputBuffer = new OutputBuffer(outputBufferSize);
}
// ------------------------------------------------------------- Properties
/**
* Coyote response.
*/
protected org.apache.coyote.Response coyoteResponse;
/**
* Set the Coyote response.
*
* @param coyoteResponse The Coyote response
*/
public void setCoyoteResponse(org.apache.coyote.Response coyoteResponse) {
this.coyoteResponse = coyoteResponse;
outputBuffer.setResponse(coyoteResponse);
}
/**
* @return the Coyote response.
*/
public org.apache.coyote.Response getCoyoteResponse() {
return this.coyoteResponse;
}
/**
* @return the Context within which this Request is being processed.
*/
public Context getContext() {
return request.getContext();
}
/**
* The associated output buffer.
*/
protected final OutputBuffer outputBuffer;
/**
* The associated output stream.
*/
protected CoyoteOutputStream outputStream;
/**
* The associated writer.
*/
protected CoyoteWriter writer;
/**
* The application commit flag.
*/
protected boolean appCommitted = false;
/**
* The included flag.
*/
protected boolean included = false;
/**
* The characterEncoding flag
*/
private boolean isCharacterEncodingSet = false;
/**
* Using output stream flag.
*/
protected boolean usingOutputStream = false;
/**
* Using writer flag.
*/
protected boolean usingWriter = false;
/**
* URL encoder.
*/
protected final UEncoder urlEncoder = new UEncoder(SafeCharsSet.WITH_SLASH);
/**
* Recyclable buffer to hold the redirect URL.
*/
protected final CharChunk redirectURLCC = new CharChunk();
/*
* Not strictly required but it makes generating HTTP/2 push requests a lot easier if these are retained until the
* response is recycled.
*/
private final List<Cookie> cookies = new ArrayList<>();
private HttpServletResponse applicationResponse = null;
// --------------------------------------------------------- Public Methods
/**
* Release all object references, and initialize instance variables, in preparation for reuse of this object.
*/
public void recycle() {
cookies.clear();
outputBuffer.recycle();
usingOutputStream = false;
usingWriter = false;
appCommitted = false;
included = false;
isCharacterEncodingSet = false;
applicationResponse = null;
if (getRequest().getDiscardFacades()) {
if (facade != null) {
facade.clear();
facade = null;
}
if (outputStream != null) {
outputStream.clear();
outputStream = null;
}
if (writer != null) {
writer.clear();
writer = null;
}
} else if (writer != null) {
writer.recycle();
}
}
public List<Cookie> getCookies() {
return cookies;
}
// ------------------------------------------------------- Response Methods
/**
* @return the number of bytes the application has actually written to the output stream. This excludes chunking,
* compression, etc. as well as headers.
*/
public long getContentWritten() {
return outputBuffer.getContentWritten();
}
/**
* @return the number of bytes the actually written to the socket. This includes chunking, compression, etc. but
* excludes headers.
*
* @param flush if <code>true</code> will perform a buffer flush first
*/
public long getBytesWritten(boolean flush) {
if (flush) {
try {
outputBuffer.flush();
} catch (IOException ioe) {
// Ignore - the client has probably closed the connection
}
}
return getCoyoteResponse().getBytesWritten(flush);
}
/**
* Set the application commit flag.
*
* @param appCommitted The new application committed flag value
*/
public void setAppCommitted(boolean appCommitted) {
this.appCommitted = appCommitted;
}
/**
* Application commit flag accessor.
*
* @return <code>true</code> if the application has committed the response
*/
public boolean isAppCommitted() {
return this.appCommitted || isCommitted() || isSuspended() ||
((getContentLength() > 0) && (getContentWritten() >= getContentLength()));
}
/**
* The request with which this response is associated.
*/
protected Request request = null;
/**
* @return the Request with which this Response is associated.
*/
public Request getRequest() {
return this.request;
}
/**
* Set the Request with which this Response is associated.
*
* @param request The new associated request
*/
public void setRequest(Request request) {
this.request = request;
}
/**
* The facade associated with this response.
*/
protected ResponseFacade facade = null;
/**
* @return the <code>ServletResponse</code> for which this object is the facade.
*/
public HttpServletResponse getResponse() {
if (facade == null) {
facade = new ResponseFacade(this);
}
if (applicationResponse == null) {
applicationResponse = facade;
}
return applicationResponse;
}
/**
* Set a wrapped HttpServletResponse to pass to the application. Components wishing to wrap the response should
* obtain the response via {@link #getResponse()}, wrap it and then call this method with the wrapped response.
*
* @param applicationResponse The wrapped response to pass to the application
*/
public void setResponse(HttpServletResponse applicationResponse) {
// Check the wrapper wraps this request
ServletResponse r = applicationResponse;
while (r instanceof HttpServletResponseWrapper) {
r = ((HttpServletResponseWrapper) r).getResponse();
}
if (r != facade) {
throw new IllegalArgumentException(sm.getString("response.illegalWrap"));
}
this.applicationResponse = applicationResponse;
}
/**
* Set the suspended flag.
*
* @param suspended The new suspended flag value
*/
public void setSuspended(boolean suspended) {
outputBuffer.setSuspended(suspended);
}
/**
* Suspended flag accessor.
*
* @return <code>true</code> if the response is suspended
*/
public boolean isSuspended() {
return outputBuffer.isSuspended();
}
/**
* Closed flag accessor.
*
* @return <code>true</code> if the response has been closed
*/
public boolean isClosed() {
return outputBuffer.isClosed();
}
/**
* Set the error flag.
*
* @return <code>false</code> if the error flag was already set
*
* @deprecated This method will be changed to return void in Tomcat 11 onwards
*/
@Deprecated
public boolean setError() {
return getCoyoteResponse().setError();
}
/**
* Error flag accessor.
*
* @return <code>true</code> if the response has encountered an error
*/
public boolean isError() {
return getCoyoteResponse().isError();
}
public boolean isErrorReportRequired() {
return getCoyoteResponse().isErrorReportRequired();
}
public boolean setErrorReported() {
return getCoyoteResponse().setErrorReported();
}
public void resetError() {
getCoyoteResponse().resetError();
}
/**
* Perform whatever actions are required to flush and close the output stream or writer, in a single operation.
*
* @exception IOException if an input/output error occurs
*/
public void finishResponse() throws IOException {
// Writing leftover bytes
outputBuffer.close();
}
/**
* @return the content length that was set or calculated for this Response.
*/
public int getContentLength() {
return getCoyoteResponse().getContentLength();
}
@Override
public String getContentType() {
return getCoyoteResponse().getContentType();
}
/**
* Return a PrintWriter that can be used to render error messages, regardless of whether a stream or writer has
* already been acquired.
*
* @return Writer which can be used for error reports. If the response is not an error report returned using
* sendError or triggered by an unexpected exception thrown during the servlet processing (and only in
* that case), null will be returned if the response stream has already been used.
*
* @exception IOException if an input/output error occurs
*/
public PrintWriter getReporter() throws IOException {
if (outputBuffer.isNew()) {
outputBuffer.checkConverter();
if (writer == null) {
writer = new CoyoteWriter(outputBuffer);
}
return writer;
} else {
return null;
}
}
// ------------------------------------------------ ServletResponse Methods
@Override
public void flushBuffer() throws IOException {
outputBuffer.flush();
}
@Override
public int getBufferSize() {
return outputBuffer.getBufferSize();
}
@Override
public String getCharacterEncoding() {
String charset = getCoyoteResponse().getCharacterEncoding();
if (charset != null) {
return charset;
}
Context context = getContext();
String result = null;
if (context != null) {
result = context.getResponseCharacterEncoding();
}
if (result == null) {
result = org.apache.coyote.Constants.DEFAULT_BODY_CHARSET.name();
}
return result;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (usingWriter) {
throw new IllegalStateException(sm.getString("coyoteResponse.getOutputStream.ise"));
}
usingOutputStream = true;
if (outputStream == null) {
outputStream = new CoyoteOutputStream(outputBuffer);
}
return outputStream;
}
@Override
public Locale getLocale() {
return getCoyoteResponse().getLocale();
}
@Override
public PrintWriter getWriter() throws IOException {
if (usingOutputStream) {
throw new IllegalStateException(sm.getString("coyoteResponse.getWriter.ise"));
}
if (request.getConnector().getEnforceEncodingInGetWriter()) {
/*
* If the response's character encoding has not been specified as described in
* <code>getCharacterEncoding</code> (i.e., the method just returns the default value
* <code>ISO-8859-1</code>), <code>getWriter</code> updates it to <code>ISO-8859-1</code> (with the effect
* that a subsequent call to getContentType() will include a charset=ISO-8859-1 component which will also be
* reflected in the Content-Type response header, thereby satisfying the Servlet spec requirement that
* containers must communicate the character encoding used for the servlet response's writer to the client).
*/
setCharacterEncoding(getCharacterEncoding());
}
usingWriter = true;
outputBuffer.checkConverter();
if (writer == null) {
writer = new CoyoteWriter(outputBuffer);
}
return writer;
}
@Override
public boolean isCommitted() {
return getCoyoteResponse().isCommitted();
}
@Override
public void reset() {
// Ignore any call from an included servlet
if (included) {
return;
}
getCoyoteResponse().reset();
outputBuffer.reset();
usingOutputStream = false;
usingWriter = false;
isCharacterEncodingSet = false;
}
@Override
public void resetBuffer() {
resetBuffer(false);
}
/**
* Reset the data buffer and the using Writer/Stream flags but not any status or header information.
*
* @param resetWriterStreamFlags <code>true</code> if the internal <code>usingWriter</code>,
* <code>usingOutputStream</code>, <code>isCharacterEncodingSet</code> flags
* should also be reset
*
* @exception IllegalStateException if the response has already been committed
*/
public void resetBuffer(boolean resetWriterStreamFlags) {
if (isCommitted()) {
throw new IllegalStateException(sm.getString("coyoteResponse.resetBuffer.ise"));
}
outputBuffer.reset(resetWriterStreamFlags);
if (resetWriterStreamFlags) {
usingOutputStream = false;
usingWriter = false;
isCharacterEncodingSet = false;
}
}
@Override
public void setBufferSize(int size) {
if (isCommitted() || !outputBuffer.isNew()) {
throw new IllegalStateException(sm.getString("coyoteResponse.setBufferSize.ise"));
}
outputBuffer.setBufferSize(size);
}
@Override
public void setContentLength(int length) {
setContentLengthLong(length);
}
@Override
public void setContentLengthLong(long length) {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
getCoyoteResponse().setContentLength(length);
}
@Override
public void setContentType(String type) {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
if (type == null) {
getCoyoteResponse().setContentType(null);
try {
getCoyoteResponse().setCharacterEncoding(null);
} catch (UnsupportedEncodingException e) {
// Can never happen when calling with null
}
isCharacterEncodingSet = false;
return;
}
String[] m = MEDIA_TYPE_CACHE.parse(type);
if (m == null) {
// Invalid - Assume no charset and just pass through whatever
// the user provided.
getCoyoteResponse().setContentTypeNoCharset(type);
return;
}
if (m[1] == null) {
// No charset and we know value is valid as cache lookup was
// successful
// Pass-through user provided value in case user-agent is buggy and
// requires specific format
getCoyoteResponse().setContentTypeNoCharset(type);
} else {
// There is a charset so have to rebuild content-type without it
getCoyoteResponse().setContentTypeNoCharset(m[0]);
// Ignore charset if getWriter() has already been called
if (!usingWriter) {
try {
getCoyoteResponse().setCharacterEncoding(m[1]);
} catch (UnsupportedEncodingException e) {
log.warn(sm.getString("coyoteResponse.encoding.invalid", m[1]), e);
}
isCharacterEncodingSet = true;
}
}
}
@Override
public void setCharacterEncoding(String encoding) {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
// Ignore any call made after the getWriter has been invoked
// The default should be used
if (usingWriter) {
return;
}
try {
getCoyoteResponse().setCharacterEncoding(encoding);
} catch (UnsupportedEncodingException e) {
log.warn(sm.getString("coyoteResponse.encoding.invalid", encoding), e);
return;
}
isCharacterEncodingSet = encoding != null;
}
@Override
public void setLocale(Locale locale) {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
getCoyoteResponse().setLocale(locale);
// Ignore any call made after the getWriter has been invoked.
// The default should be used
if (usingWriter) {
return;
}
if (isCharacterEncodingSet) {
return;
}
if (locale == null) {
try {
getCoyoteResponse().setCharacterEncoding(null);
} catch (UnsupportedEncodingException e) {
// Impossible when calling with null
}
} else {
// In some error handling scenarios, the context is unknown
// (e.g. a 404 when a ROOT context is not present)
Context context = getContext();
if (context != null) {
String charset = context.getCharset(locale);
if (charset != null) {
try {
getCoyoteResponse().setCharacterEncoding(charset);
} catch (UnsupportedEncodingException e) {
log.warn(sm.getString("coyoteResponse.encoding.invalid", charset), e);
}
}
}
}
}
// --------------------------------------------------- HttpResponse Methods
@Override
public String getHeader(String name) {
return getCoyoteResponse().getMimeHeaders().getHeader(name);
}
@Override
public Collection<String> getHeaderNames() {
MimeHeaders headers = getCoyoteResponse().getMimeHeaders();
int n = headers.size();
List<String> result = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
result.add(headers.getName(i).toString());
}
return result;
}
@Override
public Collection<String> getHeaders(String name) {
Enumeration<String> enumeration = getCoyoteResponse().getMimeHeaders().values(name);
Set<String> result = new LinkedHashSet<>();
while (enumeration.hasMoreElements()) {
result.add(enumeration.nextElement());
}
return result;
}
/**
* @return the error message that was set with <code>sendError()</code> for this Response.
*/
public String getMessage() {
return getCoyoteResponse().getMessage();
}
@Override
public int getStatus() {
return getCoyoteResponse().getStatus();
}
// -------------------------------------------- HttpServletResponse Methods
/**
* Add the specified Cookie to those that will be included with this Response.
*
* @param cookie Cookie to be added
*/
@Override
public void addCookie(final Cookie cookie) {
// Ignore any call from an included servlet
if (included || isCommitted()) {
return;
}
cookies.add(cookie);
String header = generateCookieString(cookie);
// if we reached here, no exception, cookie is valid
addHeader("Set-Cookie", header, getContext().getCookieProcessor().getCharset());
}
/**
* Special method for adding a session cookie as we should be overriding any previous.
*
* @param cookie The new session cookie to add the response
*/
public void addSessionCookieInternal(final Cookie cookie) {
if (isCommitted()) {
return;
}
String name = cookie.getName();
final String headername = "Set-Cookie";
final String startsWith = name + "=";
String header = generateCookieString(cookie);
boolean set = false;
MimeHeaders headers = getCoyoteResponse().getMimeHeaders();
int n = headers.size();
for (int i = 0; i < n; i++) {
if (headers.getName(i).toString().equals(headername)) {
if (headers.getValue(i).toString().startsWith(startsWith)) {
headers.getValue(i).setString(header);
set = true;
}
}
}
if (!set) {
addHeader(headername, header);
}
}
public String generateCookieString(final Cookie cookie) {
// Web application code can receive a IllegalArgumentException
// from the generateHeader() invocation
if (SecurityUtil.isPackageProtectionEnabled()) {
return AccessController
.doPrivileged(new PrivilegedGenerateCookieString(getContext(), cookie, request.getRequest()));
} else {
return getContext().getCookieProcessor().generateHeader(cookie, request.getRequest());
}
}
@Override
public void addDateHeader(String name, long value) {
if (name == null || name.isEmpty()) {
return;
}
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
addHeader(name, FastHttpDateFormat.formatDate(value));
}
@Override
public void addHeader(String name, String value) {
addHeader(name, value, null);
}
private void addHeader(String name, String value, Charset charset) {
if (name == null || name.isEmpty() || value == null) {
return;
}
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
char cc = name.charAt(0);
if (cc == 'C' || cc == 'c') {
if (checkSpecialHeader(name, value)) {
return;
}
}
getCoyoteResponse().addHeader(name, value, charset);
}
/**
* An extended version of this exists in {@link org.apache.coyote.Response}. This check is required here to ensure
* that the usingWriter check in {@link #setContentType(String)} is applied since usingWriter is not visible to
* {@link org.apache.coyote.Response} Called from set/addHeader.
*
* @return <code>true</code> if the header is special, no need to set the header.
*/
private boolean checkSpecialHeader(String name, String value) {
if (name.equalsIgnoreCase("Content-Type")) {
setContentType(value);
return true;
}
return false;
}
@Override
public void addIntHeader(String name, int value) {
if (name == null || name.isEmpty()) {
return;
}
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
addHeader(name, "" + value);
}
@Override
public boolean containsHeader(String name) {
// Need special handling for Content-Type and Content-Length due to
// special handling of these in coyoteResponse
char cc = name.charAt(0);
if (cc == 'C' || cc == 'c') {
if (name.equalsIgnoreCase("Content-Type")) {
// Will return null if this has not been set
return (getCoyoteResponse().getContentType() != null);
}
if (name.equalsIgnoreCase("Content-Length")) {
// -1 means not known and is not sent to client
return (getCoyoteResponse().getContentLengthLong() != -1);
}
}
return getCoyoteResponse().containsHeader(name);
}
@Override
public void setTrailerFields(Supplier<Map<String,String>> supplier) {
getCoyoteResponse().setTrailerFields(supplier);
}
@Override
public Supplier<Map<String,String>> getTrailerFields() {
return getCoyoteResponse().getTrailerFields();
}
@Override
public String encodeRedirectURL(String url) {
if (isEncodeable(toAbsolute(url))) {
return toEncoded(url, request.getSessionInternal().getIdInternal());
} else {
return url;
}
}
@Override
public String encodeURL(String url) {
String absolute;
try {
absolute = toAbsolute(url);
} catch (IllegalArgumentException iae) {
// Relative URL
return url;
}
if (isEncodeable(absolute)) {
// W3c spec clearly said
if (url.equalsIgnoreCase("")) {
url = absolute;
} else if (url.equals(absolute) && !hasPath(url)) {
url += '/';
}
return toEncoded(url, request.getSessionInternal().getIdInternal());
} else {
return url;
}
}
/**
* Send an acknowledgement of a request.
*
* @param continueResponseTiming Indicates when the request for the ACK originated so it can be compared with the
* configured timing for ACK responses.
*
* @exception IOException if an input/output error occurs
*/
public void sendAcknowledgement(ContinueResponseTiming continueResponseTiming) throws IOException {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
getCoyoteResponse().action(ActionCode.ACK, continueResponseTiming);
}
public void sendEarlyHints() {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
getCoyoteResponse().action(ActionCode.EARLY_HINTS, null);
}
/**
* {@inheritDoc}
* <p>
* Calling <code>sendError</code> with a status code of 103 differs from the usual behavior. Sending 103 will
* trigger the container to send a "103 Early Hints" informational response including all current headers. The
* application can continue to use the request and response after calling sendError with a 103 status code,
* including triggering a more typical response of any type.
* <p>
* Starting with Tomcat 12, applications should use {@link #sendEarlyHints}.
*/
@Override
public void sendError(int status) throws IOException {
sendError(status, null);
}
/**
* {@inheritDoc}
* <p>
* Calling <code>sendError</code> with a status code of 103 differs from the usual behavior. Sending 103 will
* trigger the container to send a "103 Early Hints" informational response including all current headers. The
* application can continue to use the request and response after calling sendError with a 103 status code,
* including triggering a more typical response of any type.
* <p>
* Starting with Tomcat 12, applications should use {@link #sendEarlyHints}.
*/
@Override
public void sendError(int status, String message) throws IOException {
if (isCommitted()) {
throw new IllegalStateException(sm.getString("coyoteResponse.sendError.ise"));
}
// Ignore any call from an included servlet
if (included) {
return;
}
if (SC_EARLY_HINTS == status) {
sendEarlyHints();
} else {
setError();
getCoyoteResponse().setStatus(status);
getCoyoteResponse().setMessage(message);
// Clear any data content that has been buffered
resetBuffer();
// Cause the response to be finished (from the application perspective)
setSuspended(true);
}
}
@Override
public void sendRedirect(String location) throws IOException {
sendRedirect(location, SC_FOUND);
}
/**
* Internal method that allows a redirect to be sent with a status other than {@link HttpServletResponse#SC_FOUND}
* (302). No attempt is made to validate the status code.
*
* @param location Location URL to redirect to
* @param status HTTP status code that will be sent
*
* @throws IOException an IO exception occurred
*/
public void sendRedirect(String location, int status) throws IOException {
if (isCommitted()) {
throw new IllegalStateException(sm.getString("coyoteResponse.sendRedirect.ise"));
}
// Ignore any call from an included servlet
if (included) {
return;
}
// Clear any data content that has been buffered
resetBuffer(true);
// Generate a temporary redirect to the specified location
try {
Context context = getContext();
// If no ROOT context is defined, the context can be null.
// In this case, the default Tomcat values are assumed, but without
// reference to org.apache.catalina.STRICT_SERVLET_COMPLIANCE.
String locationUri;
// Relative redirects require HTTP/1.1 or later
if (getRequest().getCoyoteRequest().getSupportsRelativeRedirects() &&
(context == null || context.getUseRelativeRedirects())) {
locationUri = location;
} else {
locationUri = toAbsolute(location);
}
setStatus(status);
setHeader("Location", locationUri);
if (context != null && context.getSendRedirectBody()) {
PrintWriter writer = getWriter();
writer.print(sm.getString("coyoteResponse.sendRedirect.note", Escape.htmlElementContent(locationUri)));
flushBuffer();
}
} catch (IllegalArgumentException e) {
log.warn(sm.getString("response.sendRedirectFail", location), e);
setStatus(SC_NOT_FOUND);
}
// Cause the response to be finished (from the application perspective)
setSuspended(true);
}
@Override
public void setDateHeader(String name, long value) {
if (name == null || name.isEmpty()) {
return;
}
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
setHeader(name, FastHttpDateFormat.formatDate(value));
}
@Override
public void setHeader(String name, String value) {
if (name == null || name.isEmpty() || value == null) {
return;
}
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
char cc = name.charAt(0);
if (cc == 'C' || cc == 'c') {
if (checkSpecialHeader(name, value)) {
return;
}
}
getCoyoteResponse().setHeader(name, value);
}
@Override
public void setIntHeader(String name, int value) {
if (name == null || name.isEmpty()) {
return;
}
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
setHeader(name, "" + value);
}
@Override
public void setStatus(int status) {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
getCoyoteResponse().setStatus(status);
}
// ------------------------------------------------------ Protected Methods
/**
* Return <code>true</code> if the specified URL should be encoded with a session identifier. This will be true if
* all of the following conditions are met:
* <ul>
* <li>The request we are responding to asked for a valid session
* <li>The requested session ID was not received via a cookie
* <li>The specified URL points back to somewhere within the web application that is responding to this request
* </ul>
*
* @param location Absolute URL to be validated
*
* @return <code>true</code> if the URL should be encoded
*/
protected boolean isEncodeable(final String location) {
if (location == null) {
return false;
}
// Is this an intra-document reference?
if (location.startsWith("#")) {
return false;
}
// Are we in a valid session that is not using cookies?
final Request hreq = request;
final Session session = hreq.getSessionInternal(false);
if (session == null) {
return false;
}
if (hreq.isRequestedSessionIdFromCookie()) {
return false;
}
// Is URL encoding permitted
if (!hreq.getServletContext().getEffectiveSessionTrackingModes().contains(SessionTrackingMode.URL)) {
return false;
}
if (SecurityUtil.isPackageProtectionEnabled()) {
Boolean result =
AccessController.doPrivileged(new PrivilegedDoIsEncodable(getContext(), hreq, session, location));
return result.booleanValue();
} else {
return doIsEncodeable(getContext(), hreq, session, location);
}
}
private static boolean doIsEncodeable(Context context, Request hreq, Session session, String location) {
// Is this a valid absolute URL?
URL url;
try {
URI uri = new URI(location);
url = uri.toURL();
} catch (MalformedURLException | URISyntaxException | IllegalArgumentException e) {
return false;
}
// Does this URL match down to (and including) the context path?
if (!hreq.getScheme().equalsIgnoreCase(url.getProtocol())) {
return false;
}
if (!hreq.getServerName().equalsIgnoreCase(url.getHost())) {
return false;
}
int serverPort = hreq.getServerPort();
if (serverPort == -1) {
if ("https".equals(hreq.getScheme())) {
serverPort = 443;
} else {
serverPort = 80;
}
}
int urlPort = url.getPort();
if (urlPort == -1) {
if ("https".equals(url.getProtocol())) {
urlPort = 443;
} else {
urlPort = 80;
}
}
if (serverPort != urlPort) {
return false;
}
String contextPath = context.getPath();
if (contextPath != null) {
String file = url.getFile();
if (!file.startsWith(contextPath)) {
return false;
}
String tok = ";" + SessionConfig.getSessionUriParamName(context) + "=" + session.getIdInternal();
return file.indexOf(tok, contextPath.length()) < 0;
}
// This URL belongs to our web application, so it is encodeable
return true;
}
/**
* Convert (if necessary) and return the absolute URL that represents the resource referenced by this possibly
* relative URL. If this URL is already absolute, return it unchanged.
*
* @param location URL to be (possibly) converted and then returned
*
* @return the encoded URL
*
* @exception IllegalArgumentException if a MalformedURLException is thrown when converting the relative URL to an
* absolute one
*/
protected String toAbsolute(String location) {
if (location == null) {
return null;
}
boolean leadingSlash = location.startsWith("/");
if (location.startsWith("//")) {
// Scheme relative
redirectURLCC.recycle();
// Add the scheme
String scheme = request.getScheme();
try {
redirectURLCC.append(scheme, 0, scheme.length());
redirectURLCC.append(':');
redirectURLCC.append(location, 0, location.length());
return redirectURLCC.toString();
} catch (IOException ioe) {
throw new IllegalArgumentException(location, ioe);
}
} else if (leadingSlash || !UriUtil.hasScheme(location)) {
redirectURLCC.recycle();
String scheme = request.getScheme();
String name = request.getServerName();
int port = request.getServerPort();
try {
redirectURLCC.append(scheme, 0, scheme.length());
redirectURLCC.append("://", 0, 3);
redirectURLCC.append(name, 0, name.length());
if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) {
redirectURLCC.append(':');
String portS = port + "";
redirectURLCC.append(portS, 0, portS.length());
}
if (!leadingSlash) {
String relativePath = request.getDecodedRequestURI();
int pos = relativePath.lastIndexOf('/');
CharChunk encodedURI = null;
if (SecurityUtil.isPackageProtectionEnabled()) {
try {
encodedURI = AccessController
.doPrivileged(new PrivilegedEncodeUrl(urlEncoder, relativePath, pos));
} catch (PrivilegedActionException pae) {
throw new IllegalArgumentException(location, pae.getException());
}
} else {
encodedURI = urlEncoder.encodeURL(relativePath, 0, pos);
}
redirectURLCC.append(encodedURI);
encodedURI.recycle();
redirectURLCC.append('/');
}
redirectURLCC.append(location, 0, location.length());
normalize(redirectURLCC);
} catch (IOException ioe) {
throw new IllegalArgumentException(location, ioe);
}
return redirectURLCC.toString();
} else {
return location;
}
}
/**
* Removes /./ and /../ sequences from absolute URLs. Code borrowed heavily from CoyoteAdapter.normalize()
*
* @param cc the char chunk containing the chars to normalize
*/
private void normalize(CharChunk cc) {
// Strip query string and/or fragment first as doing it this way makes
// the normalization logic a lot simpler
int truncate = cc.indexOf('?');
if (truncate == -1) {
truncate = cc.indexOf('#');
}
char[] truncateCC = null;
if (truncate > -1) {
truncateCC = Arrays.copyOfRange(cc.getBuffer(), cc.getStart() + truncate, cc.getEnd());
cc.setEnd(cc.getStart() + truncate);
}
if (cc.endsWith("/.") || cc.endsWith("/..")) {
try {
cc.append('/');
} catch (IOException ioe) {
throw new IllegalArgumentException(cc.toString(), ioe);
}
}
char[] c = cc.getChars();
int start = cc.getStart();
int end = cc.getEnd();
int startIndex = 0;
// Advance past the first three / characters (should place index just
// scheme://host[:port]
for (int i = 0; i < 3; i++) {
startIndex = cc.indexOf('/', startIndex + 1);
}
// Remove /./
int index = startIndex;
while (true) {
index = cc.indexOf("/./", 0, 3, index);
if (index < 0) {
break;
}
copyChars(c, start + index, start + index + 2, end - start - index - 2);
end = end - 2;
cc.setEnd(end);
}
// Remove /../
index = startIndex;
int pos;
while (true) {
index = cc.indexOf("/../", 0, 4, index);
if (index < 0) {
break;
}
// Can't go above the server root
if (index == startIndex) {
throw new IllegalArgumentException();
}
int index2 = -1;
for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos--) {
if (c[pos] == (byte) '/') {
index2 = pos;
}
}
copyChars(c, start + index2, start + index + 3, end - start - index - 3);
end = end + index2 - index - 3;
cc.setEnd(end);
index = index2;
}
// Add the query string and/or fragment (if present) back in
if (truncateCC != null) {
try {
cc.append(truncateCC, 0, truncateCC.length);
} catch (IOException ioe) {
throw new IllegalArgumentException(ioe);
}
}
}
private void copyChars(char[] c, int dest, int src, int len) {
System.arraycopy(c, src, c, dest, len);
}
/**
* Determine if an absolute URL has a path component.
*
* @param uri the URL that will be checked
*
* @return <code>true</code> if the URL has a path
*/
private boolean hasPath(String uri) {
int pos = uri.indexOf("://");
if (pos < 0) {
return false;
}
pos = uri.indexOf('/', pos + 3);
return pos >= 0;
}
/**
* Return the specified URL with the specified session identifier suitably encoded.
*
* @param url URL to be encoded with the session id
* @param sessionId Session id to be included in the encoded URL
*
* @return the encoded URL
*/
protected String toEncoded(String url, String sessionId) {
if (url == null || sessionId == null) {
return url;
}
String path = url;
String query = "";
String anchor = "";
int question = url.indexOf('?');
if (question >= 0) {
path = url.substring(0, question);
query = url.substring(question);
}
int pound = path.indexOf('#');
if (pound >= 0) {
anchor = path.substring(pound);
path = path.substring(0, pound);
}
StringBuilder sb = new StringBuilder(path);
if (sb.length() > 0) { // jsessionid can't be first.
sb.append(';');
sb.append(SessionConfig.getSessionUriParamName(request.getContext()));
sb.append('=');
sb.append(sessionId);
}
sb.append(anchor);
sb.append(query);
return sb.toString();
}
private static class PrivilegedGenerateCookieString implements PrivilegedAction<String> {
private final Context context;
private final Cookie cookie;
private final HttpServletRequest request;
PrivilegedGenerateCookieString(Context context, Cookie cookie, HttpServletRequest request) {
this.context = context;
this.cookie = cookie;
this.request = request;
}
@Override
public String run() {
return context.getCookieProcessor().generateHeader(cookie, request);
}
}
private static class PrivilegedDoIsEncodable implements PrivilegedAction<Boolean> {
private final Context context;
private final Request hreq;
private final Session session;
private final String location;
PrivilegedDoIsEncodable(Context context, Request hreq, Session session, String location) {
this.context = context;
this.hreq = hreq;
this.session = session;
this.location = location;
}
@Override
public Boolean run() {
return Boolean.valueOf(doIsEncodeable(context, hreq, session, location));
}
}
private static class PrivilegedEncodeUrl implements PrivilegedExceptionAction<CharChunk> {
private final UEncoder urlEncoder;
private final String relativePath;
private final int end;
PrivilegedEncodeUrl(UEncoder urlEncoder, String relativePath, int end) {
this.urlEncoder = urlEncoder;
this.relativePath = relativePath;
this.end = end;
}
@Override
public CharChunk run() throws IOException {
return urlEncoder.encodeURL(relativePath, 0, end);
}
}
}
|