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  * @(#)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.
  52  * <p>
  53  * This class is mostly intended for service providers. MimeMessage
  54  * and MimeBody use this class for holding their headers.
  55  * <hr> <strong>A note on RFC822 and MIME headers</strong>
  56  * <p>
  57  * RFC822 and MIME header fields <strong>must</strong> contain only
  58  * US-ASCII characters. If a header contains non US-ASCII characters,
  59  * it must be encoded as per the rules in RFC 2047. The MimeUtility
  60  * class provided in this package can be used to to achieve this.
  61  * Callers of the <code>setHeader</code>, <code>addHeader</code>, and
  62  * <code>addHeaderLine</code> methods are responsible for enforcing
  63  * the MIME requirements for the specified headers.  In addition, these
  64  * header fields must be folded (wrapped) before being sent if they
  65  * exceed the line length limitation for the transport (1000 bytes for
  66  * SMTP).  Received headers may have been folded.  The application is
  67  * responsible for folding and unfolding headers as appropriate.
  68  *
  69  * @author John Mani
  70  * @author Bill Shannon
  71  * @see MimeUtility
  72  */
  73 public final class InternetHeaders {
  74 
  75     private final FinalArrayList<hdr> headers = new FinalArrayList<hdr>();
  76 
  77     /**
  78      * Lazily cerated view of header lines (Strings).
  79      */
  80     private List<String> headerValueView;
  81 
  82     /**
  83      * Create an empty InternetHeaders object.
  84      */
  85     public InternetHeaders() {
  86     }
  87 
  88     /**
  89      * Read and parse the given RFC822 message stream till the
  90      * blank line separating the header from the body. The input
  91      * stream is left positioned at the start of the body. The
  92      * header lines are stored internally.
  93      * <p>
  94      * For efficiency, wrap a BufferedInputStream around the actual
  95      * input stream and pass it as the parameter.
  96      *
  97      * @param   is RFC822 input stream
  98      * @exception MessagingException in case of error
  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.
 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      * @exception MessagingException in case of error
 115      */
 116     public void load(InputStream is) throws MessagingException {
 117         // Read header lines until a blank line. It is valid
 118         // to have BodyParts with no header lines.
 119         String line;
 120         LineInputStream lis = new LineInputStream(is);
 121         String prevline = null; // the previous header line, as a string
 122         // a buffer to accumulate the header in, when we know it's needed
 123         StringBuilder lineBuffer = new StringBuilder();
 124 
 125         try {
 126             //while ((line = lis.readLine()) != null) {
 127             do {
 128                 line = lis.readLine();
 129                 if (line != null &&
 130                         (line.startsWith(" ") || line.startsWith("\t"))) {
 131                     // continuation of header
 132                     if (prevline != null) {
 133                         lineBuffer.append(prevline);
 134                         prevline = null;
 135                     }
 136                     lineBuffer.append("\r\n");
 137                     lineBuffer.append(line);
 138                 } else {
 139                     // new header
 140                     if (prevline != null)
 141                         addHeaderLine(prevline);
 142                     else if (lineBuffer.length() > 0) {
 143                         // store previous header first
 144                         addHeaderLine(lineBuffer.toString());
 145                         lineBuffer.setLength(0);
 146                     }
 147                     prevline = line;
 148                 }
 149             } while (line != null && line.length() > 0);
 150         } catch (IOException ioex) {
 151             throw new MessagingException("Error in input stream", ioex);
 152         }
 153     }
 154 
 155     /**
 156      * Return all the values for the specified header. The
 157      * values are String objects.  Returns <code>null</code>
 158      * if no headers with the specified name exist.
 159      *
 160      * @param   name header name
 161      * @return          array of header values, or null if none
 162      */
 163     public String[] getHeader(String name) {
 164         // XXX - should we just step through in index order?
 165         FinalArrayList<String> v = new FinalArrayList<String>(); // accumulate return values
 166 
 167         int len = headers.size();
 168         for( int i=0; i<len; i++ ) {
 169             hdr h = headers.get(i);
 170             if (name.equalsIgnoreCase(h.name)) {
 171                 v.add(h.getValue());
 172             }
 173         }
 174         if (v.size() == 0)
 175             return (null);
 176         // convert Vector to an array for return
 177         return v.toArray(new String[v.size()]);
 178     }
 179 
 180     /**
 181      * Get all the headers for this header name, returned as a single
 182      * String, with headers separated by the delimiter. If the
 183      * delimiter is <code>null</code>, only the first header is
 184      * returned.  Returns <code>null</code>
 185      * if no headers with the specified name exist.
 186      *
 187      * @param delimiter delimiter
 188      * @return the value fields for all headers with
 189      *         this name, or null if none
 190      * @param   name header name
 191      */
 192     public String getHeader(String name, String delimiter) {
 193         String[] s = getHeader(name);
 194 
 195         if (s == null)
 196             return null;
 197 
 198         if ((s.length == 1) || delimiter == null)
 199             return s[0];
 200 
 201         StringBuilder r = new StringBuilder(s[0]);
 202         for (int i = 1; i < s.length; i++) {
 203             r.append(delimiter);
 204             r.append(s[i]);
 205         }
 206         return r.toString();
 207     }
 208 
 209     /**
 210      * Change the first header line that matches name
 211      * to have value, adding a new header if no existing header
 212      * matches. Remove all matching headers but the first.
 213      * <p>
 214      * Note that RFC822 headers can only contain US-ASCII characters.
 215      *
 216      * @param   name    header name
 217      * @param   value   header value
 218      */
 219     public void setHeader(String name, String value) {
 220         boolean found = false;
 221 
 222         for (int i = 0; i < headers.size(); i++) {
 223             hdr h = headers.get(i);
 224             if (name.equalsIgnoreCase(h.name)) {
 225                 if (!found) {
 226                     int j;
 227                     if (h.line != null && (j = h.line.indexOf(':')) >= 0) {
 228                         h.line = h.line.substring(0, j + 1) + " " + value;
 229                     } else {
 230                         h.line = name + ": " + value;
 231                     }
 232                     found = true;
 233                 } else {
 234                     headers.remove(i);
 235                     i--;    // have to look at i again
 236                 }
 237             }
 238         }
 239 
 240         if (!found) {
 241             addHeader(name, value);
 242         }
 243     }
 244 
 245     /**
 246      * Add a header with the specified name and value to the header list.
 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 FinalArrayList<hdr> 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.
 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      * @return list of header lines.
 321      */
 322     public List<String> getAllHeaderLines() {
 323         if(headerValueView==null)
 324             headerValueView = new AbstractList<String>() {
 325                 @Override
 326                                 public String get(int index) {
 327                     return headers.get(index).line;
 328                 }
 329 
 330                 @Override
 331                                 public int size() {
 332                     return headers.size();
 333                 }
 334             };
 335         return headerValueView;
 336     }
 337 }
 338 
 339 /*
 340  * A private utility class to represent an individual header.
 341  */
 342 
 343 class hdr implements Header {
 344     // XXX - should these be private?
 345     String name;    // the canonicalized (trimmed) name of this header
 346     // XXX - should name be stored in lower case?
 347     String line;    // the entire RFC822 header "line"
 348 
 349     /*
 350      * Constructor that takes a line and splits out
 351      * the header name.
 352      */
 353     hdr(String l) {
 354         int i = l.indexOf(':');
 355         if (i < 0) {
 356             // should never happen
 357             name = l.trim();
 358         } else {
 359             name = l.substring(0, i).trim();
 360         }
 361         line = l;
 362     }
 363 
 364     /*
 365      * Constructor that takes a header name and value.
 366      */
 367     hdr(String n, String v) {
 368         name = n;
 369         line = n + ": " + v;
 370     }
 371 
 372     /*
 373      * Return the "name" part of the header line.
 374      */
 375     @Override
 376     public String getName() {
 377         return name;
 378     }
 379 
 380     /*
 381      * Return the "value" part of the header line.
 382      */
 383     @Override
 384     public String getValue() {
 385         int i = line.indexOf(':');
 386         if (i < 0)
 387             return line;
 388 
 389         int j;
 390         if (name.equalsIgnoreCase("Content-Description")) {
 391             // Content-Description should retain the folded whitespace after header unfolding -
 392             // rf. RFC2822 section 2.2.3, rf. RFC2822 section 3.2.3
 393             for (j = i + 1; j < line.length(); j++) {
 394                 char c = line.charAt(j);
 395                 if (!(/*c == ' ' ||*/c == '\t' || c == '\r' || c == '\n'))
 396                     break;
 397             }
 398         } else {
 399             // skip whitespace after ':'
 400             for (j = i + 1; j < line.length(); j++) {
 401                 char c = line.charAt(j);
 402                 if (!(c == ' ' || c == '\t' || c == '\r' || c == '\n'))
 403                     break;
 404             }
 405         }
 406         return line.substring(j);
 407     }
 408 }
--- EOF ---