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.DefaultHttpResponse;
32  import org.apache.mina.http.api.HttpEndOfContent;
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   * An HTTP decoder
40   * 
41   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
42   */
43  public class HttpClientDecoder implements ProtocolDecoder {
44      private static final Logger LOG = LoggerFactory.getLogger(HttpClientCodec.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      /** Key for indicating chunked data */
56      private static final String BODY_CHUNKED = "http.ckd";
57      
58      /** Regex to parse HttpRequest Request Line */
59      public static final Pattern REQUEST_LINE_PATTERN = Pattern.compile(" ");
60  
61      /** Regex to parse HttpRequest Request Line */
62      public static final Pattern RESPONSE_LINE_PATTERN = Pattern.compile(" ");
63  
64      /** Regex to parse out QueryString from HttpRequest */
65      public static final Pattern QUERY_STRING_PATTERN = Pattern.compile("\\?");
66  
67      /** Regex to parse out parameters from query string */
68      public static final Pattern PARAM_STRING_PATTERN = Pattern.compile("\\&|;");
69  
70      /** Regex to parse out key/value pairs */
71      public static final Pattern KEY_VALUE_PATTERN = Pattern.compile("=");
72  
73      /** Regex to parse raw headers and body */
74      public static final Pattern RAW_VALUE_PATTERN = Pattern.compile("\\r\\n\\r\\n");
75  
76      /** Regex to parse raw headers from body */
77      public static final Pattern HEADERS_BODY_PATTERN = Pattern.compile("\\r\\n");
78  
79      /** Regex to parse header name and value */
80      public static final Pattern HEADER_VALUE_PATTERN = Pattern.compile(": ");
81  
82      /** Regex to split cookie header following RFC6265 Section 5.4 */
83      public static final Pattern COOKIE_SEPARATOR_PATTERN = Pattern.compile(";");
84  
85      /**
86       * {@inheritDoc}
87       */
88      @Override
89      public void decode(IoSession session, IoBuffer msg, ProtocolDecoderOutput out) {
90          DecoderState state = (DecoderState)session.getAttribute(DECODER_STATE_ATT);
91          
92          if (null == state) {
93              session.setAttribute(DECODER_STATE_ATT, DecoderState.NEW);
94              state = (DecoderState)session.getAttribute(DECODER_STATE_ATT);
95          }
96          
97          switch (state) {
98              case HEAD:
99                  LOG.debug("decoding HEAD");
100                 // grab the stored a partial HEAD request
101                 ByteBuffer oldBuffer = (ByteBuffer)session.getAttribute(PARTIAL_HEAD_ATT);
102                 // concat the old buffer and the new incoming one
103                 IoBuffer.allocate(oldBuffer.remaining() + msg.remaining()).put(oldBuffer).put(msg).flip();
104                 // now let's decode like it was a new message
105     
106             case NEW:
107                 LOG.debug("decoding NEW");
108                 DefaultHttpResponse rp = parseHttpReponseHead(msg.buf());
109     
110                 if (rp == null) {
111                     // we copy the incoming BB because it's going to be recycled by the inner IoProcessor for next reads
112                     ByteBuffer partial = ByteBuffer.allocate(msg.remaining());
113                     partial.put(msg.buf());
114                     partial.flip();
115                     // no request decoded, we accumulate
116                     session.setAttribute(PARTIAL_HEAD_ATT, partial);
117                     session.setAttribute(DECODER_STATE_ATT, DecoderState.HEAD);
118                 } else {
119                     out.write(rp);
120                     // is it a response with some body content ?
121                     LOG.debug("response with content");
122                     session.setAttribute(DECODER_STATE_ATT, DecoderState.BODY);
123     
124                     String contentLen = rp.getHeader("content-length");
125     
126                     if (contentLen != null) {
127                         LOG.debug("found content len : {}", contentLen);
128                         session.setAttribute(BODY_REMAINING_BYTES, Integer.valueOf(contentLen));
129                     } else if ("chunked".equalsIgnoreCase(rp.getHeader("transfer-encoding"))) {
130                         LOG.debug("no content len but chunked");
131                         session.setAttribute(BODY_CHUNKED, Boolean.TRUE);
132                     } else if ("close".equalsIgnoreCase(rp.getHeader("connection"))) {
133                         session.closeNow();
134                     } else {
135                         throw new HttpException(HttpStatus.CLIENT_ERROR_LENGTH_REQUIRED, "no content length !");
136                     }
137                 }
138     
139                 break;
140     
141             case BODY:
142                 LOG.debug("decoding BODY: {} bytes", msg.remaining());
143                 int chunkSize = msg.remaining();
144                 
145                 // send the chunk of body
146                 if (chunkSize != 0) {
147                     IoBuffer wb = IoBuffer.allocate(msg.remaining());
148                     wb.put(msg);
149                     wb.flip();
150                     out.write(wb);
151                 }
152                 
153                 msg.position(msg.limit());
154                 
155                 // do we have reach end of body ?
156                 int remaining;
157                 
158                 // if chunked, remaining is the msg.remaining()
159                 if( session.getAttribute(BODY_CHUNKED) != null ) {
160                     remaining = chunkSize;
161                 } else {
162                     // otherwise, manage with content-length
163                     remaining = (Integer) session.getAttribute(BODY_REMAINING_BYTES);
164                     remaining -= chunkSize;
165                 }
166     
167                 if (remaining <= 0 ) {
168                     LOG.debug("end of HTTP body");
169                     session.setAttribute(DECODER_STATE_ATT, DecoderState.NEW);
170                     session.removeAttribute(BODY_REMAINING_BYTES);
171                     
172                     if( session.getAttribute(BODY_CHUNKED) != null ) {
173                         session.removeAttribute(BODY_CHUNKED);
174                     }
175                     
176                     out.write(new HttpEndOfContent());
177                 } else {
178                     if( session.getAttribute(BODY_CHUNKED) == null ) {
179                         session.setAttribute(BODY_REMAINING_BYTES, Integer.valueOf(remaining));
180                     }
181                 }
182     
183                 break;
184     
185             default:
186                 throw new HttpException(HttpStatus.SERVER_ERROR_INTERNAL_SERVER_ERROR, "Unknonwn decoder state : " + state);
187         }
188     }
189 
190     /**
191      * {@inheritDoc}
192      */
193     @Override
194     public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception {
195     }
196 
197     /**
198      * {@inheritDoc}
199      */
200     @Override
201     public void dispose(IoSession session) throws Exception {
202     }
203 
204     private DefaultHttpResponse parseHttpReponseHead(ByteBuffer buffer) {
205         String raw = new String(buffer.array(), 0, buffer.limit());
206         String[] headersAndBody = RAW_VALUE_PATTERN.split(raw, -1);
207         
208         if (headersAndBody.length <= 1) {
209             // we didn't receive the full HTTP head
210             return null;
211         }
212 
213         String[] headerFields = HEADERS_BODY_PATTERN.split(headersAndBody[0]);
214         headerFields = ArrayUtil.dropFromEndWhile(headerFields, "");
215 
216         String requestLine = headerFields[0];
217         Map<String, String> generalHeaders = new HashMap<>();
218 
219         for (String headerField:headerFields) {
220             String[] header = HEADER_VALUE_PATTERN.split(headerField);
221             generalHeaders.put(header[0].toLowerCase(), header[1]);
222         }
223 
224         String[] elements = RESPONSE_LINE_PATTERN.split(requestLine);
225         HttpStatus status = null;
226         int statusCode = Integer.parseInt(elements[1]);
227         
228         for (HttpStatus httpStatus:HttpStatus.values()) {
229             if (statusCode == httpStatus.code()) {
230                 
231                 break;
232             }
233         }
234         
235         HttpVersion version = HttpVersion.fromString(elements[0]);
236 
237         // we put the buffer position where we found the beginning of the HTTP body
238         buffer.position(headersAndBody[0].length() + 4);
239 
240         return new DefaultHttpResponse(version, status, generalHeaders);
241     }
242 }