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  * @(#)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     @Override
  82     public int read() throws IOException {
  83         if (index >= bufsize) {
  84             readPrefix();
  85             if (!decode())
  86                 return -1;
  87             index = 0; // reset index into buffer
  88         }
  89         return buffer[index++] & 0xff; // return lower byte
  90     }
  91 
  92     @Override
  93     public int read(byte[] buf, int off, int len) throws IOException {
  94         int i, c;
  95         for (i = 0; i < len; i++) {
  96             if ((c = read()) == -1) {
  97                 if (i == 0) // At end of stream, so we should
  98                     i = -1; // return -1, NOT 0.
  99                 break;
 100             }
 101             buf[off+i] = (byte)c;
 102         }
 103         return i;
 104     }
 105 
 106     @Override
 107     public boolean markSupported() {
 108         return false;
 109     }
 110 
 111     @Override
 112     public int available() throws IOException {
 113          // This is only an estimate, since in.available()
 114          // might include CRLFs too ..
 115          return ((in.available() * 3)/4 + (bufsize-index));
 116     }
 117 
 118     /**
 119      * Get the "name" field from the prefix. This is meant to
 120      * be the pathname of the decoded file
 121      *
 122      * @return     name of decoded file
 123      * @exception  IOException  if an I/O error occurs.
 124      */
 125     public String getName() throws IOException {
 126         readPrefix();
 127         return name;
 128     }
 129 
 130     /**
 131      * Get the "mode" field from the prefix. This is the permission
 132      * mode of the source file.
 133      *
 134      * @return     permission mode of source file
 135      * @exception  IOException  if an I/O error occurs.
 136      */
 137     public int getMode() throws IOException {
 138         readPrefix();
 139         return mode;
 140     }
 141 
 142     /**
 143      * UUencoded streams start off with the line:
 144      *  "begin <mode> <filename>"
 145      * Search for this prefix and gobble it up.
 146      */
 147     private void readPrefix() throws IOException {
 148         if (gotPrefix) // got the prefix
 149             return;
 150 
 151         String s;
 152         for (;;) {
 153             // read till we get the prefix: "begin MODE FILENAME"
 154             s = lin.readLine(); // NOTE: readLine consumes CRLF pairs too
 155             if (s == null)
 156                 throw new IOException("UUDecoder error: No Begin");
 157             if (s.regionMatches(true, 0, "begin", 0, 5)) {
 158                 try {
 159                     mode = Integer.parseInt(s.substring(6,9));
 160                 } catch (NumberFormatException ex) {
 161                     throw new IOException("UUDecoder error: " + ex.toString());
 162                 }
 163                 name = s.substring(10);
 164                 gotPrefix = true;
 165                 return;
 166             }
 167         }
 168     }
 169 
 170     private boolean decode() throws IOException {
 171 
 172         if (gotEnd)
 173             return false;
 174         bufsize = 0;
 175         String line;
 176         do {
 177             line = lin.readLine();
 178 
 179             /*
 180              * Improperly encoded data sometimes omits the zero length
 181              * line that starts with a space character, we detect the
 182              * following "end" line here.
 183              */
 184             if (line == null)
 185                 throw new IOException("Missing End");
 186             if (line.regionMatches(true, 0, "end", 0, 3)) {
 187                 gotEnd = true;
 188                 return false;
 189             }
 190         } while (line.length() == 0);
 191         int count = line.charAt(0);
 192         if (count < ' ')
 193             throw new IOException("Buffer format error");
 194 
 195         /*
 196          * The first character in a line is the number of original (not
 197          *  the encoded atoms) characters in the line. Note that all the
 198          *  code below has to handle the <SPACE> character that indicates
 199          *  end of encoded stream.
 200          */
 201         count = (count - ' ') & 0x3f;
 202 
 203         if (count == 0) {
 204             line = lin.readLine();
 205             if (line == null || !line.regionMatches(true, 0, "end", 0, 3))
 206                 throw new IOException("Missing End");
 207             gotEnd = true;
 208             return false;
 209         }
 210 
 211         int need = ((count * 8)+5)/6;
 212 //System.out.println("count " + count + ", need " + need + ", len " + line.length());
 213         if (line.length() < need + 1)
 214             throw new IOException("Short buffer error");
 215 
 216         int i = 1;
 217         byte a, b;
 218         /*
 219          * A correct uuencoder always encodes 3 characters at a time, even
 220          * if there aren't 3 characters left.  But since some people out
 221          * there have broken uuencoders we handle the case where they
 222          * don't include these "unnecessary" characters.
 223          */
 224         while (bufsize < count) {
 225             // continue decoding until we get 'count' decoded chars
 226             a = (byte)((line.charAt(i++) - ' ') & 0x3f);
 227             b = (byte)((line.charAt(i++) - ' ') & 0x3f);
 228             buffer[bufsize++] = (byte)(((a << 2) & 0xfc) | ((b >>> 4) & 3));
 229 
 230             if (bufsize < count) {
 231                 a = b;
 232                 b = (byte)((line.charAt(i++) - ' ') & 0x3f);
 233                 buffer[bufsize++] =
 234                                 (byte)(((a << 4) & 0xf0) | ((b >>> 2) & 0xf));
 235             }
 236 
 237             if (bufsize < count) {
 238                 a = b;
 239                 b = (byte)((line.charAt(i++) - ' ') & 0x3f);
 240                 buffer[bufsize++] = (byte)(((a << 6) & 0xc0) | (b & 0x3f));
 241             }
 242         }
 243         return true;
 244     }
 245 
 246     /*** begin TEST program *****
 247     public static void main(String argv[]) throws Exception {
 248         FileInputStream infile = new FileInputStream(argv[0]);
 249         UUDecoderStream decoder = new UUDecoderStream(infile);
 250         int c;
 251 
 252         try {
 253             while ((c = decoder.read()) != -1)
 254                 System.out.write(c);
 255             System.out.flush();
 256         } catch (Exception e) {
 257             e.printStackTrace();
 258         }
 259     }
 260     **** end TEST program ****/
 261 }