Search in sources :

Example 1 with Parameters

use of org.apache.tomcat.util.http.Parameters in project tomcat70 by apache.

the class ApplicationHttpRequest method mergeParameters.

// ------------------------------------------------------ Private Methods
/**
 * Merge the parameters from the saved query parameter string (if any), and
 * the parameters already present on this request (if any), such that the
 * parameter values from the query string show up first if there are
 * duplicate parameter names.
 */
private void mergeParameters() {
    if ((queryParamString == null) || (queryParamString.length() < 1))
        return;
    // Parse the query string from the dispatch target
    Parameters paramParser = new Parameters();
    MessageBytes queryMB = MessageBytes.newInstance();
    queryMB.setString(queryParamString);
    String encoding = getCharacterEncoding();
    // in MessageBytes.toBytes().
    if (encoding != null) {
        try {
            queryMB.setCharset(B2CConverter.getCharset(encoding));
        } catch (UnsupportedEncodingException ignored) {
        // Fall-back to ISO-8859-1
        }
    }
    paramParser.setQuery(queryMB);
    paramParser.setQueryStringEncoding(encoding);
    paramParser.handleQueryParameters();
    // Insert the additional parameters from the dispatch target
    Enumeration<String> dispParamNames = paramParser.getParameterNames();
    while (dispParamNames.hasMoreElements()) {
        String dispParamName = dispParamNames.nextElement();
        String[] dispParamValues = paramParser.getParameterValues(dispParamName);
        String[] originalValues = parameters.get(dispParamName);
        if (originalValues == null) {
            parameters.put(dispParamName, dispParamValues);
            continue;
        }
        parameters.put(dispParamName, mergeValues(dispParamValues, originalValues));
    }
}
Also used : Parameters(org.apache.tomcat.util.http.Parameters) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 2 with Parameters

use of org.apache.tomcat.util.http.Parameters in project tomcat by apache.

the class Request method parseParameters.

/**
 * Parse request parameters.
 */
protected void parseParameters() {
    parametersParsed = true;
    Parameters parameters = coyoteRequest.getParameters();
    boolean success = false;
    try {
        // Set this every time in case limit has been changed via JMX
        parameters.setLimit(getConnector().getMaxParameterCount());
        // getCharacterEncoding() may have been overridden to search for
        // hidden form field containing request encoding
        Charset charset = getCharset();
        boolean useBodyEncodingForURI = connector.getUseBodyEncodingForURI();
        parameters.setCharset(charset);
        if (useBodyEncodingForURI) {
            parameters.setQueryStringCharset(charset);
        }
        // Note: If !useBodyEncodingForURI, the query string encoding is
        // that set towards the start of CoyoyeAdapter.service()
        parameters.handleQueryParameters();
        if (usingInputStream || usingReader) {
            success = true;
            return;
        }
        String contentType = getContentType();
        if (contentType == null) {
            contentType = "";
        }
        int semicolon = contentType.indexOf(';');
        if (semicolon >= 0) {
            contentType = contentType.substring(0, semicolon).trim();
        } else {
            contentType = contentType.trim();
        }
        if ("multipart/form-data".equals(contentType)) {
            parseParts(false);
            success = true;
            return;
        }
        if (!getConnector().isParseBodyMethod(getMethod())) {
            success = true;
            return;
        }
        if (!("application/x-www-form-urlencoded".equals(contentType))) {
            success = true;
            return;
        }
        int len = getContentLength();
        if (len > 0) {
            int maxPostSize = connector.getMaxPostSize();
            if ((maxPostSize >= 0) && (len > maxPostSize)) {
                Context context = getContext();
                if (context != null && context.getLogger().isDebugEnabled()) {
                    context.getLogger().debug(sm.getString("coyoteRequest.postTooLarge"));
                }
                checkSwallowInput();
                parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
                return;
            }
            byte[] formData = null;
            if (len < CACHED_POST_LEN) {
                if (postData == null) {
                    postData = new byte[CACHED_POST_LEN];
                }
                formData = postData;
            } else {
                formData = new byte[len];
            }
            try {
                if (readPostBody(formData, len) != len) {
                    parameters.setParseFailedReason(FailReason.REQUEST_BODY_INCOMPLETE);
                    return;
                }
            } catch (IOException e) {
                // Client disconnect
                Context context = getContext();
                if (context != null && context.getLogger().isDebugEnabled()) {
                    context.getLogger().debug(sm.getString("coyoteRequest.parseParameters"), e);
                }
                parameters.setParseFailedReason(FailReason.CLIENT_DISCONNECT);
                return;
            }
            parameters.processParameters(formData, 0, len);
        } else if ("chunked".equalsIgnoreCase(coyoteRequest.getHeader("transfer-encoding"))) {
            byte[] formData = null;
            try {
                formData = readChunkedPostBody();
            } catch (IllegalStateException ise) {
                // chunkedPostTooLarge error
                parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
                Context context = getContext();
                if (context != null && context.getLogger().isDebugEnabled()) {
                    context.getLogger().debug(sm.getString("coyoteRequest.parseParameters"), ise);
                }
                return;
            } catch (IOException e) {
                // Client disconnect
                parameters.setParseFailedReason(FailReason.CLIENT_DISCONNECT);
                Context context = getContext();
                if (context != null && context.getLogger().isDebugEnabled()) {
                    context.getLogger().debug(sm.getString("coyoteRequest.parseParameters"), e);
                }
                return;
            }
            if (formData != null) {
                parameters.processParameters(formData, 0, formData.length);
            }
        }
        success = true;
    } finally {
        if (!success) {
            parameters.setParseFailedReason(FailReason.UNKNOWN);
        }
    }
}
Also used : ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) ServletContext(jakarta.servlet.ServletContext) AsyncContext(jakarta.servlet.AsyncContext) Context(org.apache.catalina.Context) Parameters(org.apache.tomcat.util.http.Parameters) Charset(java.nio.charset.Charset) IOException(java.io.IOException)

