Quantcast
Channel: Active questions tagged servlets - Stack Overflow
Viewing all articles
Browse latest Browse all 675

Spring MVC - measure length of incoming requests of type x-www-form-urlencoded

$
0
0

I'm using Spring Boot 2.7.18 and Spring MVC.
I made a OncePerRequestFilter that counts the bytes passing through the InputStream of each request, by "hijacking" the original InputStream and replacing it with an implementation that does the counting as the stream is being read from.

The problem is that this doesn't work with requests with Content-Type application/x-www-form-urlencoded because both Tomcat's and Undertow's implementations of the HttpServletRequest interface use their own internal instance of the InputStream to read the parameters of such type of requests, thus bypassing my solution.

I don't want to re-implement the getParameterValues method because it would surely be much less secure and thorough than Tomcat's and Undertow's, and copy-pasting one of their implementations in my code is also a no-no...

How can I get around this issue? Does Spring provide some way to read a request's length more easily? I can't rely on the Content-Length header because I have no guarantee that it's going to be set by the caller.

Important note: I do NOT only need to log the request body's length. The code below is just pseudo-code. I need to obtain the length of the request to do stuff with it, so please don't recommend me libraries that are only used to log the request's data (I saw there are at least a couple). Thank you.

Here's what I did so far:

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.concurrent.atomic.AtomicInteger;import javax.servlet.FilterChain;import javax.servlet.ReadListener;import javax.servlet.ServletException;import javax.servlet.ServletInputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpMethod;import org.springframework.http.MediaType;import org.springframework.web.filter.OncePerRequestFilter;public class RequestBodyMeasuringFilter extends OncePerRequestFilter {    private final Logger log = LoggerFactory.getLogger(RequestBodyMeasuringFilter.class);    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {        HttpServletRequest requestToUse;        boolean isFormRequest = MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(MediaType.parseMediaType(request.getContentType()));        if (!request.getMethod().equals(HttpMethod.POST.toString()) && !request.getMethod().equals(HttpMethod.PUT.toString())                || isFormRequest) {            if (isFormRequest)// falling back on the Content-Length header that isn't guaranteed to be present...                log.info("Request length: {}", request.getContentLength());            requestToUse = request;        } else {            requestToUse = new BodyMeasuringHttpServletRequestWrapper(request, value);        }        chain.doFilter(requestToUse, response);    }    private static class BytesCountingServletInputStream extends ServletInputStream {        private final AtomicInteger size = new AtomicInteger(0);        private final InputStream inputStream;        public BytesCountingServletInputStream(InputStream inputStream) {            this.inputStream = inputStream;        }        public int getSize() {            return this.size.get();        }        @Override        public boolean isFinished() {            try {                return inputStream.available() == 0;            } catch (IOException ex) {                log.error("Error in isFinished", ex);            }            return false;        }        @Override        public boolean isReady() {            return true;        }        @Override        public void setReadListener(ReadListener readListener) {            throw new UnsupportedOperationException();        }        @Override        public int read() throws IOException {            int r = this.inputStream.read();            if (r != -1) {                this.size.incrementAndGet();            } else {                // if r == -1 it means we reached the end of the stream.                // during tests I saw I can't rely on the "close" method...                log.info("Request length: {}", getSize());            }            return r;        }    }    public static class BodyMeasuringHttpServletRequestWrapper extends HttpServletRequestWrapper {        private BytesCountingServletInputStream inputStream;        public BodyMeasuringHttpServletRequestWrapper(HttpServletRequest request) {            super(request);        }        @Override        public int getContentLength() {            return inputStream.getSize();        }        @Override        public ServletInputStream getInputStream() {            replaceOriginalInputStream();            return inputStream;        }        @Override        public BufferedReader getReader() {            replaceOriginalInputStream();            return new BufferedReader(new InputStreamReader(inputStream));        }        private void replaceOriginalInputStream() {            try {                if (inputStream == null)                    inputStream = new BytesCountingServletInputStream(super.getInputStream());            } catch (IOException ex) {                throw new RuntimeException("Error when trying to obtain the request's InputStream.", ex);            }        }    }}

Again, this above is pseudo-code... well, not so pseudo, it does work but I've left out my own business logic where I extract the measured body length and use it for other stuff.
If you remove the isFormRequest boolean in order to treat x-www-form-urlencoded POST/PUT requests like the others, you will see that the request length won't be logged, with these.

Thank you for any help.


Viewing all articles
Browse latest Browse all 675

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>