Search in sources :

Example 1 with FilterInputStream

use of java.io.FilterInputStream in project jetty.project by eclipse.

the class MultiPartInputStreamParser method parse.

/**
     * Parse, if necessary, the multipart stream.
     *
     */
protected void parse() {
    //have we already parsed the input?
    if (_parts != null || _err != null)
        return;
    //initialize
    //keep running total of size of bytes read from input and throw an exception if exceeds MultipartConfigElement._maxRequestSize
    long total = 0;
    _parts = new MultiMap<>();
    //if its not a multipart request, don't parse it
    if (_contentType == null || !_contentType.startsWith("multipart/form-data"))
        return;
    try {
        if (_config.getLocation() == null)
            _tmpDir = _contextTmpDir;
        else if ("".equals(_config.getLocation()))
            _tmpDir = _contextTmpDir;
        else {
            File f = new File(_config.getLocation());
            if (f.isAbsolute())
                _tmpDir = f;
            else
                _tmpDir = new File(_contextTmpDir, _config.getLocation());
        }
        if (!_tmpDir.exists())
            _tmpDir.mkdirs();
        String contentTypeBoundary = "";
        int bstart = _contentType.indexOf("boundary=");
        if (bstart >= 0) {
            int bend = _contentType.indexOf(";", bstart);
            bend = (bend < 0 ? _contentType.length() : bend);
            contentTypeBoundary = QuotedStringTokenizer.unquote(value(_contentType.substring(bstart, bend)).trim());
        }
        String boundary = "--" + contentTypeBoundary;
        String lastBoundary = boundary + "--";
        byte[] byteBoundary = lastBoundary.getBytes(StandardCharsets.ISO_8859_1);
        // Get first boundary
        String line = null;
        try {
            line = ((ReadLineInputStream) _in).readLine();
        } catch (IOException e) {
            LOG.warn("Badly formatted multipart request");
            throw e;
        }
        if (line == null)
            throw new IOException("Missing content for multipart request");
        boolean badFormatLogged = false;
        line = line.trim();
        while (line != null && !line.equals(boundary) && !line.equals(lastBoundary)) {
            if (!badFormatLogged) {
                LOG.warn("Badly formatted multipart request");
                badFormatLogged = true;
            }
            line = ((ReadLineInputStream) _in).readLine();
            line = (line == null ? line : line.trim());
        }
        if (line == null || line.length() == 0)
            throw new IOException("Missing initial multi part boundary");
        // Empty multipart.
        if (line.equals(lastBoundary))
            return;
        // Read each part
        boolean lastPart = false;
        outer: while (!lastPart) {
            String contentDisposition = null;
            String contentType = null;
            String contentTransferEncoding = null;
            MultiMap<String> headers = new MultiMap<>();
            while (true) {
                line = ((ReadLineInputStream) _in).readLine();
                //No more input
                if (line == null)
                    break outer;
                //end of headers:
                if ("".equals(line))
                    break;
                total += line.length();
                if (_config.getMaxRequestSize() > 0 && total > _config.getMaxRequestSize())
                    throw new IllegalStateException("Request exceeds maxRequestSize (" + _config.getMaxRequestSize() + ")");
                //get content-disposition and content-type
                int c = line.indexOf(':', 0);
                if (c > 0) {
                    String key = line.substring(0, c).trim().toLowerCase(Locale.ENGLISH);
                    String value = line.substring(c + 1, line.length()).trim();
                    headers.put(key, value);
                    if (key.equalsIgnoreCase("content-disposition"))
                        contentDisposition = value;
                    if (key.equalsIgnoreCase("content-type"))
                        contentType = value;
                    if (key.equals("content-transfer-encoding"))
                        contentTransferEncoding = value;
                }
            }
            // Extract content-disposition
            boolean form_data = false;
            if (contentDisposition == null) {
                throw new IOException("Missing content-disposition");
            }
            QuotedStringTokenizer tok = new QuotedStringTokenizer(contentDisposition, ";", false, true);
            String name = null;
            String filename = null;
            while (tok.hasMoreTokens()) {
                String t = tok.nextToken().trim();
                String tl = t.toLowerCase(Locale.ENGLISH);
                if (t.startsWith("form-data"))
                    form_data = true;
                else if (tl.startsWith("name="))
                    name = value(t);
                else if (tl.startsWith("filename="))
                    filename = filenameValue(t);
            }
            // Check disposition
            if (!form_data) {
                continue;
            }
            //have not yet seen a name field.
            if (name == null) {
                continue;
            }
            //Have a new Part
            MultiPart part = new MultiPart(name, filename);
            part.setHeaders(headers);
            part.setContentType(contentType);
            _parts.add(name, part);
            part.open();
            InputStream partInput = null;
            if ("base64".equalsIgnoreCase(contentTransferEncoding)) {
                partInput = new Base64InputStream((ReadLineInputStream) _in);
            } else if ("quoted-printable".equalsIgnoreCase(contentTransferEncoding)) {
                partInput = new FilterInputStream(_in) {

                    @Override
                    public int read() throws IOException {
                        int c = in.read();
                        if (c >= 0 && c == '=') {
                            int hi = in.read();
                            int lo = in.read();
                            if (hi < 0 || lo < 0) {
                                throw new IOException("Unexpected end to quoted-printable byte");
                            }
                            char[] chars = new char[] { (char) hi, (char) lo };
                            c = Integer.parseInt(new String(chars), 16);
                        }
                        return c;
                    }
                };
            } else
                partInput = _in;
            try {
                int state = -2;
                int c;
                boolean cr = false;
                boolean lf = false;
                // loop for all lines
                while (true) {
                    int b = 0;
                    while ((c = (state != -2) ? state : partInput.read()) != -1) {
                        total++;
                        if (_config.getMaxRequestSize() > 0 && total > _config.getMaxRequestSize())
                            throw new IllegalStateException("Request exceeds maxRequestSize (" + _config.getMaxRequestSize() + ")");
                        state = -2;
                        // look for CR and/or LF
                        if (c == 13 || c == 10) {
                            if (c == 13) {
                                partInput.mark(1);
                                int tmp = partInput.read();
                                if (tmp != 10)
                                    partInput.reset();
                                else
                                    state = tmp;
                            }
                            break;
                        }
                        // Look for boundary
                        if (b >= 0 && b < byteBoundary.length && c == byteBoundary[b]) {
                            b++;
                        } else {
                            // Write out as many chars as we matched, then the char we're looking at.
                            if (cr)
                                part.write(13);
                            if (lf)
                                part.write(10);
                            cr = lf = false;
                            if (b > 0)
                                part.write(byteBoundary, 0, b);
                            b = -1;
                            part.write(c);
                        }
                    }
                    // Check for incomplete boundary match, writing out the chars we matched along the way
                    if ((b > 0 && b < byteBoundary.length - 2) || (b == byteBoundary.length - 1)) {
                        if (cr)
                            part.write(13);
                        if (lf)
                            part.write(10);
                        cr = lf = false;
                        part.write(byteBoundary, 0, b);
                        b = -1;
                    }
                    // Boundary match. If we've run out of input or we matched the entire final boundary marker, then this is the last part.
                    if (b > 0 || c == -1) {
                        if (b == byteBoundary.length)
                            lastPart = true;
                        if (state == 10)
                            state = -2;
                        break;
                    }
                    // handle CR LF
                    if (cr)
                        part.write(13);
                    if (lf)
                        part.write(10);
                    cr = (c == 13);
                    lf = (c == 10 || state == 10);
                    if (state == 10)
                        state = -2;
                }
            } finally {
                part.close();
            }
        }
        if (lastPart) {
            while (line != null) line = ((ReadLineInputStream) _in).readLine();
        } else
            throw new IOException("Incomplete parts");
    } catch (Exception e) {
        _err = e;
    }
}
Also used : FilterInputStream(java.io.FilterInputStream) BufferedInputStream(java.io.BufferedInputStream) ServletInputStream(javax.servlet.ServletInputStream) FilterInputStream(java.io.FilterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) IOException(java.io.IOException) File(java.io.File)

