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
|
/*
* 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.coyote.ajp;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import jakarta.servlet.ServletConnection;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.coyote.AbstractProcessor;
import org.apache.coyote.ActionCode;
import org.apache.coyote.Adapter;
import org.apache.coyote.ContinueResponseTiming;
import org.apache.coyote.ErrorState;
import org.apache.coyote.InputBuffer;
import org.apache.coyote.OutputBuffer;
import org.apache.coyote.RequestInfo;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
import org.apache.tomcat.util.net.ApplicationBufferHandler;
import org.apache.tomcat.util.net.SSLSupport;
import org.apache.tomcat.util.net.SocketWrapperBase;
import org.apache.tomcat.util.res.StringManager;
/**
* AJP Processor implementation.
*/
public class AjpProcessor extends AbstractProcessor {
private static final Log log = LogFactory.getLog(AjpProcessor.class);
/**
* The string manager for this package.
*/
private static final StringManager sm = StringManager.getManager(AjpProcessor.class);
/**
* End message array.
*/
private static final byte[] endMessageArray;
private static final byte[] endAndCloseMessageArray;
/**
* Flush message array.
*/
private static final byte[] flushMessageArray;
/**
* Pong message array.
*/
private static final byte[] pongMessageArray;
private static final Map<String,String> jakartaAttributeMapping;
private static final Set<String> iisTlsAttributes;
static {
// Allocate the end message array
AjpMessage endMessage = new AjpMessage(16);
endMessage.reset();
endMessage.appendByte(Constants.JK_AJP13_END_RESPONSE);
endMessage.appendByte(1);
endMessage.end();
endMessageArray = new byte[endMessage.getLen()];
System.arraycopy(endMessage.getBuffer(), 0, endMessageArray, 0, endMessage.getLen());
// Allocate the end and close message array
AjpMessage endAndCloseMessage = new AjpMessage(16);
endAndCloseMessage.reset();
endAndCloseMessage.appendByte(Constants.JK_AJP13_END_RESPONSE);
endAndCloseMessage.appendByte(0);
endAndCloseMessage.end();
endAndCloseMessageArray = new byte[endAndCloseMessage.getLen()];
System.arraycopy(endAndCloseMessage.getBuffer(), 0, endAndCloseMessageArray, 0, endAndCloseMessage.getLen());
// Allocate the flush message array
AjpMessage flushMessage = new AjpMessage(16);
flushMessage.reset();
flushMessage.appendByte(Constants.JK_AJP13_SEND_BODY_CHUNK);
flushMessage.appendInt(0);
flushMessage.appendByte(0);
flushMessage.end();
flushMessageArray = new byte[flushMessage.getLen()];
System.arraycopy(flushMessage.getBuffer(), 0, flushMessageArray, 0, flushMessage.getLen());
// Allocate the pong message array
AjpMessage pongMessage = new AjpMessage(16);
pongMessage.reset();
pongMessage.appendByte(Constants.JK_AJP13_CPONG_REPLY);
pongMessage.end();
pongMessageArray = new byte[pongMessage.getLen()];
System.arraycopy(pongMessage.getBuffer(), 0, pongMessageArray, 0, pongMessage.getLen());
// Build Map of Java Servlet to Jakarta Servlet attribute names
jakartaAttributeMapping =
Map.of("jakarta.servlet.request.secure_protocol", "jakarta.servlet.request.secure_protocol",
"jakarta.servlet.request.cipher_suite", "jakarta.servlet.request.cipher_suite",
"jakarta.servlet.request.key_size", "jakarta.servlet.request.key_size",
"jakarta.servlet.request.ssl_session", "jakarta.servlet.request.ssl_session",
"jakarta.servlet.request.X509Certificate", "jakarta.servlet.request.X509Certificate",
"javax.servlet.request.cipher_suite", "jakarta.servlet.request.cipher_suite",
"javax.servlet.request.key_size", "jakarta.servlet.request.key_size",
"javax.servlet.request.ssl_session", "jakarta.servlet.request.ssl_session",
"javax.servlet.request.X509Certificate", "jakarta.servlet.request.X509Certificate");
iisTlsAttributes = Set.of("CERT_ISSUER", "CERT_SUBJECT", "CERT_COOKIE", "HTTPS_SERVER_SUBJECT", "CERT_FLAGS",
"HTTPS_SECRETKEYSIZE", "CERT_SERIALNUMBER", "HTTPS_SERVER_ISSUER", "HTTPS_KEYSIZE");
}
// ----------------------------------------------------- Instance Variables
private final AbstractAjpProtocol<?> protocol;
/**
* GetBody message array. Not static like the other message arrays since the message varies with packetSize and that
* can vary per connector.
*/
private final byte[] getBodyMessageArray;
/**
* AJP packet size.
*/
private final int outputMaxChunkSize;
/**
* Header message. Note that this header is merely the one used during the processing of the first message of a
* "request", so it might not be a request header. It will stay unchanged during the processing of the whole
* request.
*/
private final AjpMessage requestHeaderMessage;
/**
* Message used for response composition.
*/
private final AjpMessage responseMessage;
/**
* Location of next write of the response message (used with non-blocking writes when the message may not be written
* in a single write). A value of -1 indicates that no message has been written to the buffer.
*/
private int responseMsgPos = -1;
/**
* Body message.
*/
private final AjpMessage bodyMessage;
/**
* Body message.
*/
private final MessageBytes bodyBytes = MessageBytes.newInstance();
/**
* Temp message bytes used for processing.
*/
private final MessageBytes tmpMB = MessageBytes.newInstance();
/**
* Byte chunk for certs.
*/
private final MessageBytes certificates = MessageBytes.newInstance();
/**
* End of stream flag.
*/
private boolean endOfStream = false;
/**
* Request body empty flag.
*/
private boolean empty = true;
/**
* First read.
*/
private boolean first = true;
/**
* Indicates that a 'get body chunk' message has been sent but the body chunk has not yet been received.
*/
private boolean waitingForBodyMessage = false;
/**
* Replay read.
*/
private boolean replay = false;
/**
* Should any response body be swallowed and not sent to the client.
*/
private boolean swallowResponse = false;
/**
* Finished response.
*/
private boolean responseFinished = false;
/**
* Bytes written to client for the current request.
*/
private long bytesWritten = 0;
// ------------------------------------------------------------ Constructor
public AjpProcessor(AbstractAjpProtocol<?> protocol, Adapter adapter) {
super(adapter);
this.protocol = protocol;
int packetSize = protocol.getPacketSize();
// Calculate maximum chunk size as packetSize may have been changed from
// the default (Constants.MAX_PACKET_SIZE)
this.outputMaxChunkSize = packetSize - Constants.SEND_HEAD_LEN;
request.setInputBuffer(new SocketInputBuffer());
requestHeaderMessage = new AjpMessage(packetSize);
responseMessage = new AjpMessage(packetSize);
bodyMessage = new AjpMessage(packetSize);
// Set the getBody message buffer
AjpMessage getBodyMessage = new AjpMessage(16);
getBodyMessage.reset();
getBodyMessage.appendByte(Constants.JK_AJP13_GET_BODY_CHUNK);
// Adjust read size if packetSize != default (Constants.MAX_PACKET_SIZE)
getBodyMessage.appendInt(Constants.MAX_READ_SIZE + packetSize - Constants.MAX_PACKET_SIZE);
getBodyMessage.end();
getBodyMessageArray = new byte[getBodyMessage.getLen()];
System.arraycopy(getBodyMessage.getBuffer(), 0, getBodyMessageArray, 0, getBodyMessage.getLen());
response.setOutputBuffer(new SocketOutputBuffer());
}
// --------------------------------------------------------- Public Methods
@Override
protected boolean flushBufferedWrite() throws IOException {
if (hasDataToWrite()) {
socketWrapper.flush(false);
if (hasDataToWrite()) {
// There is data to write but go via Response to
// maintain a consistent view of non-blocking state
response.checkRegisterForWrite();
return true;
}
}
return false;
}
@Override
protected void dispatchNonBlockingRead() {
if (available(true) > 0) {
super.dispatchNonBlockingRead();
}
}
@Override
protected SocketState dispatchEndRequest() {
// Set keep alive timeout for next request
socketWrapper.setReadTimeout(protocol.getKeepAliveTimeout());
recycle();
if (protocol.isPaused()) {
return SocketState.CLOSED;
} else {
return SocketState.OPEN;
}
}
@Override
public SocketState service(SocketWrapperBase<?> socket) throws IOException {
RequestInfo rp = request.getRequestProcessor();
rp.setStage(org.apache.coyote.Constants.STAGE_PARSE);
// Setting up the socket
this.socketWrapper = socket;
boolean cping = false;
// Expected to block on the first read as there should be at least one
// AJP message to read.
boolean firstRead = true;
while (!getErrorState().isError() && !protocol.isPaused()) {
// Parsing the request header
try {
// Get first message of the request
if (!readMessage(requestHeaderMessage, firstRead)) {
break;
}
firstRead = false;
// Processing the request so make sure the connection rather
// than keep-alive timeout is used
socketWrapper.setReadTimeout(protocol.getConnectionTimeout());
// Check message type, process right away and break if
// not regular request processing
int type = requestHeaderMessage.getByte();
if (type == Constants.JK_AJP13_CPING_REQUEST) {
if (protocol.isPaused()) {
recycle();
break;
}
cping = true;
try {
socketWrapper.write(true, pongMessageArray, 0, pongMessageArray.length);
socketWrapper.flush(true);
} catch (IOException ioe) {
if (getLog().isDebugEnabled()) {
getLog().debug(sm.getString("ajpprocessor.pongFail"), ioe);
}
setErrorState(ErrorState.CLOSE_CONNECTION_NOW, ioe);
}
recycle();
continue;
} else if (type != Constants.JK_AJP13_FORWARD_REQUEST) {
// Unexpected packet type. Unread body packets should have
// been swallowed in finish().
if (getLog().isDebugEnabled()) {
getLog().debug(sm.getString("ajpprocessor.unexpectedMessage", Integer.toString(type)));
}
setErrorState(ErrorState.CLOSE_CONNECTION_NOW, null);
break;
}
request.setStartTimeNanos(System.nanoTime());
} catch (IOException ioe) {
setErrorState(ErrorState.CLOSE_CONNECTION_NOW, ioe);
break;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (getLog().isDebugEnabled()) {
getLog().debug(sm.getString("ajpprocessor.header.error"), t);
}
// 400 - Bad Request
response.setStatus(400);
setErrorState(ErrorState.CLOSE_CLEAN, t);
}
if (getErrorState().isIoAllowed()) {
// Setting up filters, and parse some request headers
rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE);
try {
prepareRequest();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (getLog().isDebugEnabled()) {
getLog().debug(sm.getString("ajpprocessor.request.prepare"), t);
}
// 500 - Internal Server Error
response.setStatus(500);
setErrorState(ErrorState.CLOSE_CLEAN, t);
}
}
if (getErrorState().isIoAllowed() && !cping && protocol.isPaused()) {
// 503 - Service unavailable
response.setStatus(503);
setErrorState(ErrorState.CLOSE_CLEAN, null);
}
cping = false;
// Process the request in the adapter
if (getErrorState().isIoAllowed()) {
try {
rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
getAdapter().service(request, response);
} catch (InterruptedIOException e) {
setErrorState(ErrorState.CLOSE_CONNECTION_NOW, e);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
getLog().error(sm.getString("ajpprocessor.request.process"), t);
// 500 - Internal Server Error
response.setStatus(500);
setErrorState(ErrorState.CLOSE_CLEAN, t);
getAdapter().log(request, response, 0);
}
}
if (isAsync() && !getErrorState().isError()) {
break;
}
// Finish the response if not done yet
if (!responseFinished && getErrorState().isIoAllowed()) {
try {
action(ActionCode.COMMIT, null);
finishResponse();
} catch (IOException ioe) {
setErrorState(ErrorState.CLOSE_CONNECTION_NOW, ioe);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
setErrorState(ErrorState.CLOSE_NOW, t);
}
}
// If there was an error, make sure the request is counted as
// and error, and update the statistics counter
if (getErrorState().isError()) {
response.setStatus(500);
}
request.updateCounters();
rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE);
// Set keep alive timeout for next request
socketWrapper.setReadTimeout(protocol.getKeepAliveTimeout());
recycle();
}
rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);
if (getErrorState().isError() || protocol.isPaused()) {
return SocketState.CLOSED;
} else {
if (isAsync()) {
return SocketState.LONG;
} else {
return SocketState.OPEN;
}
}
}
@Override
public void recycle() {
getAdapter().checkRecycled(request, response);
super.recycle();
request.recycle();
response.recycle();
first = true;
endOfStream = false;
waitingForBodyMessage = false;
empty = true;
replay = false;
responseFinished = false;
certificates.recycle();
swallowResponse = false;
bytesWritten = 0;
}
@Override
public void pause() {
// NOOP for AJP
}
// ------------------------------------------------------ Protected Methods
// Methods used by SocketInputBuffer
/**
* Read an AJP body message. Used to read both the 'special' packet in ajp13 and to receive the data after we send a
* GET_BODY packet.
*
* @param block If there is no data available to read when this method is called, should this call block until data
* becomes available?
*
* @return <code>true</code> if at least one body byte was read, otherwise <code>false</code>
*/
private boolean receive(boolean block) throws IOException {
bodyMessage.reset();
if (!readMessage(bodyMessage, block)) {
return false;
}
waitingForBodyMessage = false;
// No data received.
if (bodyMessage.getLen() == 0) {
// just the header
return false;
}
int blen = bodyMessage.peekInt();
if (blen == 0) {
return false;
}
bodyMessage.getBodyBytes(bodyBytes);
empty = false;
return true;
}
/**
* Read an AJP message.
*
* @param message The message to populate
* @param block If there is no data available to read when this method is called, should this call block until
* data becomes available?
*
* @return true if the message has been read, false if no data was read
*
* @throws IOException any other failure, including incomplete reads
*/
private boolean readMessage(AjpMessage message, boolean block) throws IOException {
byte[] buf = message.getBuffer();
if (!read(buf, 0, Constants.H_SIZE, block)) {
return false;
}
int messageLength = message.processHeader(true);
if (messageLength < 0) {
// Invalid AJP header signature
throw new IOException(sm.getString("ajpmessage.invalidLength", Integer.valueOf(messageLength)));
} else if (messageLength == 0) {
// Zero length message.
return true;
} else {
if (messageLength > message.getBuffer().length) {
// Message too long for the buffer
// Need to trigger a 400 response
String msg = sm.getString("ajpprocessor.header.tooLong", Integer.valueOf(messageLength),
Integer.valueOf(buf.length));
log.error(msg);
throw new IllegalArgumentException(msg);
}
read(buf, Constants.H_SIZE, messageLength, true);
return true;
}
}
/**
* Get more request body data from the web server and store it in the internal buffer.
*
* @param block <code>true</code> if this is blocking IO
*
* @return <code>true</code> if there is more data, <code>false</code> if not.
*
* @throws IOException An IO error occurred
*/
protected boolean refillReadBuffer(boolean block) throws IOException {
// When using replay (e.g. after FORM auth) all the data to read has
// been buffered so there is no opportunity to refill the buffer.
if (replay) {
endOfStream = true; // we've read everything there is
}
if (endOfStream) {
return false;
}
if (first) {
first = false;
long contentLength = request.getContentLengthLong();
// - When content length > 0, AJP sends the first body message
// automatically.
// - When content length == 0, AJP does not send a body message.
// - When content length is unknown, AJP does not send the first
// body message automatically.
if (contentLength > 0) {
waitingForBodyMessage = true;
} else if (contentLength == 0) {
endOfStream = true;
return false;
}
}
// Request more data immediately
if (!waitingForBodyMessage) {
socketWrapper.write(true, getBodyMessageArray, 0, getBodyMessageArray.length);
socketWrapper.flush(true);
waitingForBodyMessage = true;
}
boolean moreData = receive(block);
if (!moreData && !waitingForBodyMessage) {
endOfStream = true;
}
return moreData;
}
/**
* After reading the request headers, we have to setup the request filters.
*/
@SuppressWarnings("deprecation")
private void prepareRequest() {
// Translate the HTTP method code to a String.
byte methodCode = requestHeaderMessage.getByte();
if (methodCode != Constants.SC_M_JK_STORED) {
String methodName = Constants.getMethodForCode(methodCode - 1);
request.method().setString(methodName);
}
requestHeaderMessage.getBytes(request.protocol());
requestHeaderMessage.getBytes(request.requestURI());
requestHeaderMessage.getBytes(request.remoteAddr());
requestHeaderMessage.getBytes(request.remoteHost());
requestHeaderMessage.getBytes(request.localName());
request.setLocalPort(requestHeaderMessage.getInt());
if (socketWrapper != null) {
request.peerAddr().setString(socketWrapper.getRemoteAddr());
}
boolean isSSL = requestHeaderMessage.getByte() != 0;
if (isSSL) {
request.scheme().setString("https");
}
// Decode headers
MimeHeaders headers = request.getMimeHeaders();
// Set this every time in case limit has been changed via JMX
headers.setLimit(protocol.getMaxHeaderCount());
boolean contentLengthSet = false;
int hCount = requestHeaderMessage.getInt();
for (int i = 0; i < hCount; i++) {
String hName;
// Header names are encoded as either an integer code starting
// with 0xA0, or as a normal string (in which case the first
// two bytes are the length).
int isc = requestHeaderMessage.peekInt();
int hId = isc & 0xFF;
MessageBytes vMB;
isc &= 0xFF00;
if (0xA000 == isc) {
requestHeaderMessage.getInt(); // To advance the read position
hName = Constants.getHeaderForCode(hId - 1);
vMB = headers.addValue(hName);
} else {
// reset hId -- if the header currently being read
// happens to be 7 or 8 bytes long, the code below
// will think it's the content-type header or the
// content-length header - SC_REQ_CONTENT_TYPE=7,
// SC_REQ_CONTENT_LENGTH=8 - leading to unexpected
// behaviour. see bug 5861 for more information.
hId = -1;
requestHeaderMessage.getBytes(tmpMB);
ByteChunk bc = tmpMB.getByteChunk();
vMB = headers.addValue(bc.getBuffer(), bc.getStart(), bc.getLength());
}
requestHeaderMessage.getBytes(vMB);
if (hId == Constants.SC_REQ_CONTENT_LENGTH || (hId == -1 && tmpMB.equalsIgnoreCase("Content-Length"))) {
long cl = vMB.getLong();
if (contentLengthSet) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
setErrorState(ErrorState.CLOSE_CLEAN, null);
} else {
contentLengthSet = true;
// Set the content-length header for the request
request.setContentLength(cl);
}
} else if (hId == Constants.SC_REQ_CONTENT_TYPE || (hId == -1 && tmpMB.equalsIgnoreCase("Content-Type"))) {
// just read the content-type header, so set it
ByteChunk bchunk = vMB.getByteChunk();
request.contentType().setBytes(bchunk.getBytes(), bchunk.getStart(), bchunk.getLength());
}
}
// Decode extra attributes
String secret = protocol.getSecret();
boolean secretPresentInRequest = false;
byte attributeCode;
while ((attributeCode = requestHeaderMessage.getByte()) != Constants.SC_A_ARE_DONE) {
switch (attributeCode) {
case Constants.SC_A_REQ_ATTRIBUTE -> {
requestHeaderMessage.getBytes(tmpMB);
String n = tmpMB.toString();
requestHeaderMessage.getBytes(tmpMB);
String v = tmpMB.toString();
/*
* AJP13 misses to forward the local IP address and the remote port. Allow the AJP connector to add
* this info via private request attributes. We will accept the forwarded data and remove it from
* the public list of request attributes.
*/
if (n.equals(Constants.SC_A_REQ_LOCAL_ADDR)) {
request.localAddr().setString(v);
} else if (n.equals(Constants.SC_A_REQ_REMOTE_PORT)) {
try {
request.setRemotePort(Integer.parseInt(v));
} catch (NumberFormatException nfe) {
// Ignore invalid value
}
} else if (n.equals(Constants.SC_A_SSL_PROTOCOL)) {
request.setAttribute(SSLSupport.SECURE_PROTOCOL_KEY, v);
request.setAttribute(SSLSupport.PROTOCOL_VERSION_KEY, v);
} else if (n.equals("JK_LB_ACTIVATION")) {
request.setAttribute(n, v);
} else if (jakartaAttributeMapping.containsKey(n)) {
// AJP uses the Java Servlet attribute names.
// Need to convert these to Jakarta Servlet.
request.setAttribute(jakartaAttributeMapping.get(n), v);
} else if (iisTlsAttributes.contains(n)) {
// Allow IIS TLS attributes
request.setAttribute(n, v);
} else {
// All 'known' attributes will be processed by the previous
// blocks. Any remaining attribute is an 'arbitrary' one.
Pattern pattern = protocol.getAllowedRequestAttributesPatternInternal();
if (pattern != null && pattern.matcher(n).matches()) {
request.setAttribute(n, v);
} else {
log.warn(sm.getString("ajpprocessor.unknownAttribute", n));
response.setStatus(403);
setErrorState(ErrorState.CLOSE_CLEAN, null);
}
}
}
case Constants.SC_A_CONTEXT -> requestHeaderMessage.getBytes(tmpMB);
// nothing
case Constants.SC_A_SERVLET_PATH -> requestHeaderMessage.getBytes(tmpMB);
// nothing
case Constants.SC_A_REMOTE_USER -> {
boolean tomcatAuthorization = protocol.getTomcatAuthorization();
if (tomcatAuthorization || !protocol.getTomcatAuthentication()) {
// Implies tomcatAuthentication == false
requestHeaderMessage.getBytes(request.getRemoteUser());
request.setRemoteUserNeedsAuthorization(tomcatAuthorization);
} else {
// Ignore user information from reverse proxy
requestHeaderMessage.getBytes(tmpMB);
}
}
case Constants.SC_A_AUTH_TYPE -> {
if (protocol.getTomcatAuthorization() || !protocol.getTomcatAuthentication()) {
// Implies tomcatAuthentication == false
requestHeaderMessage.getBytes(request.getAuthType());
} else {
// Ignore user information from reverse proxy
requestHeaderMessage.getBytes(tmpMB);
}
}
case Constants.SC_A_QUERY_STRING -> requestHeaderMessage.getBytes(request.queryString());
case Constants.SC_A_JVM_ROUTE -> requestHeaderMessage.getBytes(tmpMB);
// nothing
case Constants.SC_A_SSL_CERT ->
// SSL certificate extraction is lazy, moved to JkCoyoteHandler
requestHeaderMessage.getBytes(certificates);
case Constants.SC_A_SSL_CIPHER -> {
requestHeaderMessage.getBytes(tmpMB);
request.setAttribute(SSLSupport.CIPHER_SUITE_KEY, tmpMB.toString());
}
case Constants.SC_A_SSL_SESSION -> {
requestHeaderMessage.getBytes(tmpMB);
request.setAttribute(SSLSupport.SESSION_ID_KEY, tmpMB.toString());
}
case Constants.SC_A_SSL_KEY_SIZE ->
request.setAttribute(SSLSupport.KEY_SIZE_KEY, Integer.valueOf(requestHeaderMessage.getInt()));
case Constants.SC_A_STORED_METHOD -> requestHeaderMessage.getBytes(request.method());
case Constants.SC_A_SECRET -> {
requestHeaderMessage.getBytes(tmpMB);
if (secret != null && !secret.isEmpty()) {
secretPresentInRequest = true;
if (!tmpMB.equals(secret)) {
response.setStatus(403);
setErrorState(ErrorState.CLOSE_CLEAN, null);
}
}
}
default -> {
}
// Ignore unknown attribute for backward compatibility
}
}
// Check if secret was submitted if required
if (secret != null && !secret.isEmpty() && !secretPresentInRequest) {
response.setStatus(403);
setErrorState(ErrorState.CLOSE_CLEAN, null);
}
// Check for a full URI (including protocol://host:port/)
ByteChunk uriBC = request.requestURI().getByteChunk();
if (uriBC.startsWithIgnoreCase("http", 0)) {
int pos = uriBC.indexOf("://", 0, 3, 4);
int uriBCStart = uriBC.getStart();
if (pos != -1) {
byte[] uriB = uriBC.getBytes();
int slashPos = uriBC.indexOf('/', pos + 3);
if (slashPos == -1) {
slashPos = uriBC.getLength();
// Set URI as "/"
request.requestURI().setBytes(uriB, uriBCStart + pos + 1, 1);
} else {
request.requestURI().setBytes(uriB, uriBCStart + slashPos, uriBC.getLength() - slashPos);
}
MessageBytes hostMB = headers.setValue("host");
hostMB.setBytes(uriB, uriBCStart + pos + 3, slashPos - pos - 3);
}
}
MessageBytes valueMB = request.getMimeHeaders().getValue("host");
parseHost(valueMB);
if (!getErrorState().isIoAllowed()) {
getAdapter().log(request, response, 0);
}
}
/**
* {@inheritDoc}
* <p>
* This implementation populates the server name from the local name provided by the AJP message.
*/
@Override
protected void populateHost() {
try {
request.serverName().duplicate(request.localName());
} catch (IOException ioe) {
response.setStatus(400);
setErrorState(ErrorState.CLOSE_CLEAN, ioe);
}
}
/**
* {@inheritDoc}
* <p>
* This implementation populates the server port from the local port provided by the AJP message.
*/
@Override
protected void populatePort() {
// No host information (HTTP/1.0)
request.setServerPort(request.getLocalPort());
}
/**
* When committing the response, we have to validate the set of headers, as well as setup the response filters.
*/
@Override
protected final void prepareResponse() throws IOException {
response.setCommitted(true);
// Responses with certain status codes and/or methods are not permitted to include a response body.
int statusCode = response.getStatus();
if (statusCode < 200 || statusCode == 204 || statusCode == 205 || statusCode == 304 ||
request.method().equals("HEAD")) {
// No entity body
swallowResponse = true;
}
// Prepare special headers
MimeHeaders headers = response.getMimeHeaders();
String contentType = response.getContentType();
if (contentType != null) {
headers.setValue("Content-Type").setString(contentType);
}
String contentLanguage = response.getContentLanguage();
if (contentLanguage != null) {
headers.setValue("Content-Language").setString(contentLanguage);
}
long contentLength = response.getContentLengthLong();
if (contentLength >= 0) {
headers.setValue("Content-Length").setLong(contentLength);
}
tmpMB.recycle();
responseMsgPos = -1;
int numHeaders = headers.size();
boolean needAjpMessageHeader = true;
while (needAjpMessageHeader) {
// Write AJP message header
responseMessage.reset();
responseMessage.appendByte(Constants.JK_AJP13_SEND_HEADERS);
// Write HTTP response line
responseMessage.appendInt(statusCode);
// Reason phrase is optional but mod_jk + httpd 2.x fails with a null
// reason phrase - bug 45026
tmpMB.setString(Integer.toString(response.getStatus()));
responseMessage.appendBytes(tmpMB);
// Start headers
responseMessage.appendInt(numHeaders);
needAjpMessageHeader = false;
for (int i = 0; i < numHeaders; i++) {
try {
// Write headers
MessageBytes hN = headers.getName(i);
int hC = Constants.getResponseAjpIndex(hN.toString());
if (hC > 0) {
responseMessage.appendInt(hC);
} else {
responseMessage.appendBytes(hN);
}
MessageBytes hV = headers.getValue(i);
responseMessage.appendBytes(hV);
} catch (IllegalArgumentException iae) {
// Log the problematic header
log.warn(sm.getString("ajpprocessor.response.invalidHeader", headers.getName(i),
headers.getValue(i)), iae);
// Remove the problematic header
headers.removeHeader(i);
numHeaders--;
// Restart writing of AJP message
needAjpMessageHeader = true;
break;
}
}
}
// Write to buffer
responseMessage.end();
socketWrapper.write(true, responseMessage.getBuffer(), 0, responseMessage.getLen());
socketWrapper.flush(true);
}
@Override
protected final void flush() throws IOException {
// Calling code should ensure that there is no data in the buffers for
// non-blocking writes.
// TODO Validate the assertion above
if (!responseFinished) {
if (protocol.getAjpFlush()) {
// Send the flush message
socketWrapper.write(true, flushMessageArray, 0, flushMessageArray.length);
}
socketWrapper.flush(true);
}
}
@Override
protected final void finishResponse() throws IOException {
if (responseFinished) {
return;
}
responseFinished = true;
// Swallow the unread body packet if present
if (waitingForBodyMessage || first && request.getContentLengthLong() > 0) {
refillReadBuffer(true);
}
// Add the end message
if (getErrorState().isError()) {
socketWrapper.write(true, endAndCloseMessageArray, 0, endAndCloseMessageArray.length);
} else {
socketWrapper.write(true, endMessageArray, 0, endMessageArray.length);
}
socketWrapper.flush(true);
}
@Override
protected final void ack(ContinueResponseTiming continueResponseTiming) {
// NO-OP for AJP
}
@Override
protected void earlyHints() throws IOException {
// NO-OP for AJP
}
@Override
protected final int available(boolean doRead) {
if (endOfStream) {
return 0;
}
if (empty && doRead) {
try {
refillReadBuffer(false);
} catch (IOException ioe) {
/*
* Probably a timeout. This approach isn't ideal but it works. Returning 1 will indicate that data is
* available which should trigger a read which in turn will trigger another IOException and that one can
* be thrown.
*/
return 1;
}
}
if (empty) {
return 0;
} else {
return request.getInputBuffer().available();
}
}
@Override
protected final void setRequestBody(ByteChunk body) {
int length = body.getLength();
bodyBytes.setBytes(body.getBytes(), body.getStart(), length);
request.setContentLength(length);
first = false;
empty = false;
replay = true;
endOfStream = false;
}
@Override
protected final void setSwallowResponse() {
swallowResponse = true;
}
@Override
protected final void disableSwallowRequest() {
/*
* NO-OP With AJP, Tomcat controls when the client sends request body data. At most there will be a single
* packet to read and that will be handled in finishResponse().
*/
}
@Override
protected final boolean getPopulateRequestAttributesFromSocket() {
// NO-OPs the attribute requests since they are pre-populated when
// parsing the first AJP message.
return false;
}
@Override
protected final void populateRequestAttributeRemoteHost() {
// Get remote host name using a DNS resolution
if (request.remoteHost().isNull()) {
try {
request.remoteHost().setString(InetAddress.getByName(request.remoteAddr().toString()).getHostName());
} catch (IOException iex) {
// Ignore
}
}
}
@Override
protected final void populateSslRequestAttributes() {
if (!certificates.isNull()) {
List<X509Certificate> jsseCerts = new ArrayList<>();
ByteChunk certData = certificates.getByteChunk();
ByteArrayInputStream bais =
new ByteArrayInputStream(certData.getBytes(), certData.getStart(), certData.getLength());
// Fill the elements.
try {
CertificateFactory cf;
String clientCertProvider = protocol.getClientCertProvider();
if (clientCertProvider == null) {
cf = CertificateFactory.getInstance("X.509");
} else {
cf = CertificateFactory.getInstance("X.509", clientCertProvider);
}
while (bais.available() > 0) {
X509Certificate cert = (X509Certificate) cf.generateCertificate(bais);
jsseCerts.add(cert);
}
} catch (CertificateException | NoSuchProviderException e) {
getLog().error(sm.getString("ajpprocessor.certs.fail"), e);
return;
}
request.setAttribute(SSLSupport.CERTIFICATE_KEY, jsseCerts.toArray(new X509Certificate[0]));
}
}
@Override
protected final boolean isRequestBodyFullyRead() {
return endOfStream;
}
@Override
protected final void registerReadInterest() {
socketWrapper.registerReadInterest();
}
@Override
protected final boolean isReadyForWrite() {
return responseMsgPos == -1 && socketWrapper.isReadyForWrite();
}
@Override
protected boolean isTrailerFieldsReady() {
// AJP does not support trailers so return true so app can request the
// trailers and find out that there are none.
return true;
}
/**
* Read at least the specified amount of bytes, and place them in the input buffer. Note that if any data is
* available to read then this method will always block until at least the specified number of bytes have been read.
*
* @param buf Buffer to read data into
* @param pos Start position
* @param n The minimum number of bytes to read
* @param block If there is no data available to read when this method is called, should this call block until data
* becomes available?
*
* @return <code>true</code> if the requested number of bytes were read else <code>false</code>
*
* @throws IOException If an I/O error occurs during the read
*/
private boolean read(byte[] buf, int pos, int n, boolean block) throws IOException {
int read = socketWrapper.read(block, buf, pos, n);
if (read > 0 && read < n) {
int left = n - read;
int start = pos + read;
while (left > 0) {
read = socketWrapper.read(true, buf, start, left);
if (read == -1) {
throw new EOFException();
}
left = left - read;
start = start + read;
}
} else if (read == -1) {
throw new EOFException();
}
return read > 0;
}
private void writeData(ByteBuffer chunk) throws IOException {
boolean blocking = (response.getWriteListener() == null);
int len = chunk.remaining();
int off = 0;
// Write this chunk
while (len > 0) {
int thisTime = Math.min(len, outputMaxChunkSize);
responseMessage.reset();
responseMessage.appendByte(Constants.JK_AJP13_SEND_BODY_CHUNK);
chunk.limit(chunk.position() + thisTime);
responseMessage.appendBytes(chunk);
responseMessage.end();
socketWrapper.write(blocking, responseMessage.getBuffer(), 0, responseMessage.getLen());
socketWrapper.flush(blocking);
len -= thisTime;
off += thisTime;
}
bytesWritten += off;
}
private boolean hasDataToWrite() {
return responseMsgPos != -1 || socketWrapper.hasDataToWrite();
}
@Override
protected Log getLog() {
return log;
}
@Override
protected ServletConnection getServletConnection() {
return socketWrapper.getServletConnection("ajp", "");
}
// ------------------------------------- InputStreamInputBuffer Inner Class
/**
* This class is an input buffer which will read its data from an input stream.
*/
protected class SocketInputBuffer implements InputBuffer {
@Override
public int doRead(ApplicationBufferHandler handler) throws IOException {
if (endOfStream) {
return -1;
}
if (empty) {
if (!refillReadBuffer(true)) {
return -1;
}
}
ByteChunk bc = bodyBytes.getByteChunk();
handler.setByteBuffer(ByteBuffer.wrap(bc.getBuffer(), bc.getStart(), bc.getLength()));
empty = true;
return handler.getByteBuffer().remaining();
}
@Override
public int available() {
if (empty) {
return 0;
} else {
return bodyBytes.getByteChunk().getLength();
}
}
}
// ----------------------------------- OutputStreamOutputBuffer Inner Class
/**
* This class is an output buffer which will write data to an output stream.
*/
protected class SocketOutputBuffer implements OutputBuffer {
@Override
public int doWrite(ByteBuffer chunk) throws IOException {
if (!response.isCommitted()) {
// Validate and write response headers
try {
prepareResponse();
} catch (IOException ioe) {
setErrorState(ErrorState.CLOSE_CONNECTION_NOW, ioe);
}
}
int len = 0;
if (!swallowResponse) {
try {
len = chunk.remaining();
writeData(chunk);
len -= chunk.remaining();
} catch (IOException ioe) {
setErrorState(ErrorState.CLOSE_CONNECTION_NOW, ioe);
// Re-throw
throw ioe;
}
}
return len;
}
@Override
public long getBytesWritten() {
return bytesWritten;
}
}
}
|