001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.bcel.util;
020
021import java.io.File;
022import java.io.FileNotFoundException;
023import java.io.IOException;
024import java.io.PrintWriter;
025import java.io.UnsupportedEncodingException;
026import java.net.URLEncoder;
027import java.nio.charset.Charset;
028import java.nio.charset.StandardCharsets;
029import java.util.HashSet;
030import java.util.Set;
031
032import org.apache.bcel.Const;
033import org.apache.bcel.Constants;
034import org.apache.bcel.classfile.Attribute;
035import org.apache.bcel.classfile.ClassParser;
036import org.apache.bcel.classfile.ConstantPool;
037import org.apache.bcel.classfile.JavaClass;
038import org.apache.bcel.classfile.Method;
039import org.apache.bcel.classfile.Utility;
040
041/**
042 * Read class file(s) and convert them into HTML files.
043 *
044 * Given a JavaClass object "class" that is in package "package" five files will be created in the specified directory.
045 *
046 * <OL>
047 * <LI>"package"."class".html as the main file which defines the frames for the following subfiles.
048 * <LI>"package"."class"_attributes.html contains all (known) attributes found in the file
049 * <LI>"package"."class"_cp.html contains the constant pool
050 * <LI>"package"."class"_code.html contains the byte code
051 * <LI>"package"."class"_methods.html contains references to all methods and fields of the class
052 * </OL>
053 *
054 * All subfiles reference each other appropriately, for example clicking on a method in the Method's frame will jump to the
055 * appropriate method in the Code frame.
056 */
057public class Class2HTML implements Constants {
058
059    private static String classPackage; // name of package, unclean to make it static, but ...
060    private static String className; // name of current class, ditto
061    private static String classNameRef; // encoded name for links to the current class
062    private static ConstantPool constantPool;
063    private static final Set<String> basicTypes = new HashSet<>();
064    static {
065        basicTypes.add("int");
066        basicTypes.add("short");
067        basicTypes.add("boolean");
068        basicTypes.add("void");
069        basicTypes.add("char");
070        basicTypes.add("byte");
071        basicTypes.add("long");
072        basicTypes.add("double");
073        basicTypes.add("float");
074    }
075
076    /**
077     * The class name comes from the attacker-controlled this_class constant of the parsed class file and is
078     * concatenated into the five output file paths ("dir + className + suffix") and into the report's own
079     * self-referential links (HREF/SRC values). Class file parsing only folds '/' into '.', so Windows separators
080     * ('\\'), drive designators (':') and ".." segments survive and would let a crafted class file write its HTML
081     * output outside the target directory (CWE-22). The '#' and '%' characters are also rejected in output file names.
082     * Accepted names are encoded separately for use in the report's links.
083     *
084     * @param name the class name about to be used as part of a file name and of the report's own links.
085     * @throws IOException Thrown if the name contains a path separator, a Windows-reserved file name character, a
086     *         control character, a '#' or '%', or a ".." sequence.
087     */
088    private static void checkFileNameSafe(final String name) throws IOException {
089        for (int i = 0; i < name.length(); i++) {
090            final char c = name.charAt(i);
091            if (c < ' ' || "\\/:*?\"<>|#%".indexOf(c) >= 0) {
092                throw new IOException("Refusing to write HTML for a class whose name contains the unsafe character (0x"
093                    + Integer.toHexString(c) + "): " + name);
094            }
095        }
096        if (name.contains("..")) {
097            throw new IOException("Refusing to write HTML for a class whose name contains \"..\": " + name);
098        }
099    }
100
101    /**
102     * Main program to convert class files to HTML.
103     *
104     * @param argv command line arguments.
105     * @throws IOException Thrown if an I/O error occurs.
106     */
107    public static void main(final String[] argv) throws IOException {
108        final String[] fileName = new String[argv.length];
109        int files = 0;
110        ClassParser parser = null;
111        JavaClass javaClass = null;
112        String zipFile = null;
113        final char sep = File.separatorChar;
114        String dir = "." + sep; // Where to store HTML files
115        /*
116         * Parse command line arguments.
117         */
118        for (int i = 0; i < argv.length; i++) {
119            if (argv[i].charAt(0) == '-') { // command line switch
120                if (argv[i].equals("-d")) { // Specify target directory, default '.'
121                    dir = argv[++i];
122                    if (!dir.endsWith("" + sep)) {
123                        dir += sep;
124                    }
125                    final File store = new File(dir);
126                    if (!store.isDirectory()) {
127                        final boolean created = store.mkdirs(); // Create target directory if necessary
128                        if (!created && !store.isDirectory()) {
129                            System.out.println("Tried to create the directory " + dir + " but failed");
130                        }
131                    }
132                } else if (argv[i].equals("-zip")) {
133                    zipFile = argv[++i];
134                } else {
135                    System.out.println("Unknown option " + argv[i]);
136                }
137            } else {
138                fileName[files++] = argv[i];
139            }
140        }
141        if (files == 0) {
142            System.err.println("Class2HTML: No input files specified.");
143        } else { // Loop through files ...
144            for (int i = 0; i < files; i++) {
145                System.out.print("Processing " + fileName[i] + "...");
146                if (zipFile == null) {
147                    parser = new ClassParser(fileName[i]); // Create parser object from file
148                } else {
149                    parser = new ClassParser(zipFile, fileName[i]); // Create parser object from ZIP file
150                }
151                javaClass = parser.parse();
152                new Class2HTML(javaClass, dir);
153                System.out.println("Done.");
154            }
155        }
156    }
157
158    /**
159     * Utility method that converts a class reference in the constant pool, that is, an index to a string.
160     */
161    static String referenceClass(final int index) {
162        String str = constantPool.getConstantString(index, Const.CONSTANT_Class);
163        str = Utility.compactClassName(str);
164        str = Utility.compactClassName(str, classPackage + ".", true);
165        return "<A HREF=\"" + classNameRef + "_cp.html#cp" + index + "\" TARGET=ConstantPool>" + toHTML(str) + "</A>";
166    }
167
168    static String referenceType(final String type) {
169        String shortType = Utility.compactClassName(type);
170        shortType = Utility.compactClassName(shortType, classPackage + ".", true);
171        final int index = type.indexOf('['); // Type is an array?
172        String baseType = type;
173        if (index > -1) {
174            baseType = type.substring(0, index); // Tack of the '['
175        }
176        // test for basic type
177        if (basicTypes.contains(baseType)) {
178            return "<FONT COLOR=\"#00FF00\">" + type + "</FONT>";
179        }
180        return "<A HREF=\"" + toHTMLRef(baseType) + ".html\" TARGET=_top>" + toHTML(shortType) + "</A>";
181    }
182
183    /**
184     * Escapes text for inclusion in an HTML report.
185     *
186     * <p>
187     * Replaces ampersands, angle brackets, double quotes, and single quotes with HTML entities. Line feed and carriage return characters become the literal
188     * sequences {@code \n} and {@code \r}, respectively. All other characters are copied unchanged.
189     * </p>
190     *
191     * @param str the non-null text to escape.
192     * @return the HTML-escaped text.
193     * @throws NullPointerException if {@code str} is null.
194     * @see #toHTMLRef(String)
195     */
196    static String toHTML(final String str) {
197        final StringBuilder buf = new StringBuilder();
198        for (int i = 0; i < str.length(); i++) {
199            final char ch;
200            switch (ch = str.charAt(i)) {
201            case '&':
202                buf.append("&amp;");
203                break;
204            case '<':
205                buf.append("&lt;");
206                break;
207            case '>':
208                buf.append("&gt;");
209                break;
210            case '"':
211                buf.append("&quot;");
212                break;
213            case '\'':
214                buf.append("&#39;");
215                break;
216            case '\n':
217                buf.append("\\n");
218                break;
219            case '\r':
220                buf.append("\\r");
221                break;
222            default:
223                buf.append(ch);
224            }
225        }
226        return buf.toString();
227    }
228
229    /**
230     * Encodes a class or type name as a file-name component in an HTML report link.
231     *
232     * <p>
233     * Replaces colons with underscores, then percent-encodes the name using UTF-8. Spaces become {@code %20}, and HTML metacharacters are percent-encoded.
234     * The caller appends report suffixes and URL fragments to the encoded name.
235     * </p>
236     *
237     * @param str the non-null class or type name to encode.
238     * @return the encoded file-name component.
239     * @throws NullPointerException if {@code str} is null.
240     * @see #toHTML(String)
241     */
242    static String toHTMLRef(final String str) {
243        try {
244            return URLEncoder.encode(str.replace(':', '_'), StandardCharsets.UTF_8.name()).replace("+", "%20");
245        } catch (final UnsupportedEncodingException ex) {
246            throw new IllegalStateException(ex);
247        }
248    }
249
250    private final JavaClass javaClass; // current class object
251
252    private final String dir;
253
254    /**
255     * Writes contents of the given JavaClass into HTML files.
256     *
257     * @param javaClass The class to write.
258     * @param dir The directory to put the files in.
259     * @throws IOException Thrown when an I/O exception of some sort has occurred.
260     */
261    public Class2HTML(final JavaClass javaClass, final String dir) throws IOException {
262        this(javaClass, dir, StandardCharsets.UTF_8);
263    }
264
265    private Class2HTML(final JavaClass javaClass, final String dir, final Charset charset) throws IOException {
266        final Method[] methods = javaClass.getMethods();
267        this.javaClass = javaClass;
268        this.dir = dir;
269        className = javaClass.getClassName(); // Remember full name
270        checkFileNameSafe(className);
271        classNameRef = toHTMLRef(className);
272        constantPool = javaClass.getConstantPool();
273        // Get package name by tacking off everything after the last '.'
274        final int index = className.lastIndexOf('.');
275        if (index > -1) {
276            classPackage = className.substring(0, index);
277        } else {
278            classPackage = ""; // default package
279        }
280        final ConstantHTML constantHtml = new ConstantHTML(dir, className, classPackage, methods, constantPool, charset);
281        /*
282         * Attributes can't be written in one step, so we just open a file which will be written consequently.
283         */
284        try (AttributeHTML attributeHtml = new AttributeHTML(dir, className, constantPool, constantHtml, charset)) {
285            new MethodHTML(dir, className, methods, javaClass.getFields(), constantHtml, attributeHtml, charset);
286            // Write main file (with frames, yuk)
287            writeMainHTML(attributeHtml, charset);
288            new CodeHTML(dir, className, methods, constantPool, constantHtml, charset);
289        }
290    }
291
292    private void writeMainHTML(final AttributeHTML attributeHtml, final Charset charset) throws FileNotFoundException, UnsupportedEncodingException {
293        try (PrintWriter file = new PrintWriter(dir + className + ".html", charset.name())) {
294            // @formatter:off
295            file.println("<HTML>\n"
296                + "<HEAD><TITLE>Documentation for " + toHTML(className) + "</TITLE></HEAD>\n"
297                + "<FRAMESET BORDER=1 cols=\"30%,*\">\n"
298                + "<FRAMESET BORDER=1 rows=\"80%,*\">\n"
299                + "<FRAME NAME=\"ConstantPool\" SRC=\"" + classNameRef + "_cp.html" + "\"\n"
300                + "MARGINWIDTH=\"0\" "
301                + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n"
302                + "<FRAME NAME=\"Attributes\" SRC=\"" + classNameRef + "_attributes.html\"\n"
303                + " MARGINWIDTH=\"0\" MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n"
304                + "</FRAMESET>\n"
305                + "<FRAMESET BORDER=1 rows=\"80%,*\">\n"
306                + "<FRAME NAME=\"Code\" SRC=\"" + classNameRef + "_code.html\"\n"
307                + " MARGINWIDTH=0 "
308                + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n"
309                + "<FRAME NAME=\"Methods\" SRC=\"" + classNameRef + "_methods.html\"\n"
310                + " MARGINWIDTH=0 "
311                + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n"
312                + "</FRAMESET></FRAMESET></HTML>");
313            // @formatter:on
314        }
315        final Attribute[] attributes = javaClass.getAttributes();
316        for (int i = 0; i < attributes.length; i++) {
317            attributeHtml.writeAttribute(attributes[i], "class" + i);
318        }
319    }
320}