Example 2 with FilterInputStream

use of java.io.FilterInputStream in project jetty.project by eclipse.

the class HttpOutputTest method testSendInputStreamBigChunked.

@Test
public void testSendInputStreamBigChunked() throws Exception {
    Resource big = Resource.newClassPathResource("simple/big.txt");
    _handler._contentInputStream = new FilterInputStream(big.getInputStream()) {

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            int filled = super.read(b, off, len > 2000 ? 2000 : len);
            return filled;
        }
    };
    LocalEndPoint endp = _connector.executeRequest("GET / HTTP/1.1\nHost: localhost:80\n\n" + "GET / HTTP/1.1\nHost: localhost:80\nConnection: close\n\n");
    String response = endp.getResponse();
    assertThat(response, containsString("HTTP/1.1 200 OK"));
    assertThat(response, containsString("Transfer-Encoding: chunked"));
    assertThat(response, containsString("1\tThis is a big file"));
    assertThat(response, containsString("400\tThis is a big file"));
    assertThat(response, containsString("\r\n0\r\n"));
    response = endp.getResponse();
    assertThat(response, containsString("HTTP/1.1 200 OK"));
    assertThat(response, containsString("Connection: close"));
}
Also used : FilterInputStream(java.io.FilterInputStream) Resource(org.eclipse.jetty.util.resource.Resource) IOException(java.io.IOException) Matchers.containsString(org.hamcrest.Matchers.containsString) LocalEndPoint(org.eclipse.jetty.server.LocalConnector.LocalEndPoint) LocalEndPoint(org.eclipse.jetty.server.LocalConnector.LocalEndPoint) Test(org.junit.Test)