Example 3 with Parameters

use of org.apache.tomcat.util.http.Parameters in project tomcat70 by apache.

the class Request method parseParts.

private void parseParts() {
    // Return immediately if the parts have already been parsed
    if (parts != null || partsParseException != null) {
        return;
    }
    MultipartConfigElement mce = getWrapper().getMultipartConfigElement();
    if (mce == null) {
        if (getContext().getAllowCasualMultipartParsing()) {
            mce = new MultipartConfigElement(null, connector.getMaxPostSize(), connector.getMaxPostSize(), connector.getMaxPostSize());
        } else {
            parts = Collections.emptyList();
            return;
        }
    }
    Parameters parameters = coyoteRequest.getParameters();
    parameters.setLimit(getConnector().getMaxParameterCount());
    boolean success = false;
    try {
        File location;
        String locationStr = mce.getLocation();
        if (locationStr == null || locationStr.length() == 0) {
            location = ((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR));
        } else {
            // If relative, it is relative to TEMPDIR
            location = new File(locationStr);
            if (!location.isAbsolute()) {
                location = new File((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR), locationStr).getAbsoluteFile();
            }
        }
        if (!location.isDirectory()) {
            parameters.setParseFailedReason(FailReason.MULTIPART_CONFIG_INVALID);
            partsParseException = new IOException(sm.getString("coyoteRequest.uploadLocationInvalid", location));
            return;
        }
        // Create a new file upload handler
        DiskFileItemFactory factory = new DiskFileItemFactory();
        try {
            factory.setRepository(location.getCanonicalFile());
        } catch (IOException ioe) {
            parameters.setParseFailedReason(FailReason.IO_ERROR);
            partsParseException = ioe;
            return;
        }
        factory.setSizeThreshold(mce.getFileSizeThreshold());
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(factory);
        upload.setFileSizeMax(mce.getMaxFileSize());
        upload.setSizeMax(mce.getMaxRequestSize());
        parts = new ArrayList<Part>();
        try {
            List<FileItem> items = upload.parseRequest(new ServletRequestContext(this));
            int maxPostSize = getConnector().getMaxPostSize();
            int postSize = 0;
            String enc = getCharacterEncoding();
            Charset charset = null;
            if (enc != null) {
                try {
                    charset = B2CConverter.getCharset(enc);
                } catch (UnsupportedEncodingException e) {
                // Ignore
                }
            }
            for (FileItem item : items) {
                ApplicationPart part = new ApplicationPart(item, location);
                parts.add(part);
                if (part.getSubmittedFileName() == null) {
                    String name = part.getName();
                    String value = null;
                    try {
                        String encoding = parameters.getEncoding();
                        if (encoding == null) {
                            if (enc == null) {
                                encoding = Parameters.DEFAULT_ENCODING;
                            } else {
                                encoding = enc;
                            }
                        }
                        value = part.getString(encoding);
                    } catch (UnsupportedEncodingException uee) {
                        try {
                            value = part.getString(Parameters.DEFAULT_ENCODING);
                        } catch (UnsupportedEncodingException e) {
                        // Should not be possible
                        }
                    }
                    if (maxPostSize >= 0) {
                        // accurate but close enough.
                        if (charset == null) {
                            // Name length
                            postSize += name.getBytes().length;
                        } else {
                            postSize += name.getBytes(charset).length;
                        }
                        if (value != null) {
                            // Equals sign
                            postSize++;
                            // Value length
                            postSize += part.getSize();
                        }
                        // Value separator
                        postSize++;
                        if (postSize > maxPostSize) {
                            parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
                            throw new IllegalStateException(sm.getString("coyoteRequest.maxPostSizeExceeded"));
                        }
                    }
                    parameters.addParameter(name, value);
                }
            }
            success = true;
        } catch (InvalidContentTypeException e) {
            parameters.setParseFailedReason(FailReason.INVALID_CONTENT_TYPE);
            partsParseException = new ServletException(e);
        } catch (FileUploadBase.SizeException e) {
            parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
            checkSwallowInput();
            partsParseException = new IllegalStateException(e);
        } catch (FileUploadException e) {
            parameters.setParseFailedReason(FailReason.IO_ERROR);
            partsParseException = new IOException(e);
        } catch (IllegalStateException e) {
            // addParameters() will set parseFailedReason
            checkSwallowInput();
            partsParseException = e;
        }
    } finally {
        if (partsParseException != null || !success) {
            parameters.setParseFailedReason(FailReason.UNKNOWN);
        }
    }
}
Also used : Parameters(org.apache.tomcat.util.http.Parameters) InvalidContentTypeException(org.apache.tomcat.util.http.fileupload.FileUploadBase.InvalidContentTypeException) ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) DiskFileItemFactory(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) FileItem(org.apache.tomcat.util.http.fileupload.FileItem) MultipartConfigElement(javax.servlet.MultipartConfigElement) ServletFileUpload(org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload) FileUploadBase(org.apache.tomcat.util.http.fileupload.FileUploadBase) Part(javax.servlet.http.Part) ApplicationPart(org.apache.catalina.core.ApplicationPart) ApplicationPart(org.apache.catalina.core.ApplicationPart) File(java.io.File) FileUploadException(org.apache.tomcat.util.http.fileupload.FileUploadException)

