File: HeaderTokenizer.java

package info (click to toggle)
libgnumail-java 1.0-5
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,620 kB
  • ctags: 2,193
  • sloc: java: 17,470; sh: 9,912; makefile: 432; xml: 159
file content (409 lines) | stat: -rw-r--r-- 9,912 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
 * HeaderTokenizer.java
 * Copyright (C) 2002 The Free Software Foundation
 * 
 * This file is part of GNU JavaMail, a library.
 * 
 * GNU JavaMail is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * GNU JavaMail is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * As a special exception, if you link this library with other files to
 * produce an executable, this library does not by itself cause the
 * resulting executable to be covered by the GNU General Public License.
 * This exception does not however invalidate any other reasons why the
 * executable file might be covered by the GNU General Public License.
 */

package javax.mail.internet;

/**
 * This class tokenizes RFC822 and MIME headers into the basic symbols 
 * specified by RFC822 and MIME.
 * <p>
 * This class handles folded headers (ie headers with embedded CRLF SPACE
 * sequences). The folds are removed in the returned tokens.
 *
 * @author <a href="mailto:dog@gnu.org">Chris Burdess</a>
 * @version 1.3
 */
public class HeaderTokenizer
{

  /**
   * The Token class represents tokens returned by the HeaderTokenizer.
   */
  public static class Token
  {

    /**
     * Token type indicating an ATOM.
     */
    public static final int ATOM = -1;

    /**
     * Token type indicating a quoted string.
     * The value field contains the string without the quotes.
     */
    public static final int QUOTEDSTRING = -2;

    /**
     * Token type indicating a comment.
     * The value field contains the comment string without the comment 
     * start and end symbols.
     */
    public static final int COMMENT = -3;

    /**
     * Token type indicating end of input.
     */
    public static final int EOF = -4;

    /*
     * The type of the token.
     */
    private int type;

    /*
     * The value of the token if it is of type ATOM, QUOTEDSTRING, or
     * COMMENT.
     */
    private String value;

    /**
     * Constructor.
     * @param type Token type
     * @param value Token value
     */
    public Token(int type, String value)
    {
      this.type = type;
      this.value = value;
    }
    
    /**
     * Return the type of the token.
     * If the token represents a delimiter or a control character,
     * the type is that character itself, converted to an integer.
     * Otherwise, it's value is one of the following:
     * <ul>
     * <li>ATOM A sequence of ASCII characters delimited by either 
     * SPACE, CTL, '(', '"' or the specified SPECIALS
     * <li>QUOTEDSTRING A sequence of ASCII characters within quotes
     * <li>COMMENT A sequence of ASCII characters within '(' and ')'.
     * <li>EOF End of header
     */
    public int getType()
    {
      return type;
    }

    /**
     * Returns the value of the token just read.
     * When the current token is a quoted string, this field contains 
     * the body of the string, without the quotes.
     * When the current token is a comment, this field contains the body
     * of the comment.
     */
    public String getValue()
    {
      return value;
    }

  }

  /**
   * RFC822 specials
   */
  public static final String RFC822 = "()<>@,;:\\\"\t .[]";

  /**
   * MIME specials
   */
  public static final String MIME = "()<>@,;:\\\"\t []/?=";
  
  /*
   * The EOF token.
   */
  private static final Token EOF = new Token(Token.EOF, null);

  /*
   * The header string to parse.
   */
  private String header;

  /*
   * The delimiters separating tokens.
   */
  private String delimiters;

  /*
   * Whather or not to skip comments.
   */
  private boolean skipComments;

  /*
   * The index of the character identified as current for the token()
   * call.
   */
  private int pos = 0;

  /*
   * The index of the character that will be considered current on a call to
   * next().
   */
  private int next = 0;

  /*
   * The index of the character that will be considered current on a call to
   * peek().
   */
  private int peek = 0;
  
  private int maxPos;

  /**
   * Constructor that takes a rfc822 style header.
   * @param header The rfc822 header to be tokenized
   * @param delimiters Set of delimiter characters to be used to delimit ATOMS.
   * These are usually RFC822 or MIME
   * @param skipComments If true, comments are skipped and not returned 
   * as tokens
   */
  public HeaderTokenizer(String header, String delimiters,
      boolean skipComments)
  {
    this.header = (header==null) ? "" : header;
    this.delimiters = delimiters;
    this.skipComments = skipComments;
    pos = next = peek = 0;
    maxPos = header.length();
  }

