1 /*
   2  * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.internal.net.http;
  27 
  28 import java.net.ProtocolException;
  29 import java.nio.ByteBuffer;
  30 import java.util.ArrayList;
  31 import java.util.HashMap;
  32 import java.util.List;
  33 import java.util.Locale;
  34 import java.util.Map;
  35 import java.net.http.HttpHeaders;
  36 import static java.lang.String.format;
  37 import static java.util.Objects.requireNonNull;
  38 import static jdk.internal.net.http.common.Utils.ACCEPT_ALL;
  39 
  40 class Http1HeaderParser {
  41 
  42     private static final char CR = '\r';
  43     private static final char LF = '\n';
  44     private static final char HT = '\t';
  45     private static final char SP = ' ';
  46 
  47     private StringBuilder sb = new StringBuilder();
  48     private String statusLine;
  49     private int responseCode;
  50     private HttpHeaders headers;
  51     private Map<String,List<String>> privateMap = new HashMap<>();
  52 
  53     enum State { INITIAL,
  54                  STATUS_LINE,
  55                  STATUS_LINE_FOUND_CR,
  56                  STATUS_LINE_FOUND_LF,
  57                  STATUS_LINE_END,
  58                  STATUS_LINE_END_CR,
  59                  STATUS_LINE_END_LF,
  60                  HEADER,
  61                  HEADER_FOUND_CR,
  62                  HEADER_FOUND_LF,
  63                  HEADER_FOUND_CR_LF,
  64                  HEADER_FOUND_CR_LF_CR,
  65                  FINISHED }
  66 
  67     private State state = State.INITIAL;
  68 
  69     /** Returns the status-line. */
  70     String statusLine() { return statusLine; }
  71 
  72     /** Returns the response code. */
  73     int responseCode() { return responseCode; }
  74 
  75     /** Returns the headers, possibly empty. */
  76     HttpHeaders headers() {
  77         assert state == State.FINISHED : "Unexpected state " + state;
  78         return headers;
  79     }
  80 
  81     /** A current-state message suitable for inclusion in an exception detail message. */
  82     public String currentStateMessage() {
  83         String stateName = state.name();
  84         String msg;
  85         if (stateName.contains("INITIAL")) {
  86             return format("HTTP/1.1 header parser received no bytes");
  87         } else if (stateName.contains("STATUS")) {
  88             msg = format("parsing HTTP/1.1 status line, receiving [%s]", sb.toString());
  89         } else if (stateName.contains("HEADER")) {
  90             String headerName = sb.toString();
  91             if (headerName.indexOf(':') != -1)
  92                 headerName = headerName.substring(0, headerName.indexOf(':')+1) + "...";
  93             msg = format("parsing HTTP/1.1 header, receiving [%s]", headerName);
  94         } else {
  95             msg =format("HTTP/1.1 parser receiving [%s]", state, sb.toString());
  96         }
  97         return format("%s, parser state [%s]", msg , state);
  98     }
  99 
 100     /**
 101      * Parses HTTP/1.X status-line and headers from the given bytes. Must be
 102      * called successive times, with additional data, until returns true.
 103      *
 104      * All given ByteBuffers will be consumed, until ( possibly ) the last one
 105      * ( when true is returned ), which may not be fully consumed.
 106      *
 107      * @param input the ( partial ) header data
 108      * @return true iff the end of the headers block has been reached
 109      */
 110     boolean parse(ByteBuffer input) throws ProtocolException {
 111         requireNonNull(input, "null input");
 112 
 113         while (canContinueParsing(input)) {
 114             switch (state) {
 115                 case INITIAL:
 116                     state = State.STATUS_LINE;
 117                     break;
 118                 case STATUS_LINE:
 119                     readResumeStatusLine(input);
 120                     break;
 121                 // fallthrough
 122                 case STATUS_LINE_FOUND_CR:
 123                 case STATUS_LINE_FOUND_LF:
 124                     readStatusLineFeed(input);
 125                     break;
 126                 case STATUS_LINE_END:
 127                     maybeStartHeaders(input);
 128                     break;
 129                 // fallthrough
 130                 case STATUS_LINE_END_CR:
 131                 case STATUS_LINE_END_LF:
 132                     maybeEndHeaders(input);
 133                     break;
 134                 case HEADER:
 135                     readResumeHeader(input);
 136                     break;
 137                 // fallthrough
 138                 case HEADER_FOUND_CR:
 139                 case HEADER_FOUND_LF:
 140                     resumeOrLF(input);
 141                     break;
 142                 case HEADER_FOUND_CR_LF:
 143                     resumeOrSecondCR(input);
 144                     break;
 145                 case HEADER_FOUND_CR_LF_CR:
 146                     resumeOrEndHeaders(input);
 147                     break;
 148                 default:
 149                     throw new InternalError(
 150                             "Unexpected state: " + String.valueOf(state));
 151             }
 152         }
 153 
 154         return state == State.FINISHED;
 155     }
 156 
 157     private boolean canContinueParsing(ByteBuffer buffer) {
 158         // some states don't require any input to transition
 159         // to the next state.
 160         switch (state) {
 161             case FINISHED: return false;
 162             case STATUS_LINE_FOUND_LF: return true;
 163             case STATUS_LINE_END_LF: return true;
 164             case HEADER_FOUND_LF: return true;
 165             default: return buffer.hasRemaining();
 166         }
 167     }
 168 
 169     private void readResumeStatusLine(ByteBuffer input) {
 170         char c = 0;
 171         while (input.hasRemaining() && (c =(char)input.get()) != CR) {
 172             if (c == LF) break;
 173             sb.append(c);
 174         }
 175         if (c == CR) {
 176             state = State.STATUS_LINE_FOUND_CR;
 177         } else if (c == LF) {
 178             state = State.STATUS_LINE_FOUND_LF;
 179         }
 180     }
 181 
 182     private void readStatusLineFeed(ByteBuffer input) throws ProtocolException {
 183         char c = state == State.STATUS_LINE_FOUND_LF ? LF : (char)input.get();
 184         if (c != LF) {
 185             throw protocolException("Bad trailing char, \"%s\", when parsing status line, \"%s\"",
 186                                     c, sb.toString());
 187         }
 188 
 189         statusLine = sb.toString();
 190         sb = new StringBuilder();
 191         if (!statusLine.startsWith("HTTP/1.")) {
 192             throw protocolException("Invalid status line: \"%s\"", statusLine);
 193         }
 194         if (statusLine.length() < 12) {
 195             throw protocolException("Invalid status line: \"%s\"", statusLine);
 196         }
 197         responseCode = Integer.parseInt(statusLine.substring(9, 12));
 198 
 199         state = State.STATUS_LINE_END;
 200     }
 201 
 202     private void maybeStartHeaders(ByteBuffer input) {
 203         assert state == State.STATUS_LINE_END;
 204         assert sb.length() == 0;
 205         char c = (char)input.get();
 206         if (c == CR) {
 207             state = State.STATUS_LINE_END_CR;
 208         } else if (c == LF) {
 209             state = State.STATUS_LINE_END_LF;
 210         } else {
 211             sb.append(c);
 212             state = State.HEADER;
 213         }
 214     }
 215 
 216     private void maybeEndHeaders(ByteBuffer input) throws ProtocolException {
 217         assert state == State.STATUS_LINE_END_CR || state == State.STATUS_LINE_END_LF;
 218         assert sb.length() == 0;
 219         char c = state == State.STATUS_LINE_END_LF ? LF : (char)input.get();
 220         if (c == LF) {
 221             headers = HttpHeaders.of(privateMap, ACCEPT_ALL);
 222             privateMap = null;
 223             state = State.FINISHED;  // no headers
 224         } else {
 225             throw protocolException("Unexpected \"%s\", after status line CR", c);
 226         }
 227     }
 228 
 229     private void readResumeHeader(ByteBuffer input) {
 230         assert state == State.HEADER;
 231         assert input.hasRemaining();
 232         while (input.hasRemaining()) {
 233             char c = (char)input.get();
 234             if (c == CR) {
 235                 state = State.HEADER_FOUND_CR;
 236                 break;
 237             } else if (c == LF) {
 238                 state = State.HEADER_FOUND_LF;
 239                 break;
 240             }
 241 
 242             if (c == HT)
 243                 c = SP;
 244             sb.append(c);
 245         }
 246     }
 247 
 248     private void addHeaderFromString(String headerString) {
 249         assert sb.length() == 0;
 250         int idx = headerString.indexOf(':');
 251         if (idx == -1)
 252             return;
 253         String name = headerString.substring(0, idx).trim();
 254         if (name.isEmpty())
 255             return;
 256         String value = headerString.substring(idx + 1, headerString.length()).trim();
 257 
 258         privateMap.computeIfAbsent(name.toLowerCase(Locale.US),
 259                                    k -> new ArrayList<>()).add(value);
 260     }
 261 
 262     private void resumeOrLF(ByteBuffer input) {
 263         assert state == State.HEADER_FOUND_CR || state == State.HEADER_FOUND_LF;
 264         char c = state == State.HEADER_FOUND_LF ? LF : (char)input.get();
 265         if (c == LF) {
 266             // header value will be flushed by
 267             // resumeOrSecondCR if next line does not
 268             // begin by SP or HT
 269             state = State.HEADER_FOUND_CR_LF;
 270         } else if (c == SP || c == HT) {
 271             sb.append(SP); // parity with MessageHeaders
 272             state = State.HEADER;
 273         } else {
 274             sb = new StringBuilder();
 275             sb.append(c);
 276             state = State.HEADER;
 277         }
 278     }
 279 
 280     private void resumeOrSecondCR(ByteBuffer input) {
 281         assert state == State.HEADER_FOUND_CR_LF;
 282         char c = (char)input.get();
 283         if (c == CR || c == LF) {
 284             if (sb.length() > 0) {
 285                 // no continuation line - flush
 286                 // previous header value.
 287                 String headerString = sb.toString();
 288                 sb = new StringBuilder();
 289                 addHeaderFromString(headerString);
 290             }
 291             if (c == CR) {
 292                 state = State.HEADER_FOUND_CR_LF_CR;
 293             } else {
 294                 state = State.FINISHED;
 295                 headers = HttpHeaders.of(privateMap, ACCEPT_ALL);
 296                 privateMap = null;
 297             }
 298         } else if (c == SP || c == HT) {
 299             assert sb.length() != 0;
 300             sb.append(SP); // continuation line
 301             state = State.HEADER;
 302         } else {
 303             if (sb.length() > 0) {
 304                 // no continuation line - flush
 305                 // previous header value.
 306                 String headerString = sb.toString();
 307                 sb = new StringBuilder();
 308                 addHeaderFromString(headerString);
 309             }
 310             sb.append(c);
 311             state = State.HEADER;
 312         }
 313     }
 314 
 315     private void resumeOrEndHeaders(ByteBuffer input) throws ProtocolException {
 316         assert state == State.HEADER_FOUND_CR_LF_CR;
 317         char c = (char)input.get();
 318         if (c == LF) {
 319             state = State.FINISHED;
 320             headers = HttpHeaders.of(privateMap, ACCEPT_ALL);
 321             privateMap = null;
 322         } else {
 323             throw protocolException("Unexpected \"%s\", after CR LF CR", c);
 324         }
 325     }
 326 
 327     private ProtocolException protocolException(String format, Object... args) {
 328         return new ProtocolException(format(format, args));
 329     }
 330 }