View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.http.protocol;
29  
30  import java.io.IOException;
31  
32  import org.apache.hc.core5.annotation.Contract;
33  import org.apache.hc.core5.annotation.ThreadingBehavior;
34  import org.apache.hc.core5.http.EntityDetails;
35  import org.apache.hc.core5.http.Header;
36  import org.apache.hc.core5.http.HeaderElements;
37  import org.apache.hc.core5.http.HttpException;
38  import org.apache.hc.core5.http.HttpHeaders;
39  import org.apache.hc.core5.http.HttpRequest;
40  import org.apache.hc.core5.http.HttpRequestInterceptor;
41  import org.apache.hc.core5.http.HttpVersion;
42  import org.apache.hc.core5.http.Method;
43  import org.apache.hc.core5.http.ProtocolException;
44  import org.apache.hc.core5.http.ProtocolVersion;
45  import org.apache.hc.core5.http.message.MessageSupport;
46  import org.apache.hc.core5.util.Args;
47  
48  /**
49   * This request interceptor is responsible for delimiting the message content
50   * by adding {@code Content-Length} or {@code Transfer-Content} headers based
51   * on the properties of the enclosed entity and the protocol version.
52   * <p>
53   * This interceptor is essential for the HTTP protocol conformance and
54   * the correct operation of the client-side message processing pipeline.
55   * </p>
56   *
57   * @since 4.0
58   */
59  @Contract(threading = ThreadingBehavior.IMMUTABLE)
60  public class RequestContent implements HttpRequestInterceptor {
61  
62      /**
63       * Singleton instance.
64       * @since 5.2
65       */
66      public static final HttpRequestInterceptor INSTANCE = new RequestContent();
67  
68      private final boolean overwrite;
69  
70      /**
71       * Default constructor. The {@code Content-Length} or {@code Transfer-Encoding}
72       * will cause the interceptor to throw {@link ProtocolException} if already present in the
73       * response message.
74       */
75      public RequestContent() {
76          this(false);
77      }
78  
79      /**
80       * Constructor that can be used to fine-tune behavior of this interceptor.
81       *
82       * @param overwrite If set to {@code true} the {@code Content-Length} and
83       * {@code Transfer-Encoding} headers will be created or updated if already present.
84       * If set to {@code false} the {@code Content-Length} and
85       * {@code Transfer-Encoding} headers will cause the interceptor to throw
86       * {@link ProtocolException} if already present in the response message.
87       *
88       * @since 4.2
89       */
90       public RequestContent(final boolean overwrite) {
91           super();
92           this.overwrite = overwrite;
93      }
94  
95      @Override
96      public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context)
97              throws HttpException, IOException {
98          Args.notNull(request, "HTTP request");
99          final String method = request.getMethod();
100         if (Method.TRACE.isSame(method) && entity != null) {
101             throw new ProtocolException("TRACE request may not enclose an entity");
102         }
103         if (this.overwrite) {
104             request.removeHeaders(HttpHeaders.TRANSFER_ENCODING);
105             request.removeHeaders(HttpHeaders.CONTENT_LENGTH);
106         } else {
107             if (request.containsHeader(HttpHeaders.TRANSFER_ENCODING)) {
108                 throw new ProtocolException("Transfer-encoding header already present");
109             }
110             if (request.containsHeader(HttpHeaders.CONTENT_LENGTH)) {
111                 throw new ProtocolException("Content-Length header already present");
112             }
113         }
114         if (entity == null && isContentEnclosingMethod(method)) {
115             request.addHeader(HttpHeaders.CONTENT_LENGTH, "0");
116             return;
117         }
118         if (entity != null) {
119 
120             // Check for OPTIONS request with content but no Content-Type header
121             validateOptionsContentType(request);
122 
123             final ProtocolVersion ver = context.getProtocolVersion();
124             // Must specify a transfer encoding or a content length
125             if (entity.isChunked() || entity.getContentLength() < 0) {
126                 if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
127                     throw new ProtocolException(
128                             "Chunked transfer encoding not allowed for " + ver);
129                 }
130                 request.addHeader(HttpHeaders.TRANSFER_ENCODING, HeaderElements.CHUNKED_ENCODING);
131                 MessageSupport.addTrailerHeader(request, entity);
132             } else {
133                 request.addHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(entity.getContentLength()));
134             }
135             MessageSupport.addContentTypeHeader(request, entity);
136             MessageSupport.addContentEncodingHeader(request, entity);
137         }
138     }
139     private boolean isContentEnclosingMethod(final String method) {
140         return (Method.POST.isSame(method)||Method.PUT.isSame(method)||Method.PATCH.isSame(method));
141     }
142     /**
143      * Validates the presence of the Content-Type header for an OPTIONS request.
144      *
145      * <p>
146      * According to the RFC specifications, an HTTP {@link Method#OPTIONS} request that contains content
147      * must have a Content-Type header. This method checks for the presence of the Content-Type header
148      * in such requests. It does not validate the actual value of the Content-Type header, as determining
149      * its validity would require knowledge of all valid media types, which is beyond the scope of this method.
150      * If the header is absent, a {@link ProtocolException} is thrown.
151      * </p>
152      *
153      * <p>
154      * Note: This method does not check the validity of the Content-Type header value, only its presence.
155      * </p>
156      *
157      * @param request The {@link HttpRequest} to be validated for the presence of the Content-Type header. Must not be null.
158      * @throws ProtocolException If the Content-Type header is missing in an OPTIONS request with content.
159      */
160     public void validateOptionsContentType(final HttpRequest request) throws ProtocolException {
161         if (Method.OPTIONS.isSame(request.getMethod())) {
162             final Header header = request.getFirstHeader(HttpHeaders.CONTENT_TYPE);
163             if (header == null) {
164                 throw new ProtocolException("OPTIONS request must have Content-Type header");
165             }
166         }
167     }
168 }