1 /*
   2  * Copyright (c) 1997, 2010, 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  * @(#)UUDecoderStream.java   1.8 02/07/08
  28  */
  29 
  30 
  31 
  32 package com.sun.xml.internal.messaging.saaj.packaging.mime.util;
  33 
  34 import java.io.*;
  35 
  36 /**
  37  * This class implements a UUDecoder. It is implemented as
  38  * a FilterInputStream, so one can just wrap this class around
  39  * any input stream and read bytes from this filter. The decoding
  40  * is done as the bytes are read out.
  41  *
  42  * @author John Mani
  43  * @author Bill Shannon
  44  */
  45 
  46 public class UUDecoderStream extends FilterInputStream {
  47     private String name;
  48     private int mode;
  49 
  50     private byte[] buffer;      // cache of decoded bytes
  51     private int bufsize = 0;    // size of the cache
  52     private int index = 0;      // index into the cache
  53     private boolean gotPrefix = false;
  54     private boolean gotEnd = false;
  55     private LineInputStream lin;
  56 
  57     /**
  58      * Create a UUdecoder that decodes the specified input stream
  59      * @param in        the input stream
  60      */
  61     public UUDecoderStream(InputStream in) {
  62         super(in);
  63         lin = new LineInputStream(in);
  64         buffer = new byte[45]; // max decoded chars in a line = 45
  65     }
  66 
  67     /**
  68      * Read the next decoded byte from this input stream. The byte
  69      * is returned as an <code>int</code> in the range <code>0</code>
  70      * to <code>255</code>. If no byte is available because the end of
  71      * the stream has been reached, the value <code>-1</code> is returned.
  72      * This method blocks until input data is available, the end of the
  73      * stream is detected, or an exception is thrown.
  74      *
  75      * @return     next byte of data, or <code>-1</code> if the end of
  76      *             stream is reached.
  77      * @exception  IOException  if an I/O error occurs.
  78      * @see        java.io.FilterInputStream#in
  79      */
  80 
  81     public int read() throws IOException {
  82         if (index >= bufsize) {
  83             readPrefix();
  84             if (!decode())
  85                 return -1;
  86             index = 0; // reset index into buffer
  87         }
  88         return buffer[index++] & 0xff; // return lower byte
  89     }
  90 
  91     public int read(byte[] buf, int off, int len) throws IOException {
  92         int i, c;
  93         for (i = 0; i < len; i++) {
  94             if ((c = read()) == -1) {
  95                 if (i == 0) // At end of stream, so we should
  96                     i = -1; // return -1, NOT 0.
  97                 break;
  98             }
  99             buf[off+i] = (byte)c;
 100         }
 101         return i;
 102     }
 103 
 104     public boolean markSupported() {
 105         return false;
 106     }
 107 
 108     public int available() throws IOException {
 109          // This is only an estimate, since in.available()
 110          // might include CRLFs too ..
 111          return ((in.available() * 3)/4 + (bufsize-index));
 112     }
 113 
 114     /**
 115      * Get the "name" field from the prefix. This is meant to
 116      * be the pathname of the decoded file
 117      *
 118      * @return     name of decoded file
 119      * @exception  IOException  if an I/O error occurs.
 120      */
 121     public String getName() throws IOException {
 122         readPrefix();
 123         return name;
 124     }
 125 
 126     /**
 127      * Get the "mode" field from the prefix. This is the permission
 128      * mode of the source file.
 129      *
 130      * @return     permission mode of source file
 131      * @exception  IOException  if an I/O error occurs.
 132      */
 133     public int getMode() throws IOException {
 134         readPrefix();
 135         return mode;
 136     }
 137 
 138     /**
 139      * UUencoded streams start off with the line:
 140      *  "begin <mode> <filename>"
 141      * Search for this prefix and gobble it up.
 142      */
 143     private void readPrefix() throws IOException {
 144         if (gotPrefix) // got the prefix
 145             return;
 146 
 147         String s;
 148         for (;;) {
 149             // read till we get the prefix: "begin MODE FILENAME"
 150             s = lin.readLine(); // NOTE: readLine consumes CRLF pairs too
 151             if (s == null)
 152                 throw new IOException("UUDecoder error: No Begin");
 153             if (s.regionMatches(true, 0, "begin", 0, 5)) {
 154                 try {
 155                     mode = Integer.parseInt(s.substring(6,9));
 156                 } catch (NumberFormatException ex) {
 157                     throw new IOException("UUDecoder error: " + ex.toString());
 158                 }
 159                 name = s.substring(10);
 160                 gotPrefix = true;
 161                 return;
 162             }
 163         }
 164     }
 165 
 166     private boolean decode() throws IOException {
 167 
 168         if (gotEnd)
 169             return false;
 170         bufsize = 0;
 171         String line;
 172         do {
 173             line = lin.readLine();
 174 
 175             /*
 176              * Improperly encoded data sometimes omits the zero length
 177              * line that starts with a space character, we detect the
 178              * following "end" line here.
 179              */
 180             if (line == null)
 181                 throw new IOException("Missing End");
 182             if (line.regionMatches(true, 0, "end", 0, 3)) {
 183                 gotEnd = true;
 184                 return false;
 185             }
 186         } while (line.length() == 0);
 187         int count = line.charAt(0);
 188         if (count < ' ')
 189             throw new IOException("Buffer format error");
 190 
 191         /*
 192          * The first character in a line is the number of original (not
 193          *  the encoded atoms) characters in the line. Note that all the
 194          *  code below has to handle the <SPACE> character that indicates
 195          *  end of encoded stream.
 196          */
 197         count = (count - ' ') & 0x3f;
 198 
 199         if (count == 0) {
 200             line = lin.readLine();
 201             if (line == null || !line.regionMatches(true, 0, "end", 0, 3))
 202                 throw new IOException("Missing End");
 203             gotEnd = true;
 204             return false;
 205         }
 206 
 207         int need = ((count * 8)+5)/6;
 208 //System.out.println("count " + count + ", need " + need + ", len " + line.length());
 209         if (line.length() < need + 1)
 210             throw new IOException("Short buffer error");
 211 
 212         int i = 1;
 213         byte a, b;
 214         /*
 215          * A correct uuencoder always encodes 3 characters at a time, even
 216          * if there aren't 3 characters left.  But since some people out
 217          * there have broken uuencoders we handle the case where they
 218          * don't include these "unnecessary" characters.
 219          */
 220         while (bufsize < count) {
 221             // continue decoding until we get 'count' decoded chars
 222             a = (byte)((line.charAt(i++) - ' ') & 0x3f);
 223             b = (byte)((line.charAt(i++) - ' ') & 0x3f);
 224             buffer[bufsize++] = (byte)(((a << 2) & 0xfc) | ((b >>> 4) & 3));
 225 
 226             if (bufsize < count) {
 227                 a = b;
 228                 b = (byte)((line.charAt(i++) - ' ') & 0x3f);
 229                 buffer[bufsize++] =
 230                                 (byte)(((a << 4) & 0xf0) | ((b >>> 2) & 0xf));
 231             }
 232 
 233             if (bufsize < count) {
 234                 a = b;
 235                 b = (byte)((line.charAt(i++) - ' ') & 0x3f);
 236                 buffer[bufsize++] = (byte)(((a << 6) & 0xc0) | (b & 0x3f));
 237             }
 238         }
 239         return true;
 240     }
 241 
 242     /*** begin TEST program *****
 243     public static void main(String argv[]) throws Exception {
 244         FileInputStream infile = new FileInputStream(argv[0]);
 245         UUDecoderStream decoder = new UUDecoderStream(infile);
 246         int c;
 247 
 248         try {
 249             while ((c = decoder.read()) != -1)
 250                 System.out.write(c);
 251             System.out.flush();
 252         } catch (Exception e) {
 253             e.printStackTrace();
 254         }
 255     }
 256     **** end TEST program ****/
 257 }