Example 4 with Parameters

use of org.apache.tomcat.util.http.Parameters in project tomcat70 by apache.

the class Request method parseParameters.

/**
 * Parse request parameters.
 */
protected void parseParameters() {
    parametersParsed = true;
    Parameters parameters = coyoteRequest.getParameters();
    boolean success = false;
    try {
        // Set this every time in case limit has been changed via JMX
        parameters.setLimit(getConnector().getMaxParameterCount());
        // getCharacterEncoding() may have been overridden to search for
        // hidden form field containing request encoding
        String enc = getCharacterEncoding();
        boolean useBodyEncodingForURI = connector.getUseBodyEncodingForURI();
        if (enc != null) {
            parameters.setEncoding(enc);
            if (useBodyEncodingForURI) {
                parameters.setQueryStringEncoding(enc);
            }
        } else {
            parameters.setEncoding(org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING);
            if (useBodyEncodingForURI) {
                parameters.setQueryStringEncoding(org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING);
            }
        }
        parameters.handleQueryParameters();
        if (usingInputStream || usingReader) {
            success = true;
            return;
        }
        if (!getConnector().isParseBodyMethod(getMethod())) {
            success = true;
            return;
        }
        String contentType = getContentType();
        if (contentType == null) {
            contentType = "";
        }
        int semicolon = contentType.indexOf(';');
        if (semicolon >= 0) {
            contentType = contentType.substring(0, semicolon).trim();
        } else {
            contentType = contentType.trim();
        }
        if ("multipart/form-data".equals(contentType)) {
            parseParts();
            success = true;
            return;
        }
        if (!("application/x-www-form-urlencoded".equals(contentType))) {
            success = true;
            return;
        }
        int len = getContentLength();
        if (len > 0) {
            int maxPostSize = connector.getMaxPostSize();
            if ((maxPostSize >= 0) && (len > maxPostSize)) {
                if (context.getLogger().isDebugEnabled()) {
                    context.getLogger().debug(sm.getString("coyoteRequest.postTooLarge"));
                }
                checkSwallowInput();
                parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
                return;
            }
            byte[] formData = null;
            if (len < CACHED_POST_LEN) {
                if (postData == null) {
                    postData = new byte[CACHED_POST_LEN];
                }
                formData = postData;
            } else {
                formData = new byte[len];
            }
            try {
                if (readPostBody(formData, len) != len) {
                    parameters.setParseFailedReason(FailReason.REQUEST_BODY_INCOMPLETE);
                    return;
                }
            } catch (IOException e) {
                // Client disconnect
                if (context.getLogger().isDebugEnabled()) {
                    context.getLogger().debug(sm.getString("coyoteRequest.parseParameters"), e);
                }
                parameters.setParseFailedReason(FailReason.CLIENT_DISCONNECT);
                return;
            }
            parameters.processParameters(formData, 0, len);
        } else if ("chunked".equalsIgnoreCase(coyoteRequest.getHeader("transfer-encoding"))) {
            byte[] formData = null;
            try {
                formData = readChunkedPostBody();
            } catch (IllegalStateException ise) {
                // chunkedPostTooLarge error
                parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
                Context context = getContext();
                if (context != null && context.getLogger().isDebugEnabled()) {
                    context.getLogger().debug(sm.getString("coyoteRequest.parseParameters"), ise);
                }
                return;
            } catch (IOException e) {
                // Client disconnect
                parameters.setParseFailedReason(FailReason.CLIENT_DISCONNECT);
                Context context = getContext();
                if (context != null && context.getLogger().isDebugEnabled()) {
                    context.getLogger().debug(sm.getString("coyoteRequest.parseParameters"), e);
                }
                return;
            }
            if (formData != null) {
                parameters.processParameters(formData, 0, formData.length);
            }
        }
        success = true;
    } finally {
        if (!success) {
            parameters.setParseFailedReason(FailReason.UNKNOWN);
        }
    }
}
Also used : ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) ServletContext(javax.servlet.ServletContext) Parameters(org.apache.tomcat.util.http.Parameters) IOException(java.io.IOException)

