View Javadoc
1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *  
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *  
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License. 
18   *  
19   */
20  package org.apache.mina.http;
21  
22  import java.nio.ByteBuffer;
23  import java.util.HashMap;
24  import java.util.Map;
25  import java.util.regex.Pattern;
26  
27  import org.apache.mina.core.buffer.IoBuffer;
28  import org.apache.mina.core.session.IoSession;
29  import org.apache.mina.filter.codec.ProtocolDecoder;
30  import org.apache.mina.filter.codec.ProtocolDecoderOutput;
31  import org.apache.mina.http.api.HttpEndOfContent;
32  import org.apache.mina.http.api.HttpMethod;
33  import org.apache.mina.http.api.HttpStatus;
34  import org.apache.mina.http.api.HttpVersion;
35  import org.slf4j.Logger;
36  import org.slf4j.LoggerFactory;
37  
38  /**
39   * The HTTP decoder
40   * 
41   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
42   */
43  public class HttpServerDecoder implements ProtocolDecoder {
44      private static final Logger LOG = LoggerFactory.getLogger(HttpServerCodec.class);
45  
46      /** Key for decoder current state */
47      private static final String DECODER_STATE_ATT = "http.ds";
48  
49      /** Key for the partial HTTP requests head */
50      private static final String PARTIAL_HEAD_ATT = "http.ph";
51  
52      /** Key for the number of bytes remaining to read for completing the body */
53      private static final String BODY_REMAINING_BYTES = "http.brb";
54  
55      /** Regex to parse HttpRequest Request Line */
56      public static final Pattern REQUEST_LINE_PATTERN = Pattern.compile(" ");
57  
58      /** Regex to parse out QueryString from HttpRequest */
59      public static final Pattern QUERY_STRING_PATTERN = Pattern.compile("\\?");
60  
61      /** Regex to parse out parameters from query string */
62      public static final Pattern PARAM_STRING_PATTERN = Pattern.compile("\\&|;");
63  
64      /** Regex to parse out key/value pairs */
65      public static final Pattern KEY_VALUE_PATTERN = Pattern.compile("=");
66  
67      /** Regex to parse raw headers and body */
68      public static final Pattern RAW_VALUE_PATTERN = Pattern.compile("\\r\\n\\r\\n");
69  
70      /** Regex to parse raw headers from body */
71      public static final Pattern HEADERS_BODY_PATTERN = Pattern.compile("\\r\\n");
72  
73      /** Regex to parse header name and value */
74      public static final Pattern HEADER_VALUE_PATTERN = Pattern.compile(":");
75  
76      /** Regex to split cookie header following RFC6265 Section 5.4 */
77      public static final Pattern COOKIE_SEPARATOR_PATTERN = Pattern.compile(";");
78  
79      /**
80       * {@inheritDoc}
81       */
82      @Override
83      public void decode(IoSession session, IoBuffer msg, ProtocolDecoderOutput out) {
84          DecoderState state = (DecoderState) session.getAttribute(DECODER_STATE_ATT);
85          
86          if (null == state) {
87              session.setAttribute(DECODER_STATE_ATT, DecoderState.NEW);
88              state = (DecoderState) session.getAttribute(DECODER_STATE_ATT);
89          }
90          
91          switch (state) {
92              case HEAD:
93                  LOG.debug("decoding HEAD");
94                  // grab the stored a partial HEAD request
95                  ByteBuffer oldBuffer = (ByteBuffer) session.getAttribute(PARTIAL_HEAD_ATT);
96                  // concat the old buffer and the new incoming one
97                  // now let's decode like it was a new message
98                  msg = IoBuffer.allocate(oldBuffer.remaining() + msg.remaining()).put(oldBuffer).put(msg).flip();
99                  
100             case NEW:
101                 LOG.debug("decoding NEW");
102                 HttpRequestImpl rq = parseHttpRequestHead(msg.buf());
103     
104                 if (rq == null) {
105                     // we copy the incoming BB because it's going to be recycled by the inner IoProcessor for next reads
106                     ByteBuffer partial = ByteBuffer.allocate(msg.remaining());
107                     partial.put(msg.buf());
108                     partial.flip();
109                     // no request decoded, we accumulate
110                     session.setAttribute(PARTIAL_HEAD_ATT, partial);
111                     session.setAttribute(DECODER_STATE_ATT, DecoderState.HEAD);
112                     break;
113                 } else {
114                     out.write(rq);
115                     // is it a request with some body content ?
116                     String contentLen = rq.getHeader("content-length");
117     
118                     if (contentLen != null) {
119                         LOG.debug("found content len : {}", contentLen);
120                         session.setAttribute(BODY_REMAINING_BYTES, Integer.valueOf(contentLen));
121                         session.setAttribute(DECODER_STATE_ATT, DecoderState.BODY);
122                         // fallthrough, process body immediately
123                     } else {
124                         LOG.debug("request without content");
125                         session.setAttribute(DECODER_STATE_ATT, DecoderState.NEW);
126                         out.write(new HttpEndOfContent());
127                         break;
128                     }
129                 }
130     
131             case BODY:
132                 LOG.debug("decoding BODY: {} bytes", msg.remaining());
133                 int chunkSize = msg.remaining();
134                 
135                 // send the chunk of body
136                 if (chunkSize != 0) {
137                     IoBuffer wb = IoBuffer.allocate(msg.remaining());
138                     wb.put(msg);
139                     wb.flip();
140                     out.write(wb);
141                 }
142                 
143                 msg.position(msg.limit());
144                 // do we have reach end of body ?
145                 int remaining = (Integer) session.getAttribute(BODY_REMAINING_BYTES);
146                 remaining -= chunkSize;
147     
148                 if (remaining <= 0) {
149                     LOG.debug("end of HTTP body");
150                     session.setAttribute(DECODER_STATE_ATT, DecoderState.NEW);
151                     session.removeAttribute(BODY_REMAINING_BYTES);
152                     out.write(new HttpEndOfContent());
153                 } else {
154                     session.setAttribute(BODY_REMAINING_BYTES, Integer.valueOf(remaining));
155                 }
156     
157                 break;
158     
159             default:
160                 throw new HttpException(HttpStatus.CLIENT_ERROR_BAD_REQUEST, "Unknonwn decoder state : " + state);
161         }
162     }
163 
164     /**
165      * {@inheritDoc}
166      */
167     @Override
168     public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception {
169     }
170 
171     /**
172      * {@inheritDoc}
173      */
174     @Override
175     public void dispose(IoSession session) throws Exception {
176     }
177 
178     private HttpRequestImpl parseHttpRequestHead(ByteBuffer buffer) {
179         String raw = new String(buffer.array(), 0, buffer.limit());
180         String[] headersAndBody = RAW_VALUE_PATTERN.split(raw, -1);
181 
182         if (headersAndBody.length <= 1) {
183             // we didn't receive the full HTTP head
184             return null;
185         }
186 
187         String[] headerFields = HEADERS_BODY_PATTERN.split(headersAndBody[0]);
188         headerFields = ArrayUtil.dropFromEndWhile(headerFields, "");
189 
190         String requestLine = headerFields[0];
191         Map<String, String> generalHeaders = new HashMap<>();
192 
193         for (int i = 1; i < headerFields.length; i++) {
194             String[] header = HEADER_VALUE_PATTERN.split(headerFields[i]);
195             generalHeaders.put(header[0].toLowerCase(), header[1].trim());
196         }
197 
198         String[] elements = REQUEST_LINE_PATTERN.split(requestLine);
199         HttpMethod method = HttpMethod.valueOf(elements[0]);
200         HttpVersion version = HttpVersion.fromString(elements[2]);
201         String[] pathFrags = QUERY_STRING_PATTERN.split(elements[1]);
202         String requestedPath = pathFrags[0];
203         String queryString = pathFrags.length == 2 ? pathFrags[1] : "";
204 
205         // we put the buffer position where we found the beginning of the HTTP body
206         buffer.position(headersAndBody[0].length() + 4);
207 
208         return new HttpRequestImpl(version, method, requestedPath, queryString, generalHeaders);
209     }
210 }