1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * @(#)MimeMultipart.java     1.31 03/01/29
  28  */
  29 
  30 
  31 
  32 package com.sun.xml.internal.messaging.saaj.packaging.mime.internet;
  33 
  34 import java.io.*;
  35 
  36 import javax.activation.DataSource;
  37 
  38 import com.sun.xml.internal.messaging.saaj.packaging.mime.*;
  39 import com.sun.xml.internal.messaging.saaj.packaging.mime.util.*;
  40 import com.sun.xml.internal.messaging.saaj.util.FinalArrayList;
  41 import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
  42 import com.sun.xml.internal.messaging.saaj.util.SAAJUtil;
  43 
  44 /**
  45  * The MimeMultipart class is an implementation
  46  * that uses MIME conventions for the multipart data. <p>
  47  *
  48  * A MimeMultipart is obtained from a MimeBodyPart whose primary type
  49  * is "multipart" (by invoking the part's <code>getContent()</code> method)
  50  * or it can be created by a client as part of creating a new MimeMessage. <p>
  51  *
  52  * The default multipart subtype is "mixed".  The other multipart
  53  * subtypes, such as "alternative", "related", and so on, can be
  54  * implemented as subclasses of MimeMultipart with additional methods
  55  * to implement the additional semantics of that type of multipart
  56  * content. The intent is that service providers, mail JavaBean writers
  57  * and mail clients will write many such subclasses and their Command
  58  * Beans, and will install them into the JavaBeans Activation
  59  * Framework, so that any JavaMail implementation and its clients can
  60  * transparently find and use these classes. Thus, a MIME multipart
  61  * handler is treated just like any other type handler, thereby
  62  * decoupling the process of providing multipart handlers from the
  63  * JavaMail API. Lacking these additional MimeMultipart subclasses,
  64  * all subtypes of MIME multipart data appear as MimeMultipart objects. <p>
  65  *
  66  * An application can directly construct a MIME multipart object of any
  67  * subtype by using the <code>MimeMultipart(String subtype)</code>
  68  * constructor.  For example, to create a "multipart/alternative" object,
  69  * use <code>new MimeMultipart("alternative")</code>.
  70  *
  71  * @version 1.31, 03/01/29
  72  * @author  John Mani
  73  * @author  Bill Shannon
  74  * @author  Max Spivak
  75  */
  76 
  77 //BM MimeMultipart can extend this
  78 public  class MimeMultipart {
  79 
  80     /**
  81      * The DataSource supplying our InputStream.
  82      */
  83     protected DataSource ds = null;
  84 
  85     /**
  86      * Have we parsed the data from our InputStream yet?
  87      * Defaults to true; set to false when our constructor is
  88      * given a DataSource with an InputStream that we need to
  89      * parse.
  90      */
  91     protected boolean parsed = true;
  92 
  93     /**
  94      * Vector of MimeBodyPart objects.
  95      */
  96     protected FinalArrayList<MimeBodyPart> parts = new FinalArrayList<MimeBodyPart>(); // Holds BodyParts
  97 
  98     /**
  99      * This field specifies the content-type of this multipart
 100      * object. It defaults to "multipart/mixed".
 101      */
 102     protected ContentType contentType;
 103 
 104     /**
 105      * The <code>MimeBodyPart</code> containing this <code>MimeMultipart</code>,
 106      * if known.
 107      * @since   JavaMail 1.1
 108      */
 109     protected MimeBodyPart parent;
 110 
 111     protected static final boolean ignoreMissingEndBoundary;
 112     static {
 113         ignoreMissingEndBoundary = SAAJUtil.getSystemBoolean("saaj.mime.multipart.ignoremissingendboundary");
 114     }
 115 
 116     /**
 117      * Default constructor. An empty MimeMultipart object
 118      * is created. Its content type is set to "multipart/mixed".
 119      * A unique boundary string is generated and this string is
 120      * setup as the "boundary" parameter for the
 121      * <code>contentType</code> field. <p>
 122      *
 123      * MimeBodyParts may be added later.
 124      */
 125     public MimeMultipart() {
 126         this("mixed");
 127     }
 128 
 129     /**
 130      * Construct a MimeMultipart object of the given subtype.
 131      * A unique boundary string is generated and this string is
 132      * setup as the "boundary" parameter for the
 133      * <code>contentType</code> field. <p>
 134      *
 135      * MimeBodyParts may be added later.
 136      * @param subtype subtype.
 137      */
 138     public MimeMultipart(String subtype) {
 139         //super();
 140         /*
 141          * Compute a boundary string.
 142          */
 143         String boundary = UniqueValue.getUniqueBoundaryValue();
 144         contentType = new ContentType("multipart", subtype, null);
 145         contentType.setParameter("boundary", boundary);
 146     }
 147 
 148     /**
 149      * Constructs a MimeMultipart object and its bodyparts from the
 150      * given DataSource. <p>
 151      *
 152      * This constructor handles as a special case the situation where the
 153      * given DataSource is a MultipartDataSource object.
 154      *
 155      * Otherwise, the DataSource is assumed to provide a MIME multipart
 156      * byte stream.  The <code>parsed</code> flag is set to false.  When
 157      * the data for the body parts are needed, the parser extracts the
 158      * "boundary" parameter from the content type of this DataSource,
 159      * skips the 'preamble' and reads bytes till the terminating
 160      * boundary and creates MimeBodyParts for each part of the stream.
 161      *
 162      * @param   ds      DataSource, can be a MultipartDataSource
 163      * @param ct
 164      *      This must be the same information as {@link DataSource#getContentType()}.
 165      *      All the callers of this method seem to have this object handy, so
 166      *      for performance reason this method accepts it. Can be null.
 167      *
 168      * @exception MessagingException in case of error
 169      */
 170     public MimeMultipart(DataSource ds, ContentType ct) throws MessagingException {
 171         // 'ds' was not a MultipartDataSource, we have
 172         // to parse this ourself.
 173         parsed = false;
 174         this.ds = ds;
 175         if (ct==null)
 176             contentType = new ContentType(ds.getContentType());
 177         else
 178             contentType = ct;
 179     }
 180 
 181     /**
 182      * Set the subtype. This method should be invoked only on a new
 183      * MimeMultipart object created by the client. The default subtype
 184      * of such a multipart object is "mixed". <p>
 185      *
 186      * @param   subtype         Subtype
 187      */
 188     public  void setSubType(String subtype) {
 189         contentType.setSubType(subtype);
 190     }
 191 
 192     /**
 193      * Return the number of enclosed MimeBodyPart objects.
 194      *
 195      * @return          number of parts.
 196      * @throws MessagingException in case of error.
 197      */
 198     public  int getCount() throws MessagingException {
 199         parse();
 200         if (parts == null)
 201             return 0;
 202 
 203         return parts.size();
 204     }
 205 
 206     /**
 207      * Get the specified MimeBodyPart.  BodyParts are numbered starting at 0.
 208      *
 209      * @param index     the index of the desired MimeBodyPart.
 210      * @return          the MimeBodyPart.
 211      * @exception       MessagingException if no such MimeBodyPart exists
 212      */
 213     public  MimeBodyPart getBodyPart(int index)
 214                         throws MessagingException {
 215         parse();
 216         if (parts == null)
 217             throw new IndexOutOfBoundsException("No such BodyPart");
 218 
 219         return parts.get(index);
 220     }
 221 
 222     /**
 223      * Get the MimeBodyPart referred to by the given ContentID (CID).
 224      * Returns null if the part is not found.
 225      *
 226      * @param  CID      the ContentID of the desired part
 227      * @return          the MimeBodyPart
 228      * @exception       MessagingException if no such MimeBodyPart exists.
 229      */
 230     public  MimeBodyPart getBodyPart(String CID)
 231                         throws MessagingException {
 232         parse();
 233 
 234         int count = getCount();
 235         for (int i = 0; i < count; i++) {
 236            MimeBodyPart part = getBodyPart(i);
 237            String s = part.getContentID();
 238            // Old versions of AXIS2 put angle brackets around the content
 239            // id but not the start param
 240            String sNoAngle = (s!= null) ? s.replaceFirst("^<", "").replaceFirst(">$", "")
 241                    :null;
 242            if (s != null && (s.equals(CID) || CID.equals(sNoAngle)))
 243                 return part;
 244         }
 245         return null;
 246     }
 247 
 248     /**
 249      * Update headers. The default implementation here just
 250      * calls the <code>updateHeaders</code> method on each of its
 251      * children BodyParts. <p>
 252      *
 253      * Note that the boundary parameter is already set up when
 254      * a new and empty MimeMultipart object is created. <p>
 255      *
 256      * This method is called when the <code>saveChanges</code>
 257      * method is invoked on the Message object containing this
 258      * MimeMultipart. This is typically done as part of the Message
 259      * send process, however note that a client is free to call
 260      * it any number of times. So if the header updating process is
 261      * expensive for a specific MimeMultipart subclass, then it
 262      * might itself want to track whether its internal state actually
 263      * did change, and do the header updating only if necessary.
 264      *
 265      * @exception       MessagingException in case of error.
 266      */
 267     protected void updateHeaders() throws MessagingException {
 268         for (int i = 0; i < parts.size(); i++)
 269             parts.get(i).updateHeaders();
 270     }
 271 
 272     /**
 273      * Iterates through all the parts and outputs each Mime part
 274      * separated by a boundary.
 275      *
 276      * @param os output stream.
 277      *
 278      * @exception IOException if an I/O Error occurs.
 279      * @exception MessagingException in case of error.
 280      */
 281     public void writeTo(OutputStream os)
 282             throws IOException, MessagingException {
 283         parse();
 284 
 285         String boundary = "--" + contentType.getParameter("boundary");
 286 
 287         for (int i = 0; i < parts.size(); i++) {
 288             OutputUtil.writeln(boundary, os); // put out boundary
 289             getBodyPart(i).writeTo(os);
 290             OutputUtil.writeln(os); // put out empty line
 291         }
 292 
 293         // put out last boundary
 294         OutputUtil.writeAsAscii(boundary, os);
 295         OutputUtil.writeAsAscii("--", os);
 296         os.flush();
 297     }
 298 
 299     /**
 300      * Parse the InputStream from our DataSource, constructing the
 301      * appropriate MimeBodyParts.  The <code>parsed</code> flag is
 302      * set to true, and if true on entry nothing is done.  This
 303      * method is called by all other methods that need data for
 304      * the body parts, to make sure the data has been parsed.
 305      *
 306      * @exception MessagingException in case of error.
 307      *
 308      * @since   JavaMail 1.2
 309      */
 310     protected  void parse() throws MessagingException {
 311         if (parsed)
 312             return;
 313 
 314         InputStream in;
 315         SharedInputStream sin = null;
 316         long start = 0, end = 0;
 317         boolean foundClosingBoundary = false;
 318 
 319         try {
 320             in = ds.getInputStream();
 321             if (!(in instanceof ByteArrayInputStream) &&
 322                 !(in instanceof BufferedInputStream) &&
 323                 !(in instanceof SharedInputStream))
 324                 in = new BufferedInputStream(in);
 325         } catch (Exception ex) {
 326             throw new MessagingException("No inputstream from datasource");
 327         }
 328         if (in instanceof SharedInputStream)
 329             sin = (SharedInputStream)in;
 330 
 331         String boundary = "--" + contentType.getParameter("boundary");
 332         byte[] bndbytes = ASCIIUtility.getBytes(boundary);
 333         int bl = bndbytes.length;
 334 
 335         ByteOutputStream buf = null;
 336         try {
 337             // Skip the preamble
 338             LineInputStream lin = new LineInputStream(in);
 339             String line;
 340             while ((line = lin.readLine()) != null) {
 341                 /*
 342                  * Strip trailing whitespace.  Can't use trim method
 343                  * because it's too aggressive.  Some bogus MIME
 344                  * messages will include control characters in the
 345                  * boundary string.
 346                  */
 347                 int i;
 348                 for (i = line.length() - 1; i >= 0; i--) {
 349                     char c = line.charAt(i);
 350                     if (!(c == ' ' || c == '\t'))
 351                         break;
 352                 }
 353                 line = line.substring(0, i + 1);
 354                 if (line.equals(boundary))
 355                     break;
 356             }
 357             if (line == null)
 358                 throw new MessagingException("Missing start boundary");
 359 
 360             /*
 361              * Read and process body parts until we see the
 362              * terminating boundary line (or EOF).
 363              */
 364             boolean done = false;
 365         getparts:
 366             while (!done) {
 367                 InternetHeaders headers = null;
 368                 if (sin != null) {
 369                     start = sin.getPosition();
 370                     // skip headers
 371                     while ((line = lin.readLine()) != null && line.length() > 0)
 372                         ;
 373                     if (line == null) {
 374                         if (!ignoreMissingEndBoundary) {
 375                            throw new MessagingException("Missing End Boundary for Mime Package : EOF while skipping headers");
 376                         }
 377                         // assume there's just a missing end boundary
 378                         break getparts;
 379                     }
 380                 } else {
 381                     // collect the headers for this body part
 382                     headers = createInternetHeaders(in);
 383                 }
 384 
 385                 if (!in.markSupported())
 386                     throw new MessagingException("Stream doesn't support mark");
 387 
 388                 buf = null;
 389                 // if we don't have a shared input stream, we copy the data
 390                 if (sin == null)
 391                     buf = new ByteOutputStream();
 392                 int b;
 393                 boolean bol = true;    // beginning of line flag
 394                 // the two possible end of line characters
 395                 int eol1 = -1, eol2 = -1;
 396 
 397                 /*
 398                  * Read and save the content bytes in buf.
 399                  */
 400                 for (;;) {
 401                     if (bol) {
 402                         /*
 403                          * At the beginning of a line, check whether the
 404                          * next line is a boundary.
 405                          */
 406                         int i;
 407                         in.mark(bl + 4 + 1000); // bnd + "--\r\n" + lots of LWSP
 408                         // read bytes, matching against the boundary
 409                         for (i = 0; i < bl; i++)
 410                             if (in.read() != bndbytes[i])
 411                                 break;
 412                         if (i == bl) {
 413                             // matched the boundary, check for last boundary
 414                             int b2 = in.read();
 415                             if (b2 == '-') {
 416                                 if (in.read() == '-') {
 417                                     done = true;
 418                                     foundClosingBoundary = true;
 419                                     break;      // ignore trailing text
 420                                 }
 421                             }
 422                             // skip linear whitespace
 423                             while (b2 == ' ' || b2 == '\t')
 424                                 b2 = in.read();
 425                             // check for end of line
 426                             if (b2 == '\n')
 427                                 break;  // got it!  break out of the loop
 428                             if (b2 == '\r') {
 429                                 in.mark(1);
 430                                 if (in.read() != '\n')
 431                                     in.reset();
 432                                 break;  // got it!  break out of the loop
 433                             }
 434                         }
 435                         // failed to match, reset and proceed normally
 436                         in.reset();
 437 
 438                         // if this is not the first line, write out the
 439                         // end of line characters from the previous line
 440                         if (buf != null && eol1 != -1) {
 441                             buf.write(eol1);
 442                             if (eol2 != -1)
 443                                 buf.write(eol2);
 444                             eol1 = eol2 = -1;
 445                         }
 446                     }
 447 
 448                     // read the next byte
 449                     if ((b = in.read()) < 0) {
 450                         done = true;
 451                         break;
 452                     }
 453 
 454                     /*
 455                      * If we're at the end of the line, save the eol characters
 456                      * to be written out before the beginning of the next line.
 457                      */
 458                     if (b == '\r' || b == '\n') {
 459                         bol = true;
 460                         if (sin != null)
 461                             end = sin.getPosition() - 1;
 462                         eol1 = b;
 463                         if (b == '\r') {
 464                             in.mark(1);
 465                             if ((b = in.read()) == '\n')
 466                                 eol2 = b;
 467                             else
 468                                 in.reset();
 469                         }
 470                     } else {
 471                         bol = false;
 472                         if (buf != null)
 473                             buf.write(b);
 474                     }
 475                 }
 476 
 477                 /*
 478                  * Create a MimeBody element to represent this body part.
 479                  */
 480                 MimeBodyPart part;
 481                 if (sin != null)
 482                     part = createMimeBodyPart(sin.newStream(start, end));
 483                 else
 484                     part = createMimeBodyPart(headers, buf.getBytes(), buf.getCount());
 485                 addBodyPart(part);
 486             }
 487         } catch (IOException ioex) {
 488             throw new MessagingException("IO Error", ioex);
 489         } finally {
 490             if (buf != null)
 491                 buf.close();
 492         }
 493 
 494         if (!ignoreMissingEndBoundary && !foundClosingBoundary && sin== null) {
 495             throw new MessagingException("Missing End Boundary for Mime Package : EOF while skipping headers");
 496         }
 497         parsed = true;
 498     }
 499 
 500     /**
 501      * Create and return an InternetHeaders object that loads the
 502      * headers from the given InputStream.  Subclasses can override
 503      * this method to return a subclass of InternetHeaders, if
 504      * necessary.  This implementation simply constructs and returns
 505      * an InternetHeaders object.
 506      *
 507      * @param   is      the InputStream to read the headers from.
 508      * @return headers.
 509      * @exception       MessagingException in case of error.
 510      * @since           JavaMail 1.2
 511      */
 512     protected InternetHeaders createInternetHeaders(InputStream is)
 513                                 throws MessagingException {
 514         return new InternetHeaders(is);
 515     }
 516 
 517     /**
 518      * Create and return a MimeBodyPart object to represent a
 519      * body part parsed from the InputStream.  Subclasses can override
 520      * this method to return a subclass of MimeBodyPart, if
 521      * necessary.  This implementation simply constructs and returns
 522      * a MimeBodyPart object.
 523      *
 524      * @param   headers         the headers for the body part.
 525      * @param   content         the content of the body part.
 526      * @param   len             the content length.
 527      * @return  MimeBodyPart
 528      * @since                   JavaMail 1.2
 529      */
 530     protected MimeBodyPart createMimeBodyPart(InternetHeaders headers, byte[] content, int len) {
 531             return new MimeBodyPart(headers, content,len);
 532     }
 533 
 534     /**
 535      * Create and return a MimeBodyPart object to represent a
 536      * body part parsed from the InputStream.  Subclasses can override
 537      * this method to return a subclass of MimeBodyPart, if
 538      * necessary.  This implementation simply constructs and returns
 539      * a MimeBodyPart object.
 540      *
 541      * @param   is              InputStream containing the body part.
 542      * @return  MimeBodyPart.
 543      * @exception               MessagingException in case of error.
 544      * @since                   JavaMail 1.2
 545      */
 546     protected MimeBodyPart createMimeBodyPart(InputStream is) throws MessagingException {
 547             return new MimeBodyPart(is);
 548     }
 549 
 550     /**
 551      * Setup this MimeMultipart object from the given MultipartDataSource. <p>
 552      *
 553      * The method adds the MultipartDataSource's MimeBodyPart
 554      * objects into this MimeMultipart. This MimeMultipart's contentType is
 555      * set to that of the MultipartDataSource. <p>
 556      *
 557      * This method is typically used in those cases where one
 558      * has a multipart data source that has already been pre-parsed into
 559      * the individual body parts (for example, an IMAP datasource), but
 560      * needs to create an appropriate MimeMultipart subclass that represents
 561      * a specific multipart subtype.
 562      *
 563      * @param   mp      MimeMultipart datasource
 564      * @exception               MessagingException in case of error.
 565      */
 566     protected void setMultipartDataSource(MultipartDataSource mp)
 567                         throws MessagingException {
 568         contentType = new ContentType(mp.getContentType());
 569 
 570         int count = mp.getCount();
 571         for (int i = 0; i < count; i++)
 572             addBodyPart(mp.getBodyPart(i));
 573     }
 574 
 575     /**
 576      * Return the content-type of this MimeMultipart. <p>
 577      *
 578      * This implementation just returns the value of the
 579      * <code>contentType</code> field.
 580      *
 581      * @return  content-type
 582      * @see     #contentType
 583      */
 584     public ContentType getContentType() {
 585             return contentType;
 586     }
 587 
 588     /**
 589      * Remove the specified part from the multipart message.
 590      * Shifts all the parts after the removed part down one.
 591      *
 592      * @param   part    The part to remove
 593      * @return          true if part removed, false otherwise
 594      * @exception       MessagingException if no such MimeBodyPart exists
 595      */
 596     public boolean removeBodyPart(MimeBodyPart part) throws MessagingException {
 597         if (parts == null)
 598             throw new MessagingException("No such body part");
 599 
 600         boolean ret = parts.remove(part);
 601         part.setParent(null);
 602         return ret;
 603     }
 604 
 605     /**
 606      * Remove the part at specified location (starting from 0).
 607      * Shifts all the parts after the removed part down one.
 608      *
 609      * @param   index   Index of the part to remove
 610      * @exception       IndexOutOfBoundsException if the given index
 611      *                  is out of range.
 612      */
 613     public void removeBodyPart(int index) {
 614         if (parts == null)
 615             throw new IndexOutOfBoundsException("No such BodyPart");
 616 
 617         MimeBodyPart part = parts.get(index);
 618         parts.remove(index);
 619         part.setParent(null);
 620     }
 621 
 622     /**
 623      * Adds a MimeBodyPart to the multipart.  The MimeBodyPart is appended to
 624      * the list of existing Parts.
 625      *
 626      * @param  part  The MimeBodyPart to be appended
 627      */
 628     public synchronized void addBodyPart(MimeBodyPart part) {
 629         if (parts == null)
 630             parts = new FinalArrayList<MimeBodyPart>();
 631 
 632         parts.add(part);
 633         part.setParent(this);
 634     }
 635 
 636     /**
 637      * Adds a MimeBodyPart at position <code>index</code>.
 638      * If <code>index</code> is not the last one in the list,
 639      * the subsequent parts are shifted up. If <code>index</code>
 640      * is larger than the number of parts present, the
 641      * MimeBodyPart is appended to the end.
 642      *
 643      * @param  part  The MimeBodyPart to be inserted
 644      * @param  index Location where to insert the part
 645      */
 646     public synchronized void addBodyPart(MimeBodyPart part, int index) {
 647         if (parts == null)
 648             parts = new FinalArrayList<MimeBodyPart>();
 649 
 650         parts.add(index,part);
 651         part.setParent(this);
 652     }
 653 
 654     /**
 655      * Return the <code>MimeBodyPart</code> that contains this <code>MimeMultipart</code>
 656      * object, or <code>null</code> if not known.
 657      * @since   JavaMail 1.1
 658      */
 659     MimeBodyPart getParent() {
 660         return parent;
 661     }
 662 
 663     /**
 664      * Set the parent of this <code>MimeMultipart</code> to be the specified
 665      * <code>MimeBodyPart</code>.  Normally called by the <code>Message</code>
 666      * or <code>MimeBodyPart</code> <code>setContent(MimeMultipart)</code> method.
 667      * <code>parent</code> may be <code>null</code> if the
 668      * <code>MimeMultipart</code> is being removed from its containing
 669      * <code>MimeBodyPart</code>.
 670      * @since   JavaMail 1.1
 671      */
 672     void setParent(MimeBodyPart parent) {
 673         this.parent = parent;
 674     }
 675 }