1 /*
   2  * Copyright (c) 1997, 2016, 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  * @(#)InternetHeaders.java   1.16 02/08/08
  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.Header;
  35 import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
  36 import com.sun.xml.internal.messaging.saaj.packaging.mime.util.LineInputStream;
  37 import com.sun.xml.internal.messaging.saaj.util.FinalArrayList;
  38 
  39 import java.io.IOException;
  40 import java.io.InputStream;
  41 import java.util.AbstractList;
  42 import java.util.List;
  43 import java.util.NoSuchElementException;
  44 
  45 /**
  46  * InternetHeaders is a utility class that manages RFC822 style
  47  * headers. Given an RFC822 format message stream, it reads lines
  48  * until the blank line that indicates end of header. The input stream
  49  * is positioned at the start of the body. The lines are stored
  50  * within the object and can be extracted as either Strings or
  51  * {@link Header} objects. <p>
  52  * <p/>
  53  * This class is mostly intended for service providers. MimeMessage
  54  * and MimeBody use this class for holding their headers. <p>
  55  * <p/>
  56  * <hr> <strong>A note on RFC822 and MIME headers</strong><p>
  57  * <p/>
  58  * RFC822 and MIME header fields <strong>must</strong> contain only
  59  * US-ASCII characters. If a header contains non US-ASCII characters,
  60  * it must be encoded as per the rules in RFC 2047. The MimeUtility
  61  * class provided in this package can be used to to achieve this.
  62  * Callers of the <code>setHeader</code>, <code>addHeader</code>, and
  63  * <code>addHeaderLine</code> methods are responsible for enforcing
  64  * the MIME requirements for the specified headers.  In addition, these
  65  * header fields must be folded (wrapped) before being sent if they
  66  * exceed the line length limitation for the transport (1000 bytes for
  67  * SMTP).  Received headers may have been folded.  The application is
  68  * responsible for folding and unfolding headers as appropriate. <p>
  69  *
  70  * @author John Mani
  71  * @author Bill Shannon
  72  * @see MimeUtility
  73  */
  74 public final class InternetHeaders {
  75 
  76     private final FinalArrayList<hdr> headers = new FinalArrayList<hdr>();
  77 
  78     /**
  79      * Lazily cerated view of header lines (Strings).
  80      */
  81     private List<String> headerValueView;
  82 
  83     /**
  84      * Create an empty InternetHeaders object.
  85      */
  86     public InternetHeaders() {
  87     }
  88 
  89     /**
  90      * Read and parse the given RFC822 message stream till the
  91      * blank line separating the header from the body. The input
  92      * stream is left positioned at the start of the body. The
  93      * header lines are stored internally. <p>
  94      * <p/>
  95      * For efficiency, wrap a BufferedInputStream around the actual
  96      * input stream and pass it as the parameter.
  97      *
  98      * @param   is RFC822 input stream
  99      */
 100     public InternetHeaders(InputStream is) throws MessagingException {
 101         load(is);
 102     }
 103 
 104     /**
 105      * Read and parse the given RFC822 message stream till the
 106      * blank line separating the header from the body. Store the
 107      * header lines inside this InternetHeaders object. <p>
 108      * <p/>
 109      * Note that the header lines are added into this InternetHeaders
 110      * object, so any existing headers in this object will not be
 111      * affected.
 112      *
 113      * @param   is RFC822 input stream
 114      */
 115     public void load(InputStream is) throws MessagingException {
 116         // Read header lines until a blank line. It is valid
 117         // to have BodyParts with no header lines.
 118         String line;
 119         LineInputStream lis = new LineInputStream(is);
 120         String prevline = null; // the previous header line, as a string
 121         // a buffer to accumulate the header in, when we know it's needed
 122         StringBuilder lineBuffer = new StringBuilder();
 123 
 124         try {
 125             //while ((line = lis.readLine()) != null) {
 126             do {
 127                 line = lis.readLine();
 128                 if (line != null &&
 129                         (line.startsWith(" ") || line.startsWith("\t"))) {
 130                     // continuation of header
 131                     if (prevline != null) {
 132                         lineBuffer.append(prevline);
 133                         prevline = null;
 134                     }
 135                     lineBuffer.append("\r\n");
 136                     lineBuffer.append(line);
 137                 } else {
 138                     // new header
 139                     if (prevline != null)
 140                         addHeaderLine(prevline);
 141                     else if (lineBuffer.length() > 0) {
 142                         // store previous header first
 143                         addHeaderLine(lineBuffer.toString());
 144                         lineBuffer.setLength(0);
 145                     }
 146                     prevline = line;
 147                 }
 148             } while (line != null && line.length() > 0);
 149         } catch (IOException ioex) {
 150             throw new MessagingException("Error in input stream", ioex);
 151         }
 152     }
 153 
 154     /**
 155      * Return all the values for the specified header. The
 156      * values are String objects.  Returns <code>null</code>
 157      * if no headers with the specified name exist.
 158      *
 159      * @param   name header name
 160      * @return          array of header values, or null if none
 161      */
 162     public String[] getHeader(String name) {
 163         // XXX - should we just step through in index order?
 164         FinalArrayList<String> v = new FinalArrayList<String>(); // accumulate return values
 165 
 166         int len = headers.size();
 167         for( int i=0; i<len; i++ ) {
 168             hdr h = headers.get(i);
 169             if (name.equalsIgnoreCase(h.name)) {
 170                 v.add(h.getValue());
 171             }
 172         }
 173         if (v.size() == 0)
 174             return (null);
 175         // convert Vector to an array for return
 176         return v.toArray(new String[v.size()]);
 177     }
 178 
 179     /**
 180      * Get all the headers for this header name, returned as a single
 181      * String, with headers separated by the delimiter. If the
 182      * delimiter is <code>null</code>, only the first header is
 183      * returned.  Returns <code>null</code>
 184      * if no headers with the specified name exist.
 185      *
 186      * @param delimiter delimiter
 187      * @return the value fields for all headers with
 188      *         this name, or null if none
 189      * @param   name header name
 190      */
 191     public String getHeader(String name, String delimiter) {
 192         String[] s = getHeader(name);
 193 
 194         if (s == null)
 195             return null;
 196 
 197         if ((s.length == 1) || delimiter == null)
 198             return s[0];
 199 
 200         StringBuilder r = new StringBuilder(s[0]);
 201         for (int i = 1; i < s.length; i++) {
 202             r.append(delimiter);
 203             r.append(s[i]);
 204         }
 205         return r.toString();
 206     }
 207 
 208     /**
 209      * Change the first header line that matches name
 210      * to have value, adding a new header if no existing header
 211      * matches. Remove all matching headers but the first. <p>
 212      * <p/>
 213      * Note that RFC822 headers can only contain US-ASCII characters
 214      *
 215      * @param   name    header name
 216      * @param   value   header value
 217      */
 218     public void setHeader(String name, String value) {
 219         boolean found = false;
 220 
 221         for (int i = 0; i < headers.size(); i++) {
 222             hdr h = headers.get(i);
 223             if (name.equalsIgnoreCase(h.name)) {
 224                 if (!found) {
 225                     int j;
 226                     if (h.line != null && (j = h.line.indexOf(':')) >= 0) {
 227                         h.line = h.line.substring(0, j + 1) + " " + value;
 228                     } else {
 229                         h.line = name + ": " + value;
 230                     }
 231                     found = true;
 232                 } else {
 233                     headers.remove(i);
 234                     i--;    // have to look at i again
 235                 }
 236             }
 237         }
 238 
 239         if (!found) {
 240             addHeader(name, value);
 241         }
 242     }
 243 
 244     /**
 245      * Add a header with the specified name and value to the header list. <p>
 246      * <p/>
 247      * Note that RFC822 headers can only contain US-ASCII characters.
 248      *
 249      * @param   name    header name
 250      * @param   value   header value
 251      */
 252     public void addHeader(String name, String value) {
 253         int pos = headers.size();
 254         for (int i = headers.size() - 1; i >= 0; i--) {
 255             hdr h = headers.get(i);
 256             if (name.equalsIgnoreCase(h.name)) {
 257                 headers.add(i + 1, new hdr(name, value));
 258                 return;
 259             }
 260             // marker for default place to add new headers
 261             if (h.name.equals(":"))
 262                 pos = i;
 263         }
 264         headers.add(pos, new hdr(name, value));
 265     }
 266 
 267     /**
 268      * Remove all header entries that match the given name
 269      *
 270      * @param   name header name
 271      */
 272     public void removeHeader(String name) {
 273         for (int i = 0; i < headers.size(); i++) {
 274             hdr h = headers.get(i);
 275             if (name.equalsIgnoreCase(h.name)) {
 276                 headers.remove(i);
 277                 i--;    // have to look at i again
 278             }
 279         }
 280     }
 281 
 282     /**
 283      * Return all the headers as an Enumeration of
 284      * {@link Header} objects.
 285      *
 286      * @return  Header objects
 287      */
 288     public List<? extends Header> getAllHeaders() {
 289         return headers; // conceptually it should be read-only, but for performance reason I'm not wrapping it here
 290     }
 291 
 292     /**
 293      * Add an RFC822 header line to the header store.
 294      * If the line starts with a space or tab (a continuation line),
 295      * add it to the last header line in the list. <p>
 296      * <p/>
 297      * Note that RFC822 headers can only contain US-ASCII characters
 298      *
 299      * @param   line    raw RFC822 header line
 300      */
 301     public void addHeaderLine(String line) {
 302         try {
 303             char c = line.charAt(0);
 304             if (c == ' ' || c == '\t') {
 305                 hdr h = headers.get(headers.size() - 1);
 306                 h.line += "\r\n" + line;
 307             } else
 308                 headers.add(new hdr(line));
 309         } catch (StringIndexOutOfBoundsException e) {
 310             // line is empty, ignore it
 311             return;
 312         } catch (NoSuchElementException e) {
 313             // XXX - vector is empty?
 314         }
 315     }
 316 
 317     /**
 318      * Return all the header lines as a collection
 319      */
 320     public List<String> getAllHeaderLines() {
 321         if(headerValueView==null)
 322             headerValueView = new AbstractList<String>() {
 323                 public String get(int index) {
 324                     return headers.get(index).line;
 325                 }
 326 
 327                 public int size() {
 328                     return headers.size();
 329                 }
 330             };
 331         return headerValueView;
 332     }
 333 }
 334 
 335 /*
 336  * A private utility class to represent an individual header.
 337  */
 338 
 339 class hdr implements Header {
 340     // XXX - should these be private?
 341     String name;    // the canonicalized (trimmed) name of this header
 342     // XXX - should name be stored in lower case?
 343     String line;    // the entire RFC822 header "line"
 344 
 345     /*
 346      * Constructor that takes a line and splits out
 347      * the header name.
 348      */
 349     hdr(String l) {
 350         int i = l.indexOf(':');
 351         if (i < 0) {
 352             // should never happen
 353             name = l.trim();
 354         } else {
 355             name = l.substring(0, i).trim();
 356         }
 357         line = l;
 358     }
 359 
 360     /*
 361      * Constructor that takes a header name and value.
 362      */
 363     hdr(String n, String v) {
 364         name = n;
 365         line = n + ": " + v;
 366     }
 367 
 368     /*
 369      * Return the "name" part of the header line.
 370      */
 371     public String getName() {
 372         return name;
 373     }
 374 
 375     /*
 376      * Return the "value" part of the header line.
 377      */
 378     public String getValue() {
 379         int i = line.indexOf(':');
 380         if (i < 0)
 381             return line;
 382 
 383         int j;
 384         if (name.equalsIgnoreCase("Content-Description")) {
 385             // Content-Description should retain the folded whitespace after header unfolding -
 386             // rf. RFC2822 section 2.2.3, rf. RFC2822 section 3.2.3
 387             for (j = i + 1; j < line.length(); j++) {
 388                 char c = line.charAt(j);
 389                 if (!(/*c == ' ' ||*/c == '\t' || c == '\r' || c == '\n'))
 390                     break;
 391             }
 392         } else {
 393             // skip whitespace after ':'
 394             for (j = i + 1; j < line.length(); j++) {
 395                 char c = line.charAt(j);
 396                 if (!(c == ' ' || c == '\t' || c == '\r' || c == '\n'))
 397                     break;
 398             }
 399         }
 400         return line.substring(j);
 401     }
 402 }