Path: blob/master/src/java.net.http/share/classes/jdk/internal/net/http/Http1HeaderParser.java
41171 views
/*1* Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package jdk.internal.net.http;2627import java.net.ProtocolException;28import java.nio.BufferUnderflowException;29import java.nio.ByteBuffer;30import java.util.ArrayList;31import java.util.HashMap;32import java.util.List;33import java.util.Locale;34import java.util.Map;35import java.net.http.HttpHeaders;3637import jdk.internal.net.http.common.Utils;3839import static java.lang.String.format;40import static java.util.Objects.requireNonNull;41import static jdk.internal.net.http.common.Utils.ACCEPT_ALL;4243class Http1HeaderParser {4445private static final char CR = '\r';46private static final char LF = '\n';47private static final char HT = '\t';48private static final char SP = ' ';4950private StringBuilder sb = new StringBuilder();51private String statusLine;52private int responseCode;53private HttpHeaders headers;54private Map<String,List<String>> privateMap = new HashMap<>();5556enum State { INITIAL,57STATUS_LINE,58STATUS_LINE_FOUND_CR,59STATUS_LINE_FOUND_LF,60STATUS_LINE_END,61STATUS_LINE_END_CR,62STATUS_LINE_END_LF,63HEADER,64HEADER_FOUND_CR,65HEADER_FOUND_LF,66HEADER_FOUND_CR_LF,67HEADER_FOUND_CR_LF_CR,68FINISHED }6970private State state = State.INITIAL;7172/** Returns the status-line. */73String statusLine() { return statusLine; }7475/** Returns the response code. */76int responseCode() { return responseCode; }7778/** Returns the headers, possibly empty. */79HttpHeaders headers() {80assert state == State.FINISHED : "Unexpected state " + state;81return headers;82}8384/** A current-state message suitable for inclusion in an exception detail message. */85public String currentStateMessage() {86String stateName = state.name();87String msg;88if (stateName.contains("INITIAL")) {89return format("HTTP/1.1 header parser received no bytes");90} else if (stateName.contains("STATUS")) {91msg = format("parsing HTTP/1.1 status line, receiving [%s]", sb.toString());92} else if (stateName.contains("HEADER")) {93String headerName = sb.toString();94if (headerName.indexOf(':') != -1)95headerName = headerName.substring(0, headerName.indexOf(':')+1) + "...";96msg = format("parsing HTTP/1.1 header, receiving [%s]", headerName);97} else {98msg = format("HTTP/1.1 parser receiving [%s]", sb.toString());99}100return format("%s, parser state [%s]", msg, state);101}102103/**104* Parses HTTP/1.X status-line and headers from the given bytes. Must be105* called successive times, with additional data, until returns true.106*107* All given ByteBuffers will be consumed, until ( possibly ) the last one108* ( when true is returned ), which may not be fully consumed.109*110* @param input the ( partial ) header data111* @return true iff the end of the headers block has been reached112*/113boolean parse(ByteBuffer input) throws ProtocolException {114requireNonNull(input, "null input");115116while (canContinueParsing(input)) {117switch (state) {118case INITIAL -> state = State.STATUS_LINE;119case STATUS_LINE -> readResumeStatusLine(input);120case STATUS_LINE_FOUND_CR, STATUS_LINE_FOUND_LF -> readStatusLineFeed(input);121case STATUS_LINE_END -> maybeStartHeaders(input);122case STATUS_LINE_END_CR, STATUS_LINE_END_LF -> maybeEndHeaders(input);123case HEADER -> readResumeHeader(input);124case HEADER_FOUND_CR, HEADER_FOUND_LF -> resumeOrLF(input);125case HEADER_FOUND_CR_LF -> resumeOrSecondCR(input);126case HEADER_FOUND_CR_LF_CR -> resumeOrEndHeaders(input);127128default -> throw new InternalError("Unexpected state: " + state);129}130}131132return state == State.FINISHED;133}134135private boolean canContinueParsing(ByteBuffer buffer) {136// some states don't require any input to transition137// to the next state.138return switch (state) {139case FINISHED -> false;140case STATUS_LINE_FOUND_LF, STATUS_LINE_END_LF, HEADER_FOUND_LF -> true;141default -> buffer.hasRemaining();142};143}144145/**146* Returns a character (char) corresponding to the next byte in the147* input, interpreted as an ISO-8859-1 encoded character.148* <p>149* The ISO-8859-1 encoding is a 8-bit character coding that150* corresponds to the first 256 Unicode characters - from U+0000 to151* U+00FF. UTF-16 is backward compatible with ISO-8859-1 - which152* means each byte in the input should be interpreted as an unsigned153* value from [0, 255] representing the character code.154*155* @param input a {@code ByteBuffer} containing a partial input156* @return the next byte in the input, interpreted as an ISO-8859-1157* encoded char158* @throws BufferUnderflowException159* if the input buffer's current position is not smaller160* than its limit161*/162private char get(ByteBuffer input) {163return (char)(input.get() & 0xFF);164}165166private void readResumeStatusLine(ByteBuffer input) {167char c = 0;168while (input.hasRemaining() && (c = get(input)) != CR) {169if (c == LF) break;170sb.append(c);171}172if (c == CR) {173state = State.STATUS_LINE_FOUND_CR;174} else if (c == LF) {175state = State.STATUS_LINE_FOUND_LF;176}177}178179private void readStatusLineFeed(ByteBuffer input) throws ProtocolException {180char c = state == State.STATUS_LINE_FOUND_LF ? LF : get(input);181if (c != LF) {182throw protocolException("Bad trailing char, \"%s\", when parsing status line, \"%s\"",183c, sb.toString());184}185186statusLine = sb.toString();187sb = new StringBuilder();188if (!statusLine.startsWith("HTTP/1.")) {189throw protocolException("Invalid status line: \"%s\"", statusLine);190}191if (statusLine.length() < 12) {192throw protocolException("Invalid status line: \"%s\"", statusLine);193}194try {195responseCode = Integer.parseInt(statusLine.substring(9, 12));196} catch (NumberFormatException nfe) {197throw protocolException("Invalid status line: \"%s\"", statusLine);198}199// response code expected to be a 3-digit integer (RFC-2616, section 6.1.1)200if (responseCode < 100) {201throw protocolException("Invalid status line: \"%s\"", statusLine);202}203204state = State.STATUS_LINE_END;205}206207private void maybeStartHeaders(ByteBuffer input) {208assert state == State.STATUS_LINE_END;209assert sb.length() == 0;210char c = get(input);211if (c == CR) {212state = State.STATUS_LINE_END_CR;213} else if (c == LF) {214state = State.STATUS_LINE_END_LF;215} else {216sb.append(c);217state = State.HEADER;218}219}220221private void maybeEndHeaders(ByteBuffer input) throws ProtocolException {222assert state == State.STATUS_LINE_END_CR || state == State.STATUS_LINE_END_LF;223assert sb.length() == 0;224char c = state == State.STATUS_LINE_END_LF ? LF : get(input);225if (c == LF) {226headers = HttpHeaders.of(privateMap, ACCEPT_ALL);227privateMap = null;228state = State.FINISHED; // no headers229} else {230throw protocolException("Unexpected \"%s\", after status line CR", c);231}232}233234private void readResumeHeader(ByteBuffer input) {235assert state == State.HEADER;236assert input.hasRemaining();237while (input.hasRemaining()) {238char c = get(input);239if (c == CR) {240state = State.HEADER_FOUND_CR;241break;242} else if (c == LF) {243state = State.HEADER_FOUND_LF;244break;245}246247if (c == HT)248c = SP;249sb.append(c);250}251}252253private void addHeaderFromString(String headerString) throws ProtocolException {254assert sb.length() == 0;255int idx = headerString.indexOf(':');256if (idx == -1)257return;258String name = headerString.substring(0, idx);259260// compatibility with HttpURLConnection;261if (name.isEmpty()) return;262263if (!Utils.isValidName(name)) {264throw protocolException("Invalid header name \"%s\"", name);265}266String value = headerString.substring(idx + 1).trim();267if (!Utils.isValidValue(value)) {268throw protocolException("Invalid header value \"%s: %s\"", name, value);269}270271privateMap.computeIfAbsent(name.toLowerCase(Locale.US),272k -> new ArrayList<>()).add(value);273}274275private void resumeOrLF(ByteBuffer input) {276assert state == State.HEADER_FOUND_CR || state == State.HEADER_FOUND_LF;277char c = state == State.HEADER_FOUND_LF ? LF : get(input);278if (c == LF) {279// header value will be flushed by280// resumeOrSecondCR if next line does not281// begin by SP or HT282state = State.HEADER_FOUND_CR_LF;283} else if (c == SP || c == HT) {284sb.append(SP); // parity with MessageHeaders285state = State.HEADER;286} else {287sb = new StringBuilder();288sb.append(c);289state = State.HEADER;290}291}292293private void resumeOrSecondCR(ByteBuffer input) throws ProtocolException {294assert state == State.HEADER_FOUND_CR_LF;295char c = get(input);296if (c == CR || c == LF) {297if (sb.length() > 0) {298// no continuation line - flush299// previous header value.300String headerString = sb.toString();301sb = new StringBuilder();302addHeaderFromString(headerString);303}304if (c == CR) {305state = State.HEADER_FOUND_CR_LF_CR;306} else {307state = State.FINISHED;308headers = HttpHeaders.of(privateMap, ACCEPT_ALL);309privateMap = null;310}311} else if (c == SP || c == HT) {312assert sb.length() != 0;313sb.append(SP); // continuation line314state = State.HEADER;315} else {316if (sb.length() > 0) {317// no continuation line - flush318// previous header value.319String headerString = sb.toString();320sb = new StringBuilder();321addHeaderFromString(headerString);322}323sb.append(c);324state = State.HEADER;325}326}327328private void resumeOrEndHeaders(ByteBuffer input) throws ProtocolException {329assert state == State.HEADER_FOUND_CR_LF_CR;330char c = get(input);331if (c == LF) {332state = State.FINISHED;333headers = HttpHeaders.of(privateMap, ACCEPT_ALL);334privateMap = null;335} else {336throw protocolException("Unexpected \"%s\", after CR LF CR", c);337}338}339340private ProtocolException protocolException(String format, Object... args) {341return new ProtocolException(format(format, args));342}343}344345346