View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.fileupload;
18  
19  import static java.lang.String.format;
20  
21  import java.io.ByteArrayOutputStream;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.io.OutputStream;
25  import java.io.UnsupportedEncodingException;
26  
27  import org.apache.commons.fileupload.FileUploadBase.FileUploadIOException;
28  import org.apache.commons.fileupload.util.Closeable;
29  import org.apache.commons.fileupload.util.Streams;
30  
31  /**
32   * <p> Low level API for processing file uploads.
33   *
34   * <p> This class can be used to process data streams conforming to MIME
35   * 'multipart' format as defined in
36   * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>. Arbitrarily
37   * large amounts of data in the stream can be processed under constant
38   * memory usage.
39   *
40   * <p> The format of the stream is defined in the following way:<br>
41   *
42   * <code>
43   *   multipart-body := preamble 1*encapsulation close-delimiter epilogue<br>
44   *   encapsulation := delimiter body CRLF<br>
45   *   delimiter := "--" boundary CRLF<br>
46   *   close-delimiter := "--" boundary "--"<br>
47   *   preamble := &lt;ignore&gt;<br>
48   *   epilogue := &lt;ignore&gt;<br>
49   *   body := header-part CRLF body-part<br>
50   *   header-part := 1*header CRLF<br>
51   *   header := header-name ":" header-value<br>
52   *   header-name := &lt;printable ascii characters except ":"&gt;<br>
53   *   header-value := &lt;any ascii characters except CR & LF&gt;<br>
54   *   body-data := &lt;arbitrary data&gt;<br>
55   * </code>
56   *
57   * <p>Note that body-data can contain another mulipart entity.  There
58   * is limited support for single pass processing of such nested
59   * streams.  The nested stream is <strong>required</strong> to have a
60   * boundary token of the same length as the parent stream (see {@link
61   * #setBoundary(byte[])}).
62   *
63   * <p>Here is an example of usage of this class.<br>
64   *
65   * <pre>
66   *   try {
67   *     MultipartStream multipartStream = new MultipartStream(input, boundary);
68   *     boolean nextPart = multipartStream.skipPreamble();
69   *     OutputStream output;
70   *     while(nextPart) {
71   *       String header = multipartStream.readHeaders();
72   *       // process headers
73   *       // create some output stream
74   *       multipartStream.readBodyData(output);
75   *       nextPart = multipartStream.readBoundary();
76   *     }
77   *   } catch(MultipartStream.MalformedStreamException e) {
78   *     // the stream failed to follow required syntax
79   *   } catch(IOException e) {
80   *     // a read or write error occurred
81   *   }
82   * </pre>
83   *
84   * @version $Id: MultipartStream.java 1568863 2014-02-17 00:06:40Z sebb $
85   */
86  public class MultipartStream {
87  
88      /**
89       * Internal class, which is used to invoke the
90       * {@link ProgressListener}.
91       */
92      public static class ProgressNotifier {
93  
94          /**
95           * The listener to invoke.
96           */
97          private final ProgressListener listener;
98  
99          /**
100          * Number of expected bytes, if known, or -1.
101          */
102         private final long contentLength;
103 
104         /**
105          * Number of bytes, which have been read so far.
106          */
107         private long bytesRead;
108 
109         /**
110          * Number of items, which have been read so far.
111          */
112         private int items;
113 
114         /**
115          * Creates a new instance with the given listener
116          * and content length.
117          *
118          * @param pListener The listener to invoke.
119          * @param pContentLength The expected content length.
120          */
121         ProgressNotifier(ProgressListener pListener, long pContentLength) {
122             listener = pListener;
123             contentLength = pContentLength;
124         }
125 
126         /**
127          * Called to indicate that bytes have been read.
128          *
129          * @param pBytes Number of bytes, which have been read.
130          */
131         void noteBytesRead(int pBytes) {
132             /* Indicates, that the given number of bytes have been read from
133              * the input stream.
134              */
135             bytesRead += pBytes;
136             notifyListener();
137         }
138 
139         /**
140          * Called to indicate, that a new file item has been detected.
141          */
142         void noteItem() {
143             ++items;
144             notifyListener();
145         }
146 
147         /**
148          * Called for notifying the listener.
149          */
150         private void notifyListener() {
151             if (listener != null) {
152                 listener.update(bytesRead, contentLength, items);
153             }
154         }
155 
156     }
157 
158     // ----------------------------------------------------- Manifest constants
159 
160     /**
161      * The Carriage Return ASCII character value.
162      */
163     public static final byte CR = 0x0D;
164 
165     /**
166      * The Line Feed ASCII character value.
167      */
168     public static final byte LF = 0x0A;
169 
170     /**
171      * The dash (-) ASCII character value.
172      */
173     public static final byte DASH = 0x2D;
174 
175     /**
176      * The maximum length of <code>header-part</code> that will be
177      * processed (10 kilobytes = 10240 bytes.).
178      */
179     public static final int HEADER_PART_SIZE_MAX = 10240;
180 
181     /**
182      * The default length of the buffer used for processing a request.
183      */
184     protected static final int DEFAULT_BUFSIZE = 4096;
185 
186     /**
187      * A byte sequence that marks the end of <code>header-part</code>
188      * (<code>CRLFCRLF</code>).
189      */
190     protected static final byte[] HEADER_SEPARATOR = {CR, LF, CR, LF};
191 
192     /**
193      * A byte sequence that that follows a delimiter that will be
194      * followed by an encapsulation (<code>CRLF</code>).
195      */
196     protected static final byte[] FIELD_SEPARATOR = {CR, LF};
197 
198     /**
199      * A byte sequence that that follows a delimiter of the last
200      * encapsulation in the stream (<code>--</code>).
201      */
202     protected static final byte[] STREAM_TERMINATOR = {DASH, DASH};
203 
204     /**
205      * A byte sequence that precedes a boundary (<code>CRLF--</code>).
206      */
207     protected static final byte[] BOUNDARY_PREFIX = {CR, LF, DASH, DASH};
208 
209     // ----------------------------------------------------------- Data members
210 
211     /**
212      * The input stream from which data is read.
213      */
214     private final InputStream input;
215 
216     /**
217      * The length of the boundary token plus the leading <code>CRLF--</code>.
218      */
219     private int boundaryLength;
220 
221     /**
222      * The amount of data, in bytes, that must be kept in the buffer in order
223      * to detect delimiters reliably.
224      */
225     private final int keepRegion;
226 
227     /**
228      * The byte sequence that partitions the stream.
229      */
230     private final byte[] boundary;
231 
232     /**
233      * The length of the buffer used for processing the request.
234      */
235     private final int bufSize;
236 
237     /**
238      * The buffer used for processing the request.
239      */
240     private final byte[] buffer;
241 
242     /**
243      * The index of first valid character in the buffer.
244      * <br>
245      * 0 <= head < bufSize
246      */
247     private int head;
248 
249     /**
250      * The index of last valid character in the buffer + 1.
251      * <br>
252      * 0 <= tail <= bufSize
253      */
254     private int tail;
255 
256     /**
257      * The content encoding to use when reading headers.
258      */
259     private String headerEncoding;
260 
261     /**
262      * The progress notifier, if any, or null.
263      */
264     private final ProgressNotifier notifier;
265 
266     // ----------------------------------------------------------- Constructors
267 
268     /**
269      * Creates a new instance.
270      *
271      * @deprecated 1.2.1 Use {@link #MultipartStream(InputStream, byte[], int,
272      * ProgressNotifier)}
273      */
274     @Deprecated
275     public MultipartStream() {
276         this(null, null, null);
277     }
278 
279     /**
280      * <p> Constructs a <code>MultipartStream</code> with a custom size buffer
281      * and no progress notifier.
282      *
283      * <p> Note that the buffer must be at least big enough to contain the
284      * boundary string, plus 4 characters for CR/LF and double dash, plus at
285      * least one byte of data.  Too small a buffer size setting will degrade
286      * performance.
287      *
288      * @param input    The <code>InputStream</code> to serve as a data source.
289      * @param boundary The token used for dividing the stream into
290      *                 <code>encapsulations</code>.
291      * @param bufSize  The size of the buffer to be used, in bytes.
292      *
293      * @deprecated 1.2.1 Use {@link #MultipartStream(InputStream, byte[], int,
294      * ProgressNotifier)}.
295      */
296     @Deprecated
297     public MultipartStream(InputStream input, byte[] boundary, int bufSize) {
298         this(input, boundary, bufSize, null);
299     }
300 
301     /**
302      * <p> Constructs a <code>MultipartStream</code> with a custom size buffer.
303      *
304      * <p> Note that the buffer must be at least big enough to contain the
305      * boundary string, plus 4 characters for CR/LF and double dash, plus at
306      * least one byte of data.  Too small a buffer size setting will degrade
307      * performance.
308      *
309      * @param input    The <code>InputStream</code> to serve as a data source.
310      * @param boundary The token used for dividing the stream into
311      *                 <code>encapsulations</code>.
312      * @param bufSize  The size of the buffer to be used, in bytes.
313      * @param pNotifier The notifier, which is used for calling the
314      *                  progress listener, if any.
315      *
316      * @throws IllegalArgumentException If the buffer size is too small
317      *
318      * @since 1.3.1
319      */
320     public MultipartStream(InputStream input,
321             byte[] boundary,
322             int bufSize,
323             ProgressNotifier pNotifier) {
324 
325         if (boundary == null) {
326             throw new IllegalArgumentException("boundary may not be null");
327         }
328 
329         this.input = input;
330         this.bufSize = bufSize;
331         this.buffer = new byte[bufSize];
332         this.notifier = pNotifier;
333 
334         // We prepend CR/LF to the boundary to chop trailing CR/LF from
335         // body-data tokens.
336         this.boundaryLength = boundary.length + BOUNDARY_PREFIX.length;
337         if (bufSize < this.boundaryLength + 1) {
338             throw new IllegalArgumentException(
339                     "The buffer size specified for the MultipartStream is too small");
340         }
341         this.boundary = new byte[this.boundaryLength];
342         this.keepRegion = this.boundary.length;
343 
344         System.arraycopy(BOUNDARY_PREFIX, 0, this.boundary, 0,
345                 BOUNDARY_PREFIX.length);
346         System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length,
347                 boundary.length);
348 
349         head = 0;
350         tail = 0;
351     }
352 
353     /**
354      * <p> Constructs a <code>MultipartStream</code> with a default size buffer.
355      *
356      * @param input    The <code>InputStream</code> to serve as a data source.
357      * @param boundary The token used for dividing the stream into
358      *                 <code>encapsulations</code>.
359      * @param pNotifier An object for calling the progress listener, if any.
360      *
361      *
362      * @see #MultipartStream(InputStream, byte[], int, ProgressNotifier)
363      */
364     MultipartStream(InputStream input,
365             byte[] boundary,
366             ProgressNotifier pNotifier) {
367         this(input, boundary, DEFAULT_BUFSIZE, pNotifier);
368     }
369 
370     /**
371      * <p> Constructs a <code>MultipartStream</code> with a default size buffer.
372      *
373      * @param input    The <code>InputStream</code> to serve as a data source.
374      * @param boundary The token used for dividing the stream into
375      *                 <code>encapsulations</code>.
376      *
377      * @deprecated 1.2.1 Use {@link #MultipartStream(InputStream, byte[], int,
378      *  ProgressNotifier)}.
379      */
380     @Deprecated
381     public MultipartStream(InputStream input,
382             byte[] boundary) {
383         this(input, boundary, DEFAULT_BUFSIZE, null);
384     }
385 
386     // --------------------------------------------------------- Public methods
387 
388     /**
389      * Retrieves the character encoding used when reading the headers of an
390      * individual part. When not specified, or <code>null</code>, the platform
391      * default encoding is used.
392      *
393      * @return The encoding used to read part headers.
394      */
395     public String getHeaderEncoding() {
396         return headerEncoding;
397     }
398 
399     /**
400      * Specifies the character encoding to be used when reading the headers of
401      * individual parts. When not specified, or <code>null</code>, the platform
402      * default encoding is used.
403      *
404      * @param encoding The encoding used to read part headers.
405      */
406     public void setHeaderEncoding(String encoding) {
407         headerEncoding = encoding;
408     }
409 
410     /**
411      * Reads a byte from the <code>buffer</code>, and refills it as
412      * necessary.
413      *
414      * @return The next byte from the input stream.
415      *
416      * @throws IOException if there is no more data available.
417      */
418     public byte readByte() throws IOException {
419         // Buffer depleted ?
420         if (head == tail) {
421             head = 0;
422             // Refill.
423             tail = input.read(buffer, head, bufSize);
424             if (tail == -1) {
425                 // No more data available.
426                 throw new IOException("No more data is available");
427             }
428             if (notifier != null) {
429                 notifier.noteBytesRead(tail);
430             }
431         }
432         return buffer[head++];
433     }
434 
435     /**
436      * Skips a <code>boundary</code> token, and checks whether more
437      * <code>encapsulations</code> are contained in the stream.
438      *
439      * @return <code>true</code> if there are more encapsulations in
440      *         this stream; <code>false</code> otherwise.
441      *
442      * @throws FileUploadIOException if the bytes read from the stream exceeded the size limits
443      * @throws MalformedStreamException if the stream ends unexpectedly or
444      *                                  fails to follow required syntax.
445      */
446     public boolean readBoundary()
447             throws FileUploadIOException, MalformedStreamException {
448         byte[] marker = new byte[2];
449         boolean nextChunk = false;
450 
451         head += boundaryLength;
452         try {
453             marker[0] = readByte();
454             if (marker[0] == LF) {
455                 // Work around IE5 Mac bug with input type=image.
456                 // Because the boundary delimiter, not including the trailing
457                 // CRLF, must not appear within any file (RFC 2046, section
458                 // 5.1.1), we know the missing CR is due to a buggy browser
459                 // rather than a file containing something similar to a
460                 // boundary.
461                 return true;
462             }
463 
464             marker[1] = readByte();
465             if (arrayequals(marker, STREAM_TERMINATOR, 2)) {
466                 nextChunk = false;
467             } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) {
468                 nextChunk = true;
469             } else {
470                 throw new MalformedStreamException(
471                 "Unexpected characters follow a boundary");
472             }
473         } catch (FileUploadIOException e) {
474             // wraps a SizeException, re-throw as it will be unwrapped later
475             throw e;
476         } catch (IOException e) {
477             throw new MalformedStreamException("Stream ended unexpectedly");
478         }
479         return nextChunk;
480     }
481 
482     /**
483      * <p>Changes the boundary token used for partitioning the stream.
484      *
485      * <p>This method allows single pass processing of nested multipart
486      * streams.
487      *
488      * <p>The boundary token of the nested stream is <code>required</code>
489      * to be of the same length as the boundary token in parent stream.
490      *
491      * <p>Restoring the parent stream boundary token after processing of a
492      * nested stream is left to the application.
493      *
494      * @param boundary The boundary to be used for parsing of the nested
495      *                 stream.
496      *
497      * @throws IllegalBoundaryException if the <code>boundary</code>
498      *                                  has a different length than the one
499      *                                  being currently parsed.
500      */
501     public void setBoundary(byte[] boundary)
502             throws IllegalBoundaryException {
503         if (boundary.length != boundaryLength - BOUNDARY_PREFIX.length) {
504             throw new IllegalBoundaryException(
505             "The length of a boundary token can not be changed");
506         }
507         System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length,
508                 boundary.length);
509     }
510 
511     /**
512      * <p>Reads the <code>header-part</code> of the current
513      * <code>encapsulation</code>.
514      *
515      * <p>Headers are returned verbatim to the input stream, including the
516      * trailing <code>CRLF</code> marker. Parsing is left to the
517      * application.
518      *
519      * <p><strong>TODO</strong> allow limiting maximum header size to
520      * protect against abuse.
521      *
522      * @return The <code>header-part</code> of the current encapsulation.
523      *
524      * @throws FileUploadIOException if the bytes read from the stream exceeded the size limits.
525      * @throws MalformedStreamException if the stream ends unexpectedly.
526      */
527     public String readHeaders() throws FileUploadIOException, MalformedStreamException {
528         int i = 0;
529         byte b;
530         // to support multi-byte characters
531         ByteArrayOutputStream baos = new ByteArrayOutputStream();
532         int size = 0;
533         while (i < HEADER_SEPARATOR.length) {
534             try {
535                 b = readByte();
536             } catch (FileUploadIOException e) {
537                 // wraps a SizeException, re-throw as it will be unwrapped later
538                 throw e;
539             } catch (IOException e) {
540                 throw new MalformedStreamException("Stream ended unexpectedly");
541             }
542             if (++size > HEADER_PART_SIZE_MAX) {
543                 throw new MalformedStreamException(
544                         format("Header section has more than %s bytes (maybe it is not properly terminated)",
545                                Integer.valueOf(HEADER_PART_SIZE_MAX)));
546             }
547             if (b == HEADER_SEPARATOR[i]) {
548                 i++;
549             } else {
550                 i = 0;
551             }
552             baos.write(b);
553         }
554 
555         String headers = null;
556         if (headerEncoding != null) {
557             try {
558                 headers = baos.toString(headerEncoding);
559             } catch (UnsupportedEncodingException e) {
560                 // Fall back to platform default if specified encoding is not
561                 // supported.
562                 headers = baos.toString();
563             }
564         } else {
565             headers = baos.toString();
566         }
567 
568         return headers;
569     }
570 
571     /**
572      * <p>Reads <code>body-data</code> from the current
573      * <code>encapsulation</code> and writes its contents into the
574      * output <code>Stream</code>.
575      *
576      * <p>Arbitrary large amounts of data can be processed by this
577      * method using a constant size buffer. (see {@link
578      * #MultipartStream(InputStream,byte[],int,
579      *   MultipartStream.ProgressNotifier) constructor}).
580      *
581      * @param output The <code>Stream</code> to write data into. May
582      *               be null, in which case this method is equivalent
583      *               to {@link #discardBodyData()}.
584      *
585      * @return the amount of data written.
586      *
587      * @throws MalformedStreamException if the stream ends unexpectedly.
588      * @throws IOException              if an i/o error occurs.
589      */
590     public int readBodyData(OutputStream output)
591             throws MalformedStreamException, IOException {
592         return (int) Streams.copy(newInputStream(), output, false); // N.B. Streams.copy closes the input stream
593     }
594 
595     /**
596      * Creates a new {@link ItemInputStream}.
597      * @return A new instance of {@link ItemInputStream}.
598      */
599     ItemInputStream newInputStream() {
600         return new ItemInputStream();
601     }
602 
603     /**
604      * <p> Reads <code>body-data</code> from the current
605      * <code>encapsulation</code> and discards it.
606      *
607      * <p>Use this method to skip encapsulations you don't need or don't
608      * understand.
609      *
610      * @return The amount of data discarded.
611      *
612      * @throws MalformedStreamException if the stream ends unexpectedly.
613      * @throws IOException              if an i/o error occurs.
614      */
615     public int discardBodyData() throws MalformedStreamException, IOException {
616         return readBodyData(null);
617     }
618 
619     /**
620      * Finds the beginning of the first <code>encapsulation</code>.
621      *
622      * @return <code>true</code> if an <code>encapsulation</code> was found in
623      *         the stream.
624      *
625      * @throws IOException if an i/o error occurs.
626      */
627     public boolean skipPreamble() throws IOException {
628         // First delimiter may be not preceeded with a CRLF.
629         System.arraycopy(boundary, 2, boundary, 0, boundary.length - 2);
630         boundaryLength = boundary.length - 2;
631         try {
632             // Discard all data up to the delimiter.
633             discardBodyData();
634 
635             // Read boundary - if succeeded, the stream contains an
636             // encapsulation.
637             return readBoundary();
638         } catch (MalformedStreamException e) {
639             return false;
640         } finally {
641             // Restore delimiter.
642             System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2);
643             boundaryLength = boundary.length;
644             boundary[0] = CR;
645             boundary[1] = LF;
646         }
647     }
648 
649     /**
650      * Compares <code>count</code> first bytes in the arrays
651      * <code>a</code> and <code>b</code>.
652      *
653      * @param a     The first array to compare.
654      * @param b     The second array to compare.
655      * @param count How many bytes should be compared.
656      *
657      * @return <code>true</code> if <code>count</code> first bytes in arrays
658      *         <code>a</code> and <code>b</code> are equal.
659      */
660     public static boolean arrayequals(byte[] a,
661             byte[] b,
662             int count) {
663         for (int i = 0; i < count; i++) {
664             if (a[i] != b[i]) {
665                 return false;
666             }
667         }
668         return true;
669     }
670 
671     /**
672      * Searches for a byte of specified value in the <code>buffer</code>,
673      * starting at the specified <code>position</code>.
674      *
675      * @param value The value to find.
676      * @param pos   The starting position for searching.
677      *
678      * @return The position of byte found, counting from beginning of the
679      *         <code>buffer</code>, or <code>-1</code> if not found.
680      */
681     protected int findByte(byte value,
682             int pos) {
683         for (int i = pos; i < tail; i++) {
684             if (buffer[i] == value) {
685                 return i;
686             }
687         }
688 
689         return -1;
690     }
691 
692     /**
693      * Searches for the <code>boundary</code> in the <code>buffer</code>
694      * region delimited by <code>head</code> and <code>tail</code>.
695      *
696      * @return The position of the boundary found, counting from the
697      *         beginning of the <code>buffer</code>, or <code>-1</code> if
698      *         not found.
699      */
700     protected int findSeparator() {
701         int first;
702         int match = 0;
703         int maxpos = tail - boundaryLength;
704         for (first = head; first <= maxpos && match != boundaryLength; first++) {
705             first = findByte(boundary[0], first);
706             if (first == -1 || first > maxpos) {
707                 return -1;
708             }
709             for (match = 1; match < boundaryLength; match++) {
710                 if (buffer[first + match] != boundary[match]) {
711                     break;
712                 }
713             }
714         }
715         if (match == boundaryLength) {
716             return first - 1;
717         }
718         return -1;
719     }
720 
721     /**
722      * Thrown to indicate that the input stream fails to follow the
723      * required syntax.
724      */
725     public static class MalformedStreamException extends IOException {
726 
727         /**
728          * The UID to use when serializing this instance.
729          */
730         private static final long serialVersionUID = 6466926458059796677L;
731 
732         /**
733          * Constructs a <code>MalformedStreamException</code> with no
734          * detail message.
735          */
736         public MalformedStreamException() {
737             super();
738         }
739 
740         /**
741          * Constructs an <code>MalformedStreamException</code> with
742          * the specified detail message.
743          *
744          * @param message The detail message.
745          */
746         public MalformedStreamException(String message) {
747             super(message);
748         }
749 
750     }
751 
752     /**
753      * Thrown upon attempt of setting an invalid boundary token.
754      */
755     public static class IllegalBoundaryException extends IOException {
756 
757         /**
758          * The UID to use when serializing this instance.
759          */
760         private static final long serialVersionUID = -161533165102632918L;
761 
762         /**
763          * Constructs an <code>IllegalBoundaryException</code> with no
764          * detail message.
765          */
766         public IllegalBoundaryException() {
767             super();
768         }
769 
770         /**
771          * Constructs an <code>IllegalBoundaryException</code> with
772          * the specified detail message.
773          *
774          * @param message The detail message.
775          */
776         public IllegalBoundaryException(String message) {
777             super(message);
778         }
779 
780     }
781 
782     /**
783      * An {@link InputStream} for reading an items contents.
784      */
785     public class ItemInputStream extends InputStream implements Closeable {
786 
787         /**
788          * The number of bytes, which have been read so far.
789          */
790         private long total;
791 
792         /**
793          * The number of bytes, which must be hold, because
794          * they might be a part of the boundary.
795          */
796         private int pad;
797 
798         /**
799          * The current offset in the buffer.
800          */
801         private int pos;
802 
803         /**
804          * Whether the stream is already closed.
805          */
806         private boolean closed;
807 
808         /**
809          * Creates a new instance.
810          */
811         ItemInputStream() {
812             findSeparator();
813         }
814 
815         /**
816          * Called for finding the separator.
817          */
818         private void findSeparator() {
819             pos = MultipartStream.this.findSeparator();
820             if (pos == -1) {
821                 if (tail - head > keepRegion) {
822                     pad = keepRegion;
823                 } else {
824                     pad = tail - head;
825                 }
826             }
827         }
828 
829         /**
830          * Returns the number of bytes, which have been read
831          * by the stream.
832          *
833          * @return Number of bytes, which have been read so far.
834          */
835         public long getBytesRead() {
836             return total;
837         }
838 
839         /**
840          * Returns the number of bytes, which are currently
841          * available, without blocking.
842          *
843          * @throws IOException An I/O error occurs.
844          * @return Number of bytes in the buffer.
845          */
846         @Override
847         public int available() throws IOException {
848             if (pos == -1) {
849                 return tail - head - pad;
850             }
851             return pos - head;
852         }
853 
854         /**
855          * Offset when converting negative bytes to integers.
856          */
857         private static final int BYTE_POSITIVE_OFFSET = 256;
858 
859         /**
860          * Returns the next byte in the stream.
861          *
862          * @return The next byte in the stream, as a non-negative
863          *   integer, or -1 for EOF.
864          * @throws IOException An I/O error occurred.
865          */
866         @Override
867         public int read() throws IOException {
868             if (closed) {
869                 throw new FileItemStream.ItemSkippedException();
870             }
871             if (available() == 0 && makeAvailable() == 0) {
872                 return -1;
873             }
874             ++total;
875             int b = buffer[head++];
876             if (b >= 0) {
877                 return b;
878             }
879             return b + BYTE_POSITIVE_OFFSET;
880         }
881 
882         /**
883          * Reads bytes into the given buffer.
884          *
885          * @param b The destination buffer, where to write to.
886          * @param off Offset of the first byte in the buffer.
887          * @param len Maximum number of bytes to read.
888          * @return Number of bytes, which have been actually read,
889          *   or -1 for EOF.
890          * @throws IOException An I/O error occurred.
891          */
892         @Override
893         public int read(byte[] b, int off, int len) throws IOException {
894             if (closed) {
895                 throw new FileItemStream.ItemSkippedException();
896             }
897             if (len == 0) {
898                 return 0;
899             }
900             int res = available();
901             if (res == 0) {
902                 res = makeAvailable();
903                 if (res == 0) {
904                     return -1;
905                 }
906             }
907             res = Math.min(res, len);
908             System.arraycopy(buffer, head, b, off, res);
909             head += res;
910             total += res;
911             return res;
912         }
913 
914         /**
915          * Closes the input stream.
916          *
917          * @throws IOException An I/O error occurred.
918          */
919         @Override
920         public void close() throws IOException {
921             close(false);
922         }
923 
924         /**
925          * Closes the input stream.
926          *
927          * @param pCloseUnderlying Whether to close the underlying stream
928          *   (hard close)
929          * @throws IOException An I/O error occurred.
930          */
931         public void close(boolean pCloseUnderlying) throws IOException {
932             if (closed) {
933                 return;
934             }
935             if (pCloseUnderlying) {
936                 closed = true;
937                 input.close();
938             } else {
939                 for (;;) {
940                     int av = available();
941                     if (av == 0) {
942                         av = makeAvailable();
943                         if (av == 0) {
944                             break;
945                         }
946                     }
947                     skip(av);
948                 }
949             }
950             closed = true;
951         }
952 
953         /**
954          * Skips the given number of bytes.
955          *
956          * @param bytes Number of bytes to skip.
957          * @return The number of bytes, which have actually been
958          *   skipped.
959          * @throws IOException An I/O error occurred.
960          */
961         @Override
962         public long skip(long bytes) throws IOException {
963             if (closed) {
964                 throw new FileItemStream.ItemSkippedException();
965             }
966             int av = available();
967             if (av == 0) {
968                 av = makeAvailable();
969                 if (av == 0) {
970                     return 0;
971                 }
972             }
973             long res = Math.min(av, bytes);
974             head += res;
975             return res;
976         }
977 
978         /**
979          * Attempts to read more data.
980          *
981          * @return Number of available bytes
982          * @throws IOException An I/O error occurred.
983          */
984         private int makeAvailable() throws IOException {
985             if (pos != -1) {
986                 return 0;
987             }
988 
989             // Move the data to the beginning of the buffer.
990             total += tail - head - pad;
991             System.arraycopy(buffer, tail - pad, buffer, 0, pad);
992 
993             // Refill buffer with new data.
994             head = 0;
995             tail = pad;
996 
997             for (;;) {
998                 int bytesRead = input.read(buffer, tail, bufSize - tail);
999                 if (bytesRead == -1) {
1000                     // The last pad amount is left in the buffer.
1001                     // Boundary can't be in there so signal an error
1002                     // condition.
1003                     final String msg = "Stream ended unexpectedly";
1004                     throw new MalformedStreamException(msg);
1005                 }
1006                 if (notifier != null) {
1007                     notifier.noteBytesRead(bytesRead);
1008                 }
1009                 tail += bytesRead;
1010 
1011                 findSeparator();
1012                 int av = available();
1013 
1014                 if (av > 0 || pos != -1) {
1015                     return av;
1016                 }
1017             }
1018         }
1019 
1020         /**
1021          * Returns, whether the stream is closed.
1022          *
1023          * @return True, if the stream is closed, otherwise false.
1024          */
1025         public boolean isClosed() {
1026             return closed;
1027         }
1028 
1029     }
1030 
1031 }