Example 3 with FilterInputStream

use of java.io.FilterInputStream in project javaee7-samples by javaee-samples.

the class MyClientReaderInterceptor method aroundReadFrom.

@Override
public Object aroundReadFrom(ReaderInterceptorContext ric) throws IOException, WebApplicationException {
    System.out.println("MyClientReaderInterceptor");
    //        ric.setInputStream(new FilterInputStream(ric.getInputStream()) {
    //
    //            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    //
    //            @Override
    //            public int read(byte[] b, int off, int len) throws IOException {
    //                baos.write(b, off, len);
    ////                System.out.println("@@@@@@ " + b);
    //                return super.read(b, off, len);
    //            }
    //
    //            @Override
    //            public void close() throws IOException {
    //                System.out.println("### " + baos.toString());
    //                super.close();
    //            }
    //        });
    final InputStream old = ric.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int c;
    while ((c = old.read()) != -1) {
        baos.write(c);
    }
    System.out.println("MyClientReaderInterceptor --> " + baos.toString());
    ric.setInputStream(new ByteArrayInputStream(baos.toByteArray()));
    return ric.proceed();
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) FilterInputStream(java.io.FilterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 4 with FilterInputStream

use of java.io.FilterInputStream in project jersey by jersey.

the class ApacheConnector method getInputStream.

private static InputStream getInputStream(final CloseableHttpResponse response) throws IOException {
    final InputStream inputStream;
    if (response.getEntity() == null) {
        inputStream = new ByteArrayInputStream(new byte[0]);
    } else {
        final InputStream i = response.getEntity().getContent();
        if (i.markSupported()) {
            inputStream = i;
        } else {
            inputStream = new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
        }
    }
    return new FilterInputStream(inputStream) {

        @Override
        public void close() throws IOException {
            response.close();
            super.close();
        }
    };
}
Also used : FilterInputStream(java.io.FilterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FilterInputStream(java.io.FilterInputStream) InputStream(java.io.InputStream)

Example 5 with FilterInputStream

use of java.io.FilterInputStream in project zaproxy by zaproxy.

the class ProxyThread method decodeResponseIfNeeded.

private void decodeResponseIfNeeded(HttpMessage msg) {
    String encoding = msg.getResponseHeader().getHeader(HttpHeader.CONTENT_ENCODING);
    if (proxyParam.isAlwaysDecodeGzip() && encoding != null && !encoding.equalsIgnoreCase(HttpHeader.IDENTITY)) {
        encoding = Pattern.compile("^x-", Pattern.CASE_INSENSITIVE).matcher(encoding).replaceAll("");
        if (!encoding.equalsIgnoreCase(HttpHeader.DEFLATE) && !encoding.equalsIgnoreCase(HttpHeader.GZIP)) {
            log.warn("Unsupported content encoding method: " + encoding);
            return;
        }
        // Uncompress content
        try (ByteArrayInputStream bais = new ByteArrayInputStream(msg.getResponseBody().getBytes());
            FilterInputStream fis = buildStreamDecoder(encoding, bais);
            BufferedInputStream bis = new BufferedInputStream(fis);
            ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            int readLength;
            byte[] readBuffer = new byte[1024];
            while ((readLength = bis.read(readBuffer, 0, 1024)) != -1) {
                out.write(readBuffer, 0, readLength);
            }
            msg.setResponseBody(out.toByteArray());
            msg.getResponseHeader().setHeader(HttpHeader.CONTENT_ENCODING, null);
            if (msg.getResponseHeader().getHeader(HttpHeader.CONTENT_LENGTH) != null) {
                msg.getResponseHeader().setHeader(HttpHeader.CONTENT_LENGTH, Integer.toString(out.size()));
            }
        } catch (IOException e) {
            log.error("Unable to uncompress gzip content: " + e.getMessage(), e);
        }
    }
}
Also used : FilterInputStream(java.io.FilterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Aggregations

FilterInputStream (java.io.FilterInputStream)26 IOException (java.io.IOException)13 ByteArrayInputStream (java.io.ByteArrayInputStream)8 InputStream (java.io.InputStream)8 BufferedInputStream (java.io.BufferedInputStream)5 File (java.io.File)5 FileInputStream (java.io.FileInputStream)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 FileOutputStream (java.io.FileOutputStream)4 URL (java.net.URL)4 ZipEntry (java.util.zip.ZipEntry)4 BufferedOutputStream (java.io.BufferedOutputStream)2 DataInputStream (java.io.DataInputStream)2 OutputStream (java.io.OutputStream)2 HttpURLConnection (java.net.HttpURLConnection)2 Random (java.util.Random)2 JarFile (java.util.jar.JarFile)2 JarInputStream (java.util.jar.JarInputStream)2 GZIPInputStream (java.util.zip.GZIPInputStream)2 ZipInputStream (java.util.zip.ZipInputStream)2