Example 5 with Parameters

use of org.apache.tomcat.util.http.Parameters in project tomcat by apache.

the class Request method parseParts.

private void parseParts(boolean explicit) {
    // Return immediately if the parts have already been parsed
    if (parts != null || partsParseException != null) {
        return;
    }
    Context context = getContext();
    MultipartConfigElement mce = getWrapper().getMultipartConfigElement();
    if (mce == null) {
        if (context.getAllowCasualMultipartParsing()) {
            mce = new MultipartConfigElement(null, connector.getMaxPostSize(), connector.getMaxPostSize(), connector.getMaxPostSize());
        } else {
            if (explicit) {
                partsParseException = new IllegalStateException(sm.getString("coyoteRequest.noMultipartConfig"));
                return;
            } else {
                parts = Collections.emptyList();
                return;
            }
        }
    }
    Parameters parameters = coyoteRequest.getParameters();
    parameters.setLimit(getConnector().getMaxParameterCount());
    boolean success = false;
    try {
        File location;
        String locationStr = mce.getLocation();
        if (locationStr == null || locationStr.length() == 0) {
            location = ((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR));
        } else {
            // If relative, it is relative to TEMPDIR
            location = new File(locationStr);
            if (!location.isAbsolute()) {
                location = new File((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR), locationStr).getAbsoluteFile();
            }
        }
        if (!location.exists() && context.getCreateUploadTargets()) {
            log.warn(sm.getString("coyoteRequest.uploadCreate", location.getAbsolutePath(), getMappingData().wrapper.getName()));
            if (!location.mkdirs()) {
                log.warn(sm.getString("coyoteRequest.uploadCreateFail", location.getAbsolutePath()));
            }
        }
        if (!location.isDirectory()) {
            parameters.setParseFailedReason(FailReason.MULTIPART_CONFIG_INVALID);
            partsParseException = new IOException(sm.getString("coyoteRequest.uploadLocationInvalid", location));
            return;
        }
        // Create a new file upload handler
        DiskFileItemFactory factory = new DiskFileItemFactory();
        try {
            factory.setRepository(location.getCanonicalFile());
        } catch (IOException ioe) {
            parameters.setParseFailedReason(FailReason.IO_ERROR);
            partsParseException = ioe;
            return;
        }
        factory.setSizeThreshold(mce.getFileSizeThreshold());
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(factory);
        upload.setFileSizeMax(mce.getMaxFileSize());
        upload.setSizeMax(mce.getMaxRequestSize());
        parts = new ArrayList<>();
        try {
            List<FileItem> items = upload.parseRequest(new ServletRequestContext(this));
            int maxPostSize = getConnector().getMaxPostSize();
            int postSize = 0;
            Charset charset = getCharset();
            for (FileItem item : items) {
                ApplicationPart part = new ApplicationPart(item, location);
                parts.add(part);
                if (part.getSubmittedFileName() == null) {
                    String name = part.getName();
                    if (maxPostSize >= 0) {
                        // Have to calculate equivalent size. Not completely
                        // accurate but close enough.
                        postSize += name.getBytes(charset).length;
                        // Equals sign
                        postSize++;
                        // Value length
                        postSize += part.getSize();
                        // Value separator
                        postSize++;
                        if (postSize > maxPostSize) {
                            parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
                            throw new IllegalStateException(sm.getString("coyoteRequest.maxPostSizeExceeded"));
                        }
                    }
                    String value = null;
                    try {
                        value = part.getString(charset.name());
                    } catch (UnsupportedEncodingException uee) {
                    // Not possible
                    }
                    parameters.addParameter(name, value);
                }
            }
            success = true;
        } catch (InvalidContentTypeException e) {
            parameters.setParseFailedReason(FailReason.INVALID_CONTENT_TYPE);
            partsParseException = new ServletException(e);
        } catch (SizeException e) {
            parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
            checkSwallowInput();
            partsParseException = new IllegalStateException(e);
        } catch (IOException e) {
            parameters.setParseFailedReason(FailReason.IO_ERROR);
            partsParseException = new IOException(e);
        } catch (IllegalStateException e) {
            // addParameters() will set parseFailedReason
            checkSwallowInput();
            partsParseException = e;
        }
    } finally {
        // respect to changes in the remainder of the method.
        if (partsParseException != null || !success) {
            parameters.setParseFailedReason(FailReason.UNKNOWN);
        }
    }
}
Also used : ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) ServletContext(jakarta.servlet.ServletContext) AsyncContext(jakarta.servlet.AsyncContext) Context(org.apache.catalina.Context) Parameters(org.apache.tomcat.util.http.Parameters) InvalidContentTypeException(org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException) ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) DiskFileItemFactory(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory) ServletException(jakarta.servlet.ServletException) FileItem(org.apache.tomcat.util.http.fileupload.FileItem) MultipartConfigElement(jakarta.servlet.MultipartConfigElement) ServletFileUpload(org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload) ApplicationPart(org.apache.catalina.core.ApplicationPart) File(java.io.File) SizeException(org.apache.tomcat.util.http.fileupload.impl.SizeException)

Aggregations

Parameters (org.apache.tomcat.util.http.Parameters)6 IOException (java.io.IOException)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 Charset (java.nio.charset.Charset)4 ServletRequestContext (org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext)4 Context (org.apache.catalina.Context)3 AsyncContext (jakarta.servlet.AsyncContext)2 ServletContext (jakarta.servlet.ServletContext)2 File (java.io.File)2 ApplicationPart (org.apache.catalina.core.ApplicationPart)2 MessageBytes (org.apache.tomcat.util.buf.MessageBytes)2 FileItem (org.apache.tomcat.util.http.fileupload.FileItem)2 DiskFileItemFactory (org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory)2 ServletFileUpload (org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload)2 MultipartConfigElement (jakarta.servlet.MultipartConfigElement)1 ServletException (jakarta.servlet.ServletException)1 AsyncContext (javax.servlet.AsyncContext)1 MultipartConfigElement (javax.servlet.MultipartConfigElement)1 ServletContext (javax.servlet.ServletContext)1 ServletException (javax.servlet.ServletException)1