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
|
/*
* 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.tomcat.util.buf;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/*
* In a server it is very important to be able to operate on
* the original byte[] without converting everything to chars.
* Some protocols are ASCII only, and some allow different
* non-UNICODE encodings. The encoding is not known beforehand,
* and can even change during the execution of the protocol.
* ( for example a multipart message may have parts with different
* encoding )
*
* For HTTP it is not very clear how the encoding of RequestURI
* and mime values can be determined, but it is a great advantage
* to be able to parse the request without converting to string.
*/
// TODO: This class could either extend ByteBuffer, or better a ByteBuffer
// inside this way it could provide the search/etc on ByteBuffer, as a helper.
/**
* This class is used to represent a chunk of bytes, and utilities to manipulate
* byte[].
*
* The buffer can be modified and used for both input and output.
*
* There are 2 modes: The chunk can be associated with a sink - ByteInputChannel
* or ByteOutputChannel, which will be used when the buffer is empty (on input)
* or filled (on output). For output, it can also grow. This operating mode is
* selected by calling setLimit() or allocate(initial, limit) with limit != -1.
*
* Various search and append method are defined - similar with String and
* StringBuffer, but operating on bytes.
*
* This is important because it allows processing the http headers directly on
* the received bytes, without converting to chars and Strings until the strings
* are needed. In addition, the charset is determined later, from headers or
* user code.
*
* @author dac@sun.com
* @author James Todd [gonzo@sun.com]
* @author Costin Manolache
* @author Remy Maucherat
*/
public final class ByteChunk extends AbstractChunk {
private static final long serialVersionUID = 1L;
/**
* Input interface, used when the buffer is empty.
*
* Same as java.nio.channels.ReadableByteChannel
*/
public static interface ByteInputChannel {
/**
* Read new bytes.
*
* @return The number of bytes read
*
* @throws IOException If an I/O error occurs during reading
*/
public int realReadBytes() throws IOException;
}
/**
* When we need more space we'll either grow the buffer ( up to the limit )
* or send it to a channel.
*
* Same as java.nio.channel.WritableByteChannel.
*/
public static interface ByteOutputChannel {
/**
* Send the bytes ( usually the internal conversion buffer ). Expect 8k
* output if the buffer is full.
*
* @param buf bytes that will be written
* @param off offset in the bytes array
* @param len length that will be written
* @throws IOException If an I/O occurs while writing the bytes
*/
public void realWriteBytes(byte buf[], int off, int len) throws IOException;
/**
* Send the bytes ( usually the internal conversion buffer ). Expect 8k
* output if the buffer is full.
*
* @param from bytes that will be written
* @throws IOException If an I/O occurs while writing the bytes
*/
public void realWriteBytes(ByteBuffer from) throws IOException;
}
// --------------------
/**
* Default encoding used to convert to strings. It should be UTF8, as most
* standards seem to converge, but the servlet API requires 8859_1, and this
* object is used mostly for servlets.
*/
public static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1;
private transient Charset charset;
// byte[]
private byte[] buff;
// transient as serialization is primarily for values via, e.g. JMX
private transient ByteInputChannel in = null;
private transient ByteOutputChannel out = null;
/**
* Creates a new, uninitialized ByteChunk object.
*/
public ByteChunk() {
}
public ByteChunk(int initial) {
allocate(initial, -1);
}
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
oos.writeUTF(getCharset().name());
}
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
this.charset = Charset.forName(ois.readUTF());
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public void recycle() {
super.recycle();
charset = null;
}
// -------------------- Setup --------------------
public void allocate(int initial, int limit) {
if (buff == null || buff.length < initial) {
buff = new byte[initial];
}
setLimit(limit);
start = 0;
end = 0;
isSet = true;
hasHashCode = false;
}
/**
* Sets the buffer to the specified subarray of bytes.
*
* @param b the ascii bytes
* @param off the start offset of the bytes
* @param len the length of the bytes
*/
public void setBytes(byte[] b, int off, int len) {
buff = b;
start = off;
end = start + len;
isSet = true;
hasHashCode = false;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
public Charset getCharset() {
if (charset == null) {
charset = DEFAULT_CHARSET;
}
return charset;
}
/**
* @return the buffer.
*/
public byte[] getBytes() {
return getBuffer();
}
/**
* @return the buffer.
*/
public byte[] getBuffer() {
return buff;
}
/**
* When the buffer is empty, read the data from the input channel.
*
* @param in The input channel
*/
public void setByteInputChannel(ByteInputChannel in) {
this.in = in;
}
/**
* When the buffer is full, write the data to the output channel. Also used
* when large amount of data is appended. If not set, the buffer will grow
* to the limit.
*
* @param out The output channel
*/
public void setByteOutputChannel(ByteOutputChannel out) {
this.out = out;
}
// -------------------- Adding data to the buffer --------------------
public void append(byte b) throws IOException {
makeSpace(1);
int limit = getLimitInternal();
// couldn't make space
if (end >= limit) {
flushBuffer();
}
buff[end++] = b;
}
public void append(ByteChunk src) throws IOException {
append(src.getBytes(), src.getStart(), src.getLength());
}
/**
* Add data to the buffer.
*
* @param src Bytes array
* @param off Offset
* @param len Length
* @throws IOException Writing overflow data to the output channel failed
*/
public void append(byte src[], int off, int len) throws IOException {
// will grow, up to limit
makeSpace(len);
int limit = getLimitInternal();
// Optimize on a common case.
// If the buffer is empty and the source is going to fill up all the
// space in buffer, may as well write it directly to the output,
// and avoid an extra copy
if (len == limit && end == start && out != null) {
out.realWriteBytes(src, off, len);
return;
}
// if we are below the limit
if (len <= limit - end) {
System.arraycopy(src, off, buff, end, len);
end += len;
return;
}
// Need more space than we can afford, need to flush buffer.
// The buffer is already at (or bigger than) limit.
// We chunk the data into slices fitting in the buffer limit, although
// if the data is written directly if it doesn't fit.
int avail = limit - end;
System.arraycopy(src, off, buff, end, avail);
end += avail;
flushBuffer();
int remain = len - avail;
while (remain > (limit - end)) {
out.realWriteBytes(src, (off + len) - remain, limit - end);
remain = remain - (limit - end);
}
System.arraycopy(src, (off + len) - remain, buff, end, remain);
end += remain;
}
/**
* Add data to the buffer.
*
* @param from the ByteBuffer with the data
* @throws IOException Writing overflow data to the output channel failed
*/
public void append(ByteBuffer from) throws IOException {
int len = from.remaining();
// will grow, up to limit
makeSpace(len);
int limit = getLimitInternal();
// Optimize on a common case.
// If the buffer is empty and the source is going to fill up all the
// space in buffer, may as well write it directly to the output,
// and avoid an extra copy
if (len == limit && end == start && out != null) {
out.realWriteBytes(from);
from.position(from.limit());
return;
}
// if we have limit and we're below
if (len <= limit - end) {
// makeSpace will grow the buffer to the limit,
// so we have space
from.get(buff, end, len);
end += len;
return;
}
// need more space than we can afford, need to flush
// buffer
// the buffer is already at ( or bigger than ) limit
// We chunk the data into slices fitting in the buffer limit, although
// if the data is written directly if it doesn't fit
int avail = limit - end;
from.get(buff, end, avail);
end += avail;
flushBuffer();
int fromLimit = from.limit();
int remain = len - avail;
avail = limit - end;
while (remain >= avail) {
from.limit(from.position() + avail);
out.realWriteBytes(from);
from.position(from.limit());
remain = remain - avail;
}
from.limit(fromLimit);
from.get(buff, end, remain);
end += remain;
}
// -------------------- Removing data from the buffer --------------------
/*
* @deprecated Use {@link #subtract()}.
* This method will be removed in Tomcat 10
*/
@Deprecated
public int substract() throws IOException {
return subtract();
}
public int subtract() throws IOException {
if (checkEof()) {
return -1;
}
return buff[start++] & 0xFF;
}
/*
* @deprecated Use {@link #subtractB()}.
* This method will be removed in Tomcat 10
*/
@Deprecated
public byte substractB() throws IOException {
return subtractB();
}
public byte subtractB() throws IOException {
if (checkEof()) {
return -1;
}
return buff[start++];
}
/*
* @deprecated Use {@link #subtract(byte[],int,int)}.
* This method will be removed in Tomcat 10
*/
@Deprecated
public int substract(byte dest[], int off, int len) throws IOException {
return subtract(dest, off, len);
}
public int subtract(byte dest[], int off, int len) throws IOException {
if (checkEof()) {
return -1;
}
int n = len;
if (len > getLength()) {
n = getLength();
}
System.arraycopy(buff, start, dest, off, n);
start += n;
return n;
}
/**
* Transfers bytes from the buffer to the specified ByteBuffer. After the
* operation the position of the ByteBuffer will be returned to the one
* before the operation, the limit will be the position incremented by the
* number of the transferred bytes.
*
* @param to the ByteBuffer into which bytes are to be written.
* @return an integer specifying the actual number of bytes read, or -1 if
* the end of the stream is reached
* @throws IOException if an input or output exception has occurred
*
* @deprecated Use {@link #subtract(ByteBuffer)}.
* This method will be removed in Tomcat 10
*/
@Deprecated
public int substract(ByteBuffer to) throws IOException {
return subtract(to);
}
/**
* Transfers bytes from the buffer to the specified ByteBuffer. After the
* operation the position of the ByteBuffer will be returned to the one
* before the operation, the limit will be the position incremented by the
* number of the transfered bytes.
*
* @param to the ByteBuffer into which bytes are to be written.
* @return an integer specifying the actual number of bytes read, or -1 if
* the end of the stream is reached
* @throws IOException if an input or output exception has occurred
*/
public int subtract(ByteBuffer to) throws IOException {
if (checkEof()) {
return -1;
}
int n = Math.min(to.remaining(), getLength());
to.put(buff, start, n);
to.limit(to.position());
to.position(to.position() - n);
start += n;
return n;
}
private boolean checkEof() throws IOException {
if ((end - start) == 0) {
if (in == null) {
return true;
}
int n = in.realReadBytes();
if (n < 0) {
return true;
}
}
return false;
}
/**
* Send the buffer to the sink. Called by append() when the limit is
* reached. You can also call it explicitly to force the data to be written.
*
* @throws IOException Writing overflow data to the output channel failed
*/
public void flushBuffer() throws IOException {
// assert out!=null
if (out == null) {
throw new BufferOverflowException(sm.getString(
"chunk.overflow", Integer.valueOf(getLimit()), Integer.valueOf(buff.length)));
}
out.realWriteBytes(buff, start, end - start);
end = start;
}
/**
* Make space for len bytes. If len is small, allocate a reserve space too.
* Never grow bigger than the limit or {@link AbstractChunk#ARRAY_MAX_SIZE}.
*
* @param count The size
*/
public void makeSpace(int count) {
byte[] tmp = null;
int limit = getLimitInternal();
long newSize;
long desiredSize = end + count;
// Can't grow above the limit
if (desiredSize > limit) {
desiredSize = limit;
}
if (buff == null) {
if (desiredSize < 256) {
desiredSize = 256; // take a minimum
}
buff = new byte[(int) desiredSize];
}
// limit < buf.length (the buffer is already big)
// or we already have space XXX
if (desiredSize <= buff.length) {
return;
}
// grow in larger chunks
if (desiredSize < 2L * buff.length) {
newSize = buff.length * 2L;
} else {
newSize = buff.length * 2L + count;
}
if (newSize > limit) {
newSize = limit;
}
tmp = new byte[(int) newSize];
// Compacts buffer
System.arraycopy(buff, start, tmp, 0, end - start);
buff = tmp;
tmp = null;
end = end - start;
start = 0;
}
// -------------------- Conversion and getters --------------------
@Override
public String toString() {
if (isNull()) {
return null;
} else if (end - start == 0) {
return "";
}
return StringCache.toString(this);
}
public String toStringInternal() {
if (charset == null) {
charset = DEFAULT_CHARSET;
}
// new String(byte[], int, int, Charset) takes a defensive copy of the
// entire byte array. This is expensive if only a small subset of the
// bytes will be used. The code below is from Apache Harmony.
CharBuffer cb = charset.decode(ByteBuffer.wrap(buff, start, end - start));
return new String(cb.array(), cb.arrayOffset(), cb.length());
}
public long getLong() {
return Ascii.parseLong(buff, start, end - start);
}
// -------------------- equals --------------------
@Override
public boolean equals(Object obj) {
if (obj instanceof ByteChunk) {
return equals((ByteChunk) obj);
}
return false;
}
/**
* Compares the message bytes to the specified String object.
*
* @param s the String to compare
* @return <code>true</code> if the comparison succeeded, <code>false</code>
* otherwise
*/
public boolean equals(String s) {
// XXX ENCODING - this only works if encoding is UTF8-compat
// ( ok for tomcat, where we compare ascii - header names, etc )!!!
byte[] b = buff;
int len = end - start;
if (b == null || len != s.length()) {
return false;
}
int off = start;
for (int i = 0; i < len; i++) {
if (b[off++] != s.charAt(i)) {
return false;
}
}
return true;
}
/**
* Compares the message bytes to the specified String object.
*
* @param s the String to compare
* @return <code>true</code> if the comparison succeeded, <code>false</code>
* otherwise
*/
public boolean equalsIgnoreCase(String s) {
byte[] b = buff;
int len = end - start;
if (b == null || len != s.length()) {
return false;
}
int off = start;
for (int i = 0; i < len; i++) {
if (Ascii.toLower(b[off++]) != Ascii.toLower(s.charAt(i))) {
return false;
}
}
return true;
}
public boolean equals(ByteChunk bb) {
return equals(bb.getBytes(), bb.getStart(), bb.getLength());
}
public boolean equals(byte b2[], int off2, int len2) {
byte b1[] = buff;
if (b1 == null && b2 == null) {
return true;
}
int len = end - start;
if (len != len2 || b1 == null || b2 == null) {
return false;
}
int off1 = start;
while (len-- > 0) {
if (b1[off1++] != b2[off2++]) {
return false;
}
}
return true;
}
public boolean equals(CharChunk cc) {
return equals(cc.getChars(), cc.getStart(), cc.getLength());
}
public boolean equals(char c2[], int off2, int len2) {
// XXX works only for enc compatible with ASCII/UTF !!!
byte b1[] = buff;
if (c2 == null && b1 == null) {
return true;
}
if (b1 == null || c2 == null || end - start != len2) {
return false;
}
int off1 = start;
int len = end - start;
while (len-- > 0) {
if ((char) b1[off1++] != c2[off2++]) {
return false;
}
}
return true;
}
/**
* Returns true if the buffer starts with the specified string when tested
* in a case sensitive manner.
*
* @param s the string
* @param pos The position
*
* @return <code>true</code> if the start matches
*/
public boolean startsWith(String s, int pos) {
byte[] b = buff;
int len = s.length();
if (b == null || len + pos > end - start) {
return false;
}
int off = start + pos;
for (int i = 0; i < len; i++) {
if (b[off++] != s.charAt(i)) {
return false;
}
}
return true;
}
/**
* Returns true if the buffer starts with the specified string when tested
* in a case insensitive manner.
*
* @param s the string
* @param pos The position
*
* @return <code>true</code> if the start matches
*/
public boolean startsWithIgnoreCase(String s, int pos) {
byte[] b = buff;
int len = s.length();
if (b == null || len + pos > end - start) {
return false;
}
int off = start + pos;
for (int i = 0; i < len; i++) {
if (Ascii.toLower(b[off++]) != Ascii.toLower(s.charAt(i))) {
return false;
}
}
return true;
}
@Override
protected int getBufferElement(int index) {
return buff[index];
}
/**
* Returns the first instance of the given character in this ByteChunk
* starting at the specified byte. If the character is not found, -1 is
* returned. <br>
* NOTE: This only works for characters in the range 0-127.
*
* @param c The character
* @param starting The start position
* @return The position of the first instance of the character or -1 if the
* character is not found.
*/
public int indexOf(char c, int starting) {
int ret = indexOf(buff, start + starting, end, c);
return (ret >= start) ? ret - start : -1;
}
/**
* Returns the first instance of the given character in the given byte array
* between the specified start and end. <br>
* NOTE: This only works for characters in the range 0-127.
*
* @param bytes The array to search
* @param start The point to start searching from in the array
* @param end The point to stop searching in the array
* @param s The character to search for
* @return The position of the first instance of the character or -1 if the
* character is not found.
*/
public static int indexOf(byte bytes[], int start, int end, char s) {
int offset = start;
while (offset < end) {
byte b = bytes[offset];
if (b == s) {
return offset;
}
offset++;
}
return -1;
}
/**
* Returns the first instance of the given byte in the byte array between
* the specified start and end.
*
* @param bytes The byte array to search
* @param start The point to start searching from in the byte array
* @param end The point to stop searching in the byte array
* @param b The byte to search for
* @return The position of the first instance of the byte or -1 if the byte
* is not found.
*/
public static int findByte(byte bytes[], int start, int end, byte b) {
int offset = start;
while (offset < end) {
if (bytes[offset] == b) {
return offset;
}
offset++;
}
return -1;
}
/**
* Returns the first instance of any of the given bytes in the byte array
* between the specified start and end.
*
* @param bytes The byte array to search
* @param start The point to start searching from in the byte array
* @param end The point to stop searching in the byte array
* @param b The array of bytes to search for
* @return The position of the first instance of the byte or -1 if the byte
* is not found.
*/
public static int findBytes(byte bytes[], int start, int end, byte b[]) {
int offset = start;
while (offset < end) {
for (byte value : b) {
if (bytes[offset] == value) {
return offset;
}
}
offset++;
}
return -1;
}
/**
* Convert specified String to a byte array. This ONLY WORKS for ascii, UTF
* chars will be truncated.
*
* @param value to convert to byte array
* @return the byte array value
*/
public static final byte[] convertToBytes(String value) {
byte[] result = new byte[value.length()];
for (int i = 0; i < value.length(); i++) {
result[i] = (byte) value.charAt(i);
}
return result;
}
public static class BufferOverflowException extends IOException {
private static final long serialVersionUID = 1L;
public BufferOverflowException(String message) {
super(message);
}
}
}
|