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