2 // ========================================================================
3 // Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
19 package org.eclipse.jetty.util;
21 import java.io.BufferedInputStream;
22 import java.io.BufferedOutputStream;
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.FilterInputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.OutputStream;
32 import java.nio.charset.StandardCharsets;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.List;
37 import java.util.Locale;
39 import javax.servlet.MultipartConfigElement;
40 import javax.servlet.ServletException;
41 import javax.servlet.http.Part;
43 import org.eclipse.jetty.util.log.Log;
44 import org.eclipse.jetty.util.log.Logger;
49 * MultiPartInputStream
51 * Handle a MultiPart Mime input stream, breaking it up on the boundary into files and strings.
53 public class MultiPartInputStreamParser
55 private static final Logger LOG = Log.getLogger(MultiPartInputStreamParser.class);
56 public static final MultipartConfigElement __DEFAULT_MULTIPART_CONFIG = new MultipartConfigElement(System.getProperty("java.io.tmpdir"));
57 protected InputStream _in;
58 protected MultipartConfigElement _config;
59 protected String _contentType;
60 protected MultiMap<Part> _parts;
61 protected File _tmpDir;
62 protected File _contextTmpDir;
63 protected boolean _deleteOnExit;
67 public class MultiPart implements Part
69 protected String _name;
70 protected String _filename;
72 protected OutputStream _out;
73 protected ByteArrayOutputStream2 _bout;
74 protected String _contentType;
75 protected MultiMap<String> _headers;
76 protected long _size = 0;
77 protected boolean _temporary = true;
79 public MultiPart (String name, String filename)
86 protected void setContentType (String contentType)
88 _contentType = contentType;
95 //Write to a buffer in memory until we discover we've exceed the
96 //MultipartConfig fileSizeThreshold
97 _out = _bout= new ByteArrayOutputStream2();
100 protected void close()
107 protected void write (int b)
110 if (MultiPartInputStreamParser.this._config.getMaxFileSize() > 0 && _size + 1 > MultiPartInputStreamParser.this._config.getMaxFileSize())
111 throw new IllegalStateException ("Multipart Mime part "+_name+" exceeds max filesize");
113 if (MultiPartInputStreamParser.this._config.getFileSizeThreshold() > 0 && _size + 1 > MultiPartInputStreamParser.this._config.getFileSizeThreshold() && _file==null)
120 protected void write (byte[] bytes, int offset, int length)
123 if (MultiPartInputStreamParser.this._config.getMaxFileSize() > 0 && _size + length > MultiPartInputStreamParser.this._config.getMaxFileSize())
124 throw new IllegalStateException ("Multipart Mime part "+_name+" exceeds max filesize");
126 if (MultiPartInputStreamParser.this._config.getFileSizeThreshold() > 0 && _size + length > MultiPartInputStreamParser.this._config.getFileSizeThreshold() && _file==null)
129 _out.write(bytes, offset, length);
133 protected void createFile ()
136 _file = File.createTempFile("MultiPart", "", MultiPartInputStreamParser.this._tmpDir);
139 _file.deleteOnExit();
140 FileOutputStream fos = new FileOutputStream(_file);
141 BufferedOutputStream bos = new BufferedOutputStream(fos);
143 if (_size > 0 && _out != null)
145 //already written some bytes, so need to copy them into the file
156 protected void setHeaders(MultiMap<String> headers)
162 * @see javax.servlet.http.Part#getContentType()
164 public String getContentType()
170 * @see javax.servlet.http.Part#getHeader(java.lang.String)
172 public String getHeader(String name)
176 return (String)_headers.getValue(name.toLowerCase(Locale.ENGLISH), 0);
180 * @see javax.servlet.http.Part#getHeaderNames()
182 public Collection<String> getHeaderNames()
184 return _headers.keySet();
188 * @see javax.servlet.http.Part#getHeaders(java.lang.String)
190 public Collection<String> getHeaders(String name)
192 return _headers.getValues(name);
196 * @see javax.servlet.http.Part#getInputStream()
198 public InputStream getInputStream() throws IOException
202 //written to a file, whether temporary or not
203 return new BufferedInputStream (new FileInputStream(_file));
207 //part content is in memory
208 return new ByteArrayInputStream(_bout.getBuf(),0,_bout.size());
214 * @see javax.servlet.http.Part#getSubmittedFileName()
217 public String getSubmittedFileName()
219 return getContentDispositionFilename();
222 public byte[] getBytes()
225 return _bout.toByteArray();
230 * @see javax.servlet.http.Part#getName()
232 public String getName()
238 * @see javax.servlet.http.Part#getSize()
240 public long getSize()
246 * @see javax.servlet.http.Part#write(java.lang.String)
248 public void write(String fileName) throws IOException
254 //part data is only in the ByteArrayOutputStream and never been written to disk
255 _file = new File (_tmpDir, fileName);
257 BufferedOutputStream bos = null;
260 bos = new BufferedOutputStream(new FileOutputStream(_file));
273 //the part data is already written to a temporary file, just rename it
276 File f = new File(_tmpDir, fileName);
277 if (_file.renameTo(f))
283 * Remove the file, whether or not Part.write() was called on it
284 * (ie no longer temporary)
285 * @see javax.servlet.http.Part#delete()
287 public void delete() throws IOException
289 if (_file != null && _file.exists())
294 * Only remove tmp files.
296 * @throws IOException
298 public void cleanUp() throws IOException
300 if (_temporary && _file != null && _file.exists())
306 * Get the file, if any, the data has been written to.
308 public File getFile ()
315 * Get the filename from the content-disposition.
316 * @return null or the filename
318 public String getContentDispositionFilename ()
328 * @param in Request input stream
329 * @param contentType Content-Type header
330 * @param config MultipartConfigElement
331 * @param contextTmpDir javax.servlet.context.tempdir
333 public MultiPartInputStreamParser (InputStream in, String contentType, MultipartConfigElement config, File contextTmpDir)
335 _in = new ReadLineInputStream(in);
336 _contentType = contentType;
338 _contextTmpDir = contextTmpDir;
339 if (_contextTmpDir == null)
340 _contextTmpDir = new File (System.getProperty("java.io.tmpdir"));
343 _config = new MultipartConfigElement(_contextTmpDir.getAbsolutePath());
347 * Get the already parsed parts.
349 public Collection<Part> getParsedParts()
352 return Collections.emptyList();
354 Collection<List<Part>> values = _parts.values();
355 List<Part> parts = new ArrayList<Part>();
356 for (List<Part> o: values)
358 List<Part> asList = LazyList.getList(o, false);
359 parts.addAll(asList);
365 * Delete any tmp storage for parts, and clear out the parts list.
367 * @throws MultiException
369 public void deleteParts ()
370 throws MultiException
372 Collection<Part> parts = getParsedParts();
373 MultiException err = new MultiException();
378 ((MultiPartInputStreamParser.MultiPart)p).cleanUp();
387 err.ifExceptionThrowMulti();
392 * Parse, if necessary, the multipart data and return the list of Parts.
394 * @throws IOException
395 * @throws ServletException
397 public Collection<Part> getParts()
398 throws IOException, ServletException
401 Collection<List<Part>> values = _parts.values();
402 List<Part> parts = new ArrayList<Part>();
403 for (List<Part> o: values)
405 List<Part> asList = LazyList.getList(o, false);
406 parts.addAll(asList);
413 * Get the named Part.
416 * @throws IOException
417 * @throws ServletException
419 public Part getPart(String name)
420 throws IOException, ServletException
423 return (Part)_parts.getValue(name, 0);
428 * Parse, if necessary, the multipart stream.
430 * @throws IOException
431 * @throws ServletException
433 protected void parse ()
434 throws IOException, ServletException
436 //have we already parsed the input?
441 long total = 0; //keep running total of size of bytes read from input and throw an exception if exceeds MultipartConfigElement._maxRequestSize
442 _parts = new MultiMap<Part>();
444 //if its not a multipart request, don't parse it
445 if (_contentType == null || !_contentType.startsWith("multipart/form-data"))
448 //sort out the location to which to write the files
450 if (_config.getLocation() == null)
451 _tmpDir = _contextTmpDir;
452 else if ("".equals(_config.getLocation()))
453 _tmpDir = _contextTmpDir;
456 File f = new File (_config.getLocation());
460 _tmpDir = new File (_contextTmpDir, _config.getLocation());
463 if (!_tmpDir.exists())
466 String contentTypeBoundary = "";
467 int bstart = _contentType.indexOf("boundary=");
470 int bend = _contentType.indexOf(";", bstart);
471 bend = (bend < 0? _contentType.length(): bend);
472 contentTypeBoundary = QuotedStringTokenizer.unquote(value(_contentType.substring(bstart,bend)).trim());
475 String boundary="--"+contentTypeBoundary;
476 byte[] byteBoundary=(boundary+"--").getBytes(StandardCharsets.ISO_8859_1);
478 // Get first boundary
482 line=((ReadLineInputStream)_in).readLine();
484 catch (IOException e)
486 LOG.warn("Badly formatted multipart request");
491 throw new IOException("Missing content for multipart request");
493 boolean badFormatLogged = false;
495 while (line != null && !line.equals(boundary))
497 if (!badFormatLogged)
499 LOG.warn("Badly formatted multipart request");
500 badFormatLogged = true;
502 line=((ReadLineInputStream)_in).readLine();
503 line=(line==null?line:line.trim());
507 throw new IOException("Missing initial multi part boundary");
510 boolean lastPart=false;
512 outer:while(!lastPart)
514 String contentDisposition=null;
515 String contentType=null;
516 String contentTransferEncoding=null;
518 MultiMap<String> headers = new MultiMap<String>();
521 line=((ReadLineInputStream)_in).readLine();
531 total += line.length();
532 if (_config.getMaxRequestSize() > 0 && total > _config.getMaxRequestSize())
533 throw new IllegalStateException ("Request exceeds maxRequestSize ("+_config.getMaxRequestSize()+")");
535 //get content-disposition and content-type
536 int c=line.indexOf(':',0);
539 String key=line.substring(0,c).trim().toLowerCase(Locale.ENGLISH);
540 String value=line.substring(c+1,line.length()).trim();
541 headers.put(key, value);
542 if (key.equalsIgnoreCase("content-disposition"))
543 contentDisposition=value;
544 if (key.equalsIgnoreCase("content-type"))
546 if(key.equals("content-transfer-encoding"))
547 contentTransferEncoding=value;
551 // Extract content-disposition
552 boolean form_data=false;
553 if(contentDisposition==null)
555 throw new IOException("Missing content-disposition");
558 QuotedStringTokenizer tok=new QuotedStringTokenizer(contentDisposition,";", false, true);
560 String filename=null;
561 while(tok.hasMoreTokens())
563 String t=tok.nextToken().trim();
564 String tl=t.toLowerCase(Locale.ENGLISH);
565 if(t.startsWith("form-data"))
567 else if(tl.startsWith("name="))
569 else if(tl.startsWith("filename="))
570 filename=filenameValue(t);
578 //It is valid for reset and submit buttons to have an empty name.
579 //If no name is supplied, the browser skips sending the info for that field.
580 //However, if you supply the empty string as the name, the browser sends the
581 //field, with name as the empty string. So, only continue this loop if we
582 //have not yet seen a name field.
589 MultiPart part = new MultiPart(name, filename);
590 part.setHeaders(headers);
591 part.setContentType(contentType);
592 _parts.add(name, part);
595 InputStream partInput = null;
596 if ("base64".equalsIgnoreCase(contentTransferEncoding))
598 partInput = new Base64InputStream((ReadLineInputStream)_in);
600 else if ("quoted-printable".equalsIgnoreCase(contentTransferEncoding))
602 partInput = new FilterInputStream(_in)
605 public int read() throws IOException
608 if (c >= 0 && c == '=')
612 if (hi < 0 || lo < 0)
614 throw new IOException("Unexpected end to quoted-printable byte");
616 char[] chars = new char[] { (char)hi, (char)lo };
617 c = Integer.parseInt(new String(chars),16);
634 // loop for all lines
638 while((c=(state!=-2)?state:partInput.read())!=-1)
641 if (_config.getMaxRequestSize() > 0 && total > _config.getMaxRequestSize())
642 throw new IllegalStateException("Request exceeds maxRequestSize ("+_config.getMaxRequestSize()+")");
646 // look for CR and/or LF
652 int tmp=partInput.read();
662 if(b>=0&&b<byteBoundary.length&&c==byteBoundary[b])
668 // Got a character not part of the boundary, so we don't have the boundary marker.
669 // Write out as many chars as we matched, then the char we're looking at.
678 part.write(byteBoundary,0,b);
685 // Check for incomplete boundary match, writing out the chars we matched along the way
686 if((b>0&&b<byteBoundary.length-2)||(b==byteBoundary.length-1))
695 part.write(byteBoundary,0,b);
699 // Boundary match. If we've run out of input or we matched the entire final boundary marker, then this is the last part.
703 if(b==byteBoundary.length)
718 lf=(c==10||state==10);
730 throw new IOException("Incomplete parts");
733 public void setDeleteOnExit(boolean deleteOnExit)
735 _deleteOnExit = deleteOnExit;
739 public boolean isDeleteOnExit()
741 return _deleteOnExit;
745 /* ------------------------------------------------------------ */
746 private String value(String nameEqualsValue)
748 int idx = nameEqualsValue.indexOf('=');
749 String value = nameEqualsValue.substring(idx+1).trim();
750 return QuotedStringTokenizer.unquoteOnly(value);
754 /* ------------------------------------------------------------ */
755 private String filenameValue(String nameEqualsValue)
757 int idx = nameEqualsValue.indexOf('=');
758 String value = nameEqualsValue.substring(idx+1).trim();
760 if (value.matches(".??[a-z,A-Z]\\:\\\\[^\\\\].*"))
762 //incorrectly escaped IE filenames that have the whole path
763 //we just strip any leading & trailing quotes and leave it as is
764 char first=value.charAt(0);
765 if (first=='"' || first=='\'')
766 value=value.substring(1);
767 char last=value.charAt(value.length()-1);
768 if (last=='"' || last=='\'')
769 value = value.substring(0,value.length()-1);
774 //unquote the string, but allow any backslashes that don't
775 //form a valid escape sequence to remain as many browsers
776 //even on *nix systems will not escape a filename containing
778 return QuotedStringTokenizer.unquoteOnly(value, true);
783 private static class Base64InputStream extends InputStream
785 ReadLineInputStream _in;
791 public Base64InputStream(ReadLineInputStream rlis)
797 public int read() throws IOException
799 if (_buffer==null || _pos>= _buffer.length)
801 //Any CR and LF will be consumed by the readLine() call.
802 //We need to put them back into the bytes returned from this
803 //method because the parsing of the multipart content uses them
804 //as markers to determine when we've reached the end of a part.
805 _line = _in.readLine();
807 return -1; //nothing left
808 if (_line.startsWith("--"))
809 _buffer=(_line+"\r\n").getBytes(); //boundary marking end of part
810 else if (_line.length()==0)
811 _buffer="\r\n".getBytes(); //blank line
814 ByteArrayOutputStream baos = new ByteArrayOutputStream((4*_line.length()/3)+2);
815 B64Code.decode(_line, baos);
818 _buffer = baos.toByteArray();
824 return _buffer[_pos++];