View Javadoc
1   /*
2    * Copyright (c) 1998, 2012, 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  package sun.security.util;
27  
28  import java.math.BigInteger;
29  import java.util.regex.Pattern;
30  import java.util.regex.Matcher;
31  import java.util.Locale;
32  
33  /**
34   * A utility class for debuging.
35   *
36   * @author Roland Schemers
37   */
38  public class Debug {
39  
40      private String prefix;
41  
42      private static String args;
43  
44      static {
45          args = java.security.AccessController.doPrivileged
46                  (new sun.security.action.GetPropertyAction
47                  ("java.security.debug"));
48  
49          String args2 = java.security.AccessController.doPrivileged
50                  (new sun.security.action.GetPropertyAction
51                  ("java.security.auth.debug"));
52  
53          if (args == null) {
54              args = args2;
55          } else {
56              if (args2 != null)
57                 args = args + "," + args2;
58          }
59  
60          if (args != null) {
61              args = marshal(args);
62              if (args.equals("help")) {
63                  Help();
64              }
65          }
66      }
67  
68      public static void Help()
69      {
70          System.err.println();
71          System.err.println("all           turn on all debugging");
72          System.err.println("access        print all checkPermission results");
73          System.err.println("certpath      PKIX CertPathBuilder and");
74          System.err.println("              CertPathValidator debugging");
75          System.err.println("combiner      SubjectDomainCombiner debugging");
76          System.err.println("gssloginconfig");
77          System.err.println("              GSS LoginConfigImpl debugging");
78          System.err.println("configfile    JAAS ConfigFile loading");
79          System.err.println("configparser  JAAS ConfigFile parsing");
80          System.err.println("jar           jar verification");
81          System.err.println("logincontext  login context results");
82          System.err.println("jca           JCA engine class debugging");
83          System.err.println("policy        loading and granting");
84          System.err.println("provider      security provider debugging");
85          System.err.println("pkcs11        PKCS11 session manager debugging");
86          System.err.println("pkcs11keystore");
87          System.err.println("              PKCS11 KeyStore debugging");
88          System.err.println("sunpkcs11     SunPKCS11 provider debugging");
89          System.err.println("scl           permissions SecureClassLoader assigns");
90          System.err.println("ts            timestamping");
91          System.err.println();
92          System.err.println("The following can be used with access:");
93          System.err.println();
94          System.err.println("stack         include stack trace");
95          System.err.println("domain        dump all domains in context");
96          System.err.println("failure       before throwing exception, dump stack");
97          System.err.println("              and domain that didn't have permission");
98          System.err.println();
99          System.err.println("The following can be used with stack and domain:");
100         System.err.println();
101         System.err.println("permission=<classname>");
102         System.err.println("              only dump output if specified permission");
103         System.err.println("              is being checked");
104         System.err.println("codebase=<URL>");
105         System.err.println("              only dump output if specified codebase");
106         System.err.println("              is being checked");
107 
108         System.err.println();
109         System.err.println("Note: Separate multiple options with a comma");
110         System.exit(0);
111     }
112 
113 
114     /**
115      * Get a Debug object corresponding to whether or not the given
116      * option is set. Set the prefix to be the same as option.
117      */
118 
119     public static Debug getInstance(String option)
120     {
121         return getInstance(option, option);
122     }
123 
124     /**
125      * Get a Debug object corresponding to whether or not the given
126      * option is set. Set the prefix to be prefix.
127      */
128     public static Debug getInstance(String option, String prefix)
129     {
130         if (isOn(option)) {
131             Debug d = new Debug();
132             d.prefix = prefix;
133             return d;
134         } else {
135             return null;
136         }
137     }
138 
139     /**
140      * True if the system property "security.debug" contains the
141      * string "option".
142      */
143     public static boolean isOn(String option)
144     {
145         if (args == null)
146             return false;
147         else {
148             if (args.indexOf("all") != -1)
149                 return true;
150             else
151                 return (args.indexOf(option) != -1);
152         }
153     }
154 
155     /**
156      * print a message to stderr that is prefixed with the prefix
157      * created from the call to getInstance.
158      */
159 
160     public void println(String message)
161     {
162         System.err.println(prefix + ": "+message);
163     }
164 
165     /**
166      * print a blank line to stderr that is prefixed with the prefix.
167      */
168 
169     public void println()
170     {
171         System.err.println(prefix + ":");
172     }
173 
174     /**
175      * print a message to stderr that is prefixed with the prefix.
176      */
177 
178     public static void println(String prefix, String message)
179     {
180         System.err.println(prefix + ": "+message);
181     }
182 
183     /**
184      * return a hexadecimal printed representation of the specified
185      * BigInteger object. the value is formatted to fit on lines of
186      * at least 75 characters, with embedded newlines. Words are
187      * separated for readability, with eight words (32 bytes) per line.
188      */
189     public static String toHexString(BigInteger b) {
190         String hexValue = b.toString(16);
191         StringBuffer buf = new StringBuffer(hexValue.length()*2);
192 
193         if (hexValue.startsWith("-")) {
194             buf.append("   -");
195             hexValue = hexValue.substring(1);
196         } else {
197             buf.append("    ");     // four spaces
198         }
199         if ((hexValue.length()%2) != 0) {
200             // add back the leading 0
201             hexValue = "0" + hexValue;
202         }
203         int i=0;
204         while (i < hexValue.length()) {
205             // one byte at a time
206             buf.append(hexValue.substring(i, i+2));
207             i+=2;
208             if (i!= hexValue.length()) {
209                 if ((i%64) == 0) {
210                     buf.append("\n    ");     // line after eight words
211                 } else if (i%8 == 0) {
212                     buf.append(" ");     // space between words
213                 }
214             }
215         }
216         return buf.toString();
217     }
218 
219     /**
220      * change a string into lower case except permission classes and URLs.
221      */
222     private static String marshal(String args) {
223         if (args != null) {
224             StringBuffer target = new StringBuffer();
225             StringBuffer source = new StringBuffer(args);
226 
227             // obtain the "permission=<classname>" options
228             // the syntax of classname: IDENTIFIER.IDENTIFIER
229             // the regular express to match a class name:
230             // "[a-zA-Z_$][a-zA-Z0-9_$]*([.][a-zA-Z_$][a-zA-Z0-9_$]*)*"
231             String keyReg = "[Pp][Ee][Rr][Mm][Ii][Ss][Ss][Ii][Oo][Nn]=";
232             String keyStr = "permission=";
233             String reg = keyReg +
234                 "[a-zA-Z_$][a-zA-Z0-9_$]*([.][a-zA-Z_$][a-zA-Z0-9_$]*)*";
235             Pattern pattern = Pattern.compile(reg);
236             Matcher matcher = pattern.matcher(source);
237             StringBuffer left = new StringBuffer();
238             while (matcher.find()) {
239                 String matched = matcher.group();
240                 target.append(matched.replaceFirst(keyReg, keyStr));
241                 target.append("  ");
242 
243                 // delete the matched sequence
244                 matcher.appendReplacement(left, "");
245             }
246             matcher.appendTail(left);
247             source = left;
248 
249             // obtain the "codebase=<URL>" options
250             // the syntax of URL is too flexible, and here assumes that the
251             // URL contains no space, comma(','), and semicolon(';'). That
252             // also means those characters also could be used as separator
253             // after codebase option.
254             // However, the assumption is incorrect in some special situation
255             // when the URL contains comma or semicolon
256             keyReg = "[Cc][Oo][Dd][Ee][Bb][Aa][Ss][Ee]=";
257             keyStr = "codebase=";
258             reg = keyReg + "[^, ;]*";
259             pattern = Pattern.compile(reg);
260             matcher = pattern.matcher(source);
261             left = new StringBuffer();
262             while (matcher.find()) {
263                 String matched = matcher.group();
264                 target.append(matched.replaceFirst(keyReg, keyStr));
265                 target.append("  ");
266 
267                 // delete the matched sequence
268                 matcher.appendReplacement(left, "");
269             }
270             matcher.appendTail(left);
271             source = left;
272 
273             // convert the rest to lower-case characters
274             target.append(source.toString().toLowerCase(Locale.ENGLISH));
275 
276             return target.toString();
277         }
278 
279         return null;
280     }
281 
282     private final static char[] hexDigits = "0123456789abcdef".toCharArray();
283 
284     public static String toString(byte[] b) {
285         if (b == null) {
286             return "(null)";
287         }
288         StringBuilder sb = new StringBuilder(b.length * 3);
289         for (int i = 0; i < b.length; i++) {
290             int k = b[i] & 0xff;
291             if (i != 0) {
292                 sb.append(':');
293             }
294             sb.append(hexDigits[k >>> 4]);
295             sb.append(hexDigits[k & 0xf]);
296         }
297         return sb.toString();
298     }
299 
300 }