  /**
   * Constructor.
   * Comments are ignored and not returned as tokens
   * @param header The header that is tokenized
   * @param delimiters The delimiters to be used
   */
  public HeaderTokenizer(String header, String delimiters)
  {
    this(header, delimiters, true);
  }

  /**
   * Constructor.
   * The RFC822 defined delimiters - RFC822 - are used to delimit ATOMS.
   * Also comments are skipped and not returned as tokens
   */
  public HeaderTokenizer(String header)
  {
    this(header, RFC822, true);
  }

  /**
   * Parses the next token from this String.
   * <p>
   * Clients sit in a loop calling <code>next()</code> to parse successive 
   * tokens until an EOF Token is returned.
   * @return the next token
   * @exception ParseException if the parse fails
   */
  public Token next()
    throws ParseException
  {
    pos = next;
    Token token = token();
    next = pos;
    peek = next;
    return token;
  }

  /**
   * Peek at the next token, without actually removing the token 
   * from the parse stream.
   * Invoking this method multiple times will return successive tokens,
   * until <code>next()</code> is called.
   * @return the next peek token
   * @param ParseException if the parse fails
   */
  public Token peek()
    throws ParseException
  {
    pos = peek;
    Token token = token();
    peek = pos;
    return token;
  }

  /**
   * Return the rest of the header.
   */
  public String getRemainder()
  {
    return header.substring(next);
  }

  /*
   * Returns the next token.
   */
  private Token token()
    throws ParseException
  {
    if (pos>=maxPos)
      return EOF;
    if (skipWhitespace()==Token.EOF)
      return EOF;
    
    boolean needsFilter = false;
    char c;
    
    // comment
    for (c = header.charAt(pos); c=='('; c = header.charAt(pos))
    {
      int start = ++pos;
      int parenCount = 1;
      while (parenCount>0 && pos<maxPos)
      {
        c = header.charAt(pos);
        if (c == '\\')
        {
          pos++;
          needsFilter = true;
        }
        else if (c=='\r')
          needsFilter = true;
        else if (c=='(')
          parenCount++;
        else if (c==')')
          parenCount--;
        pos++;
      }

      if (parenCount!=0)
        throw new ParseException("Illegal comment");
      
      if (!skipComments)
      {
        if (needsFilter)
          return new Token(Token.COMMENT, filter(header, start, pos-1));
        else
          return new Token(Token.COMMENT, header.substring(start, pos-1));
      }
      
      if (skipWhitespace()==Token.EOF)
        return EOF;
    }

    // quotedstring
    if (c=='"')
    {
      int start = ++pos;
      while (pos<maxPos)
      {
        c = header.charAt(pos);
        if (c=='\\')
        {
          pos++;
          needsFilter = true;
        }
        else if (c=='\r')
          needsFilter = true;
        else if (c=='"')
        {
          pos++;
          if (needsFilter)
            return new Token(Token.QUOTEDSTRING, 
                filter(header, start, pos-1));
          else
            return new Token(Token.QUOTEDSTRING, 
                header.substring(start, pos-1));
        }
        pos++;
      }
      throw new ParseException("Illegal quoted string");
    }

    // delimiter
    if (c<' ' || c>='\177' || delimiters.indexOf(c)>=0)
    {
      pos++;
      char[] chars = new char[1];
      chars[0] = c;
      return new Token(c, new String(chars));
    }
    
    // atom
    int start = pos;
    while (pos<maxPos)
    {
      c = header.charAt(pos);
      if (c<' ' || c>='\177' || c=='(' || c==' ' || c=='"' || 
          delimiters.indexOf(c)>=0)
        break;
      pos++;
    }
    return new Token(Token.ATOM, header.substring(start, pos));
  }

  /*
   * Advance pos over any whitespace delimiters.
   */
  private int skipWhitespace()
  {
    while (pos<maxPos)
    {
      char c = header.charAt(pos);
      if (c!=' ' && c!='\t' && c!='\r' && c!='\n')
        return pos;
      pos++;
    }
    return Token.EOF;
  }

  /*
   * Process out CR and backslash (line continuation) bytes.
   */
  private String filter(String s, int start, int end)
  {
    StringBuffer buffer = new StringBuffer();
    boolean backslash = false;
    boolean cr = false;
    for (int i = start; i<end; i++)
    {
      char c = s.charAt(i);
      if (c=='\n' && cr)
        cr = false;
      else
      {
        cr = false;
        if (!backslash)
        {
          if (c=='\\')
            backslash = true;
          else if (c=='\r')
            cr = true;
          else
            buffer.append(c);
        }
        else
        {
          buffer.append(c);
          backslash = false;
        }
      }
    }
    return buffer.toString();
  }

}