/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 1997-2016 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package javax.mail.internet; import java.io.*; import java.util.*; import javax.mail.*; import com.sun.mail.util.LineInputStream; import com.sun.mail.util.PropUtil; /** * InternetHeaders is a utility class that manages RFC822 style * headers. Given an RFC822 format message stream, it reads lines * until the blank line that indicates end of header. The input stream * is positioned at the start of the body. The lines are stored * within the object and can be extracted as either Strings or * {@link javax.mail.Header} objects.
* * This class is mostly intended for service providers. MimeMessage * and MimeBody use this class for holding their headers. * *
*
* RFC822 and MIME header fields must contain only
* US-ASCII characters. If a header contains non US-ASCII characters,
* it must be encoded as per the rules in RFC 2047. The MimeUtility
* class provided in this package can be used to to achieve this.
* Callers of the setHeader
, addHeader
, and
* addHeaderLine
methods are responsible for enforcing
* the MIME requirements for the specified headers. In addition, these
* header fields must be folded (wrapped) before being sent if they
* exceed the line length limitation for the transport (1000 bytes for
* SMTP). Received headers may have been folded. The application is
* responsible for folding and unfolding headers as appropriate.
*
* The current implementation supports the System property
* mail.mime.ignorewhitespacelines
, which if set to true
* will cause a line containing only whitespace to be considered
* a blank line terminating the header.
*
* @see javax.mail.internet.MimeUtility
* @author John Mani
* @author Bill Shannon
*/
public class InternetHeaders {
private static final boolean ignoreWhitespaceLines =
PropUtil.getBooleanSystemProperty("mail.mime.ignorewhitespacelines",
false);
/**
* An individual internet header. This class is only used by
* subclasses of InternetHeaders.
*
* An InternetHeader object with a null value is used as a placeholder
* for headers of that name, to preserve the order of headers.
* A placeholder InternetHeader object with a name of ":" marks
* the location in the list of headers where new headers are
* added by default.
*
* @since JavaMail 1.4
*/
protected static final class InternetHeader extends Header {
/*
* Note that the value field from the superclass
* isn't used in this class. We extract the value
* from the line field as needed. We store the line
* rather than just the value to ensure that we can
* get back the exact original line, with the original
* whitespace, etc.
*/
String line; // the entire RFC822 header "line",
// or null if placeholder
/**
* Constructor that takes a line and splits out
* the header name.
*
* @param l the header line
*/
public InternetHeader(String l) {
super("", ""); // XXX - we'll change it later
int i = l.indexOf(':');
if (i < 0) {
// should never happen
name = l.trim();
} else {
name = l.substring(0, i).trim();
}
line = l;
}
/**
* Constructor that takes a header name and value.
*
* @param n the name of the header
* @param v the value of the header
*/
public InternetHeader(String n, String v) {
super(n, "");
if (v != null)
line = n + ": " + v;
else
line = null;
}
/**
* Return the "value" part of the header line.
*/
@Override
public String getValue() {
int i = line.indexOf(':');
if (i < 0)
return line;
// skip whitespace after ':'
int j;
for (j = i + 1; j < line.length(); j++) {
char c = line.charAt(j);
if (!(c == ' ' || c == '\t' || c == '\r' || c == '\n'))
break;
}
return line.substring(j);
}
}
/*
* The enumeration object used to enumerate an
* InternetHeaders object. Can return
* either a String or a Header object.
*/
static class MatchEnum {
private Iterator
*
* For efficiency, wrap a BufferedInputStream around the actual
* input stream and pass it as the parameter.
*
* No placeholder entries are inserted; the original order of
* the headers is preserved.
*
* @param is RFC822 input stream
* @exception MessagingException for any I/O error reading the stream
*/
public InternetHeaders(InputStream is) throws MessagingException {
this(is, false);
}
/**
* Read and parse the given RFC822 message stream till the
* blank line separating the header from the body. The input
* stream is left positioned at the start of the body. The
* header lines are stored internally.
*
* For efficiency, wrap a BufferedInputStream around the actual
* input stream and pass it as the parameter.
*
* No placeholder entries are inserted; the original order of
* the headers is preserved.
*
* @param is RFC822 input stream
* @param allowutf8 if UTF-8 encoded headers are allowed
* @exception MessagingException for any I/O error reading the stream
* @since JavaMail 1.6
*/
public InternetHeaders(InputStream is, boolean allowutf8)
throws MessagingException {
headers = new ArrayList<>(40);
load(is, allowutf8);
}
/**
* Read and parse the given RFC822 message stream till the
* blank line separating the header from the body. Store the
* header lines inside this InternetHeaders object. The order
* of header lines is preserved.
*
* Note that the header lines are added into this InternetHeaders
* object, so any existing headers in this object will not be
* affected. Headers are added to the end of the existing list
* of headers, in order.
*
* @param is RFC822 input stream
* @exception MessagingException for any I/O error reading the stream
*/
public void load(InputStream is) throws MessagingException {
load(is, false);
}
/**
* Read and parse the given RFC822 message stream till the
* blank line separating the header from the body. Store the
* header lines inside this InternetHeaders object. The order
* of header lines is preserved.
*
* Note that the header lines are added into this InternetHeaders
* object, so any existing headers in this object will not be
* affected. Headers are added to the end of the existing list
* of headers, in order.
*
* @param is RFC822 input stream
* @param allowutf8 if UTF-8 encoded headers are allowed
* @exception MessagingException for any I/O error reading the stream
* @since JavaMail 1.6
*/
public void load(InputStream is, boolean allowutf8)
throws MessagingException {
// Read header lines until a blank line. It is valid
// to have BodyParts with no header lines.
String line;
LineInputStream lis = new LineInputStream(is, allowutf8);
String prevline = null; // the previous header line, as a string
// a buffer to accumulate the header in, when we know it's needed
StringBuffer lineBuffer = new StringBuffer();
try {
// if the first line being read is a continuation line,
// we ignore it if it's otherwise empty or we treat it as
// a non-continuation line if it has non-whitespace content
boolean first = true;
do {
line = lis.readLine();
if (line != null &&
(line.startsWith(" ") || line.startsWith("\t"))) {
// continuation of header
if (prevline != null) {
lineBuffer.append(prevline);
prevline = null;
}
if (first) {
String lt = line.trim();
if (lt.length() > 0)
lineBuffer.append(lt);
} else {
if (lineBuffer.length() > 0)
lineBuffer.append("\r\n");
lineBuffer.append(line);
}
} else {
// new header
if (prevline != null)
addHeaderLine(prevline);
else if (lineBuffer.length() > 0) {
// store previous header first
addHeaderLine(lineBuffer.toString());
lineBuffer.setLength(0);
}
prevline = line;
}
first = false;
} while (line != null && !isEmpty(line));
} catch (IOException ioex) {
throw new MessagingException("Error in input stream", ioex);
}
}
/**
* Is this line an empty (blank) line?
*/
private static final boolean isEmpty(String line) {
return line.length() == 0 ||
(ignoreWhitespaceLines && line.trim().length() == 0);
}
/**
* Return all the values for the specified header. The
* values are String objects. Returns
*
* Note that RFC822 headers can only contain US-ASCII characters
*
* @param name header name
* @param value header value
*/
public void setHeader(String name, String value) {
boolean found = false;
for (int i = 0; i < headers.size(); i++) {
InternetHeader h = headers.get(i);
if (name.equalsIgnoreCase(h.getName())) {
if (!found) {
int j;
if (h.line != null && (j = h.line.indexOf(':')) >= 0) {
h.line = h.line.substring(0, j + 1) + " " + value;
// preserves capitalization, spacing
} else {
h.line = name + ": " + value;
}
found = true;
} else {
headers.remove(i);
i--; // have to look at i again
}
}
}
if (!found) {
addHeader(name, value);
}
}
/**
* Add a header with the specified name and value to the header list.
*
* The current implementation knows about the preferred order of most
* well-known headers and will insert headers in that order. In
* addition, it knows that
*
* Note that RFC822 headers can only contain US-ASCII characters.
*
* @param name header name
* @param value header value
*/
public void addHeader(String name, String value) {
int pos = headers.size();
boolean addReverse =
name.equalsIgnoreCase("Received") ||
name.equalsIgnoreCase("Return-Path");
if (addReverse)
pos = 0;
for (int i = headers.size() - 1; i >= 0; i--) {
InternetHeader h = headers.get(i);
if (name.equalsIgnoreCase(h.getName())) {
if (addReverse) {
pos = i;
} else {
headers.add(i + 1, new InternetHeader(name, value));
return;
}
}
// marker for default place to add new headers
if (!addReverse && h.getName().equals(":"))
pos = i;
}
headers.add(pos, new InternetHeader(name, value));
}
/**
* Remove all header entries that match the given name
* @param name header name
*/
public void removeHeader(String name) {
for (int i = 0; i < headers.size(); i++) {
InternetHeader h = headers.get(i);
if (name.equalsIgnoreCase(h.getName())) {
h.line = null;
//headers.remove(i);
//i--; // have to look at i again
}
}
}
/**
* Return all the headers as an Enumeration of
* {@link javax.mail.Header} objects.
*
* @return Enumeration of Header objects
*/
public Enumeration
*
* Note that RFC822 headers can only contain US-ASCII characters
*
* @param line raw RFC822 header line
*/
public void addHeaderLine(String line) {
try {
char c = line.charAt(0);
if (c == ' ' || c == '\t') {
InternetHeader h = headers.get(headers.size() - 1);
h.line += "\r\n" + line;
} else
headers.add(new InternetHeader(line));
} catch (StringIndexOutOfBoundsException e) {
// line is empty, ignore it
return;
} catch (NoSuchElementException e) {
// XXX - list is empty?
}
}
/**
* Return all the header lines as an Enumeration of Strings.
*
* @return Enumeration of Strings of all header lines
*/
public EnumerationReceived
and
* Return-Path
headers). If no existing header
* or placeholder for the header is found, new headers are
* added after the special placeholder with the name ":".
*
* @since JavaMail 1.4
*/
protected Listnull
* if no headers with the specified name exist.
*
* @param name header name
* @return array of header values, or null if none
*/
public String[] getHeader(String name) {
Iteratornull
, only the first header is
* returned. Returns null
* if no headers with the specified name exist.
*
* @param name header name
* @param delimiter delimiter
* @return the value fields for all headers with
* this name, or null if none
*/
public String getHeader(String name, String delimiter) {
String s[] = getHeader(name);
if (s == null)
return null;
if ((s.length == 1) || delimiter == null)
return s[0];
StringBuffer r = new StringBuffer(s[0]);
for (int i = 1; i < s.length; i++) {
r.append(delimiter);
r.append(s[i]);
}
return r.toString();
}
/**
* Change the first header line that matches name
* to have value, adding a new header if no existing header
* matches. Remove all matching headers but the first. Received
headers should be
* inserted in reverse order (newest before oldest), and that they
* should appear at the beginning of the headers, preceeded only by
* a possible Return-Path
header.