Refine Local Agent.sh use
[aaf/authz.git] / cadi / core / src / main / java / org / onap / aaf / cadi / PropAccess.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  * ===========================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END====================================================
19  *
20  */
21
22 package org.onap.aaf.cadi;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.PrintStream;
29 import java.io.PrintWriter;
30 import java.io.StringWriter;
31 import java.text.SimpleDateFormat;
32 import java.util.ArrayList;
33 import java.util.Date;
34 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.Properties;
37
38 import org.onap.aaf.cadi.config.Config;
39 import org.onap.aaf.cadi.config.SecurityInfo;
40
41 public class PropAccess implements Access {
42     // Sonar says cannot be static... it's ok.  not too many PropAccesses created.
43     private final SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
44
45     public static final Level DEFAULT = Level.AUDIT;
46     
47     private Symm symm;
48     private int level;
49     private Properties props;
50     private List<String> recursionProtection = null;
51     private LogIt logIt;
52     private String name;
53
54     public PropAccess() {
55         logIt = new StreamLogIt(System.out);
56         init(null);
57     }
58     
59     /**
60      * This Constructor soly exists to instantiate Servlet Context Based Logging that will call "init" later.
61      * @param sc
62      */
63     protected PropAccess(Object o) {
64         logIt = new StreamLogIt(System.out);
65         props = new Properties();
66     }
67     
68     public PropAccess(String ... args) {
69         this(System.out,args);
70     }
71     
72     public PropAccess(PrintStream ps, String[] args) {
73         logIt = new StreamLogIt(ps==null?System.out:ps);
74         init(logIt,args);
75     }
76     
77     public PropAccess(LogIt logit, String[] args) {
78         init(logit, args);
79     }
80     
81     public PropAccess(Properties p) {
82         this(System.out,p);
83     }
84     
85     public PropAccess(PrintStream ps, Properties p) {
86         logIt = new StreamLogIt(ps==null?System.out:ps);
87         init(p);
88     }
89     
90     protected void init(final LogIt logIt, final String[] args) {
91         this.logIt = logIt;
92         Properties nprops=new Properties();
93         int eq;
94         for (String arg : args) {
95             if ((eq=arg.indexOf('='))>0) {
96                 nprops.setProperty(arg.substring(0, eq),arg.substring(eq+1));
97             }
98         }
99         init(nprops);
100     }
101     
102     protected void init(Properties p) {
103         // Make sure these two are set before any changes in Logging
104         name = "cadi";
105         level=DEFAULT.maskOf();
106         
107         props = new Properties();
108         // First, load related System Properties
109         for (Entry<Object,Object> es : System.getProperties().entrySet()) {
110             String key = es.getKey().toString();
111             for (String start : new String[] {"cadi_","aaf_","cm_"}) {
112                 if (key.startsWith(start)) {
113                     props.put(key, es.getValue());
114                 }
115             }            
116         }
117         // Second, overlay or fill in with Passed in Props
118         if (p!=null) {
119             props.putAll(p);
120         }
121         
122         // Third, load any Chained Property Files
123         load(props.getProperty(Config.CADI_PROP_FILES));
124         
125         String sLevel = props.getProperty(Config.CADI_LOGLEVEL); 
126         if (sLevel!=null) {
127             level=Level.valueOf(sLevel).maskOf(); 
128         }
129         // Setup local Symmetrical key encryption
130         if (symm==null) {
131             try {
132                 symm = Symm.obtain(this);
133             } catch (CadiException e) {
134                 System.err.append("FATAL ERROR: Cannot obtain Key Information.");
135                 e.printStackTrace(System.err);
136                 System.exit(1);
137             }
138         }
139         
140         name = props.getProperty(Config.CADI_LOGNAME, name);
141         
142         specialConversions();
143     }
144     
145    
146     private void specialConversions() {
147         // Critical - if no Security Protocols set, then set it.  We'll just get messed up if not
148         if (props.get(Config.CADI_PROTOCOLS)==null) {
149             props.setProperty(Config.CADI_PROTOCOLS, SecurityInfo.HTTPS_PROTOCOLS_DEFAULT);
150         }
151         
152         Object temp;
153         temp=props.get(Config.CADI_PROTOCOLS);
154         if (props.get(Config.HTTPS_PROTOCOLS)==null && temp!=null) {
155             props.put(Config.HTTPS_PROTOCOLS, temp);
156         }
157         
158         if (temp!=null) {
159             if ("1.7".equals(System.getProperty("java.specification.version")) 
160                     && (temp==null || (temp instanceof String && ((String)temp).contains("TLSv1.2")))) {
161                 System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT);
162             }
163         }
164     }
165
166     private void load(String cadi_prop_files) {
167         if (cadi_prop_files==null) {
168             return;
169         }
170         String prevKeyFile = props.getProperty(Config.CADI_KEYFILE);
171         int prev = 0, end = cadi_prop_files.length();
172         int idx;
173         String filename;
174         while (prev<end) {
175             idx = cadi_prop_files.indexOf(File.pathSeparatorChar,prev);
176             if (idx<0) {
177                 idx = end;
178             }
179             File file = new File(filename=cadi_prop_files.substring(prev,idx));
180             if (file.exists()) {
181                 printf(Level.INIT,"Loading CADI Properties from %s",file.getAbsolutePath());
182                 try {
183                     FileInputStream fis = new FileInputStream(file);
184                     try {
185                         props.load(fis);
186                         // Recursively Load
187                         String chainProp = props.getProperty(Config.CADI_PROP_FILES);
188                         if (chainProp!=null) {
189                             if (recursionProtection==null) {
190                                 recursionProtection = new ArrayList<>();
191                                 recursionProtection.add(cadi_prop_files);
192                             }
193                             if (!recursionProtection.contains(chainProp)) {
194                                 recursionProtection.add(chainProp);
195                                 load(chainProp); // recurse
196                             }
197                         }
198                     } finally {
199                         fis.close();
200                     }
201                 } catch (Exception e) {
202                     log(e,filename,"cannot be opened");
203                 }
204             } else {
205                 printf(Level.WARN,"Warning: recursive CADI Property %s does not exist",file.getAbsolutePath());
206             }
207             prev = idx+1;
208         }
209         
210         // Trim 
211         for (Entry<Object, Object> es : props.entrySet()) {
212             Object value = es.getValue();
213             if (value instanceof String) {
214                 String trim = ((String)value).trim();
215                 // Remove Beginning/End Quotes, which might be there if mixed with Bash Props
216                 int s = 0, e=trim.length()-1;
217                 if (s<e && trim.charAt(s)=='"' && trim.charAt(e)=='"') {
218                     trim=trim.substring(s+1,e);
219                 }
220                 if (trim!=value) { // Yes, I want OBJECT equals
221                     props.setProperty((String)es.getKey(), trim);
222                 }
223             }
224         }
225         // Reset Symm if Keyfile Changes:
226         String newKeyFile = props.getProperty(Config.CADI_KEYFILE);
227         if ((prevKeyFile!=null && newKeyFile!=null) || (newKeyFile!=null && !newKeyFile.equals(prevKeyFile))) {
228             try {
229                 symm = Symm.obtain(this);
230             } catch (CadiException e) {
231                 System.err.append("FATAL ERROR: Cannot obtain Key Information.");
232                 e.printStackTrace(System.err);
233                 System.exit(1);
234             }
235
236             prevKeyFile=newKeyFile;
237         }
238         
239         String loglevel = props.getProperty(Config.CADI_LOGLEVEL);
240         if (loglevel!=null) {
241             try {
242                 level=Level.valueOf(loglevel).maskOf();
243             } catch (IllegalArgumentException e) {
244                 printf(Level.ERROR,"%s=%s is an Invalid Log Level",Config.CADI_LOGLEVEL,loglevel);
245             }
246         }
247         
248         specialConversions();
249     }
250     
251     @Override
252     public void load(InputStream is) throws IOException {
253         props.load(is);
254         load(props.getProperty(Config.CADI_PROP_FILES));
255     }
256
257     @Override
258     public void log(Level level, Object ... elements) {
259         if (willLog(level)) {
260             logIt.push(level,elements);
261         }
262     }
263
264     protected StringBuilder buildMsg(Level level, Object[] elements) {
265         return buildMsg(name,iso8601,level,elements);
266     }
267
268     public static StringBuilder buildMsg(final String name, final SimpleDateFormat sdf, Level level, Object[] elements) { 
269         StringBuilder sb = new StringBuilder(sdf.format(new Date()));
270         sb.append(' ');
271         sb.append(level.name());
272         sb.append(" [");
273         sb.append(name);
274         
275         int end = elements.length;
276         if (end<=0) {
277             sb.append("] ");
278         } else {
279             int idx = 0;
280             if(elements[idx]!=null  && 
281                 elements[idx] instanceof Integer) {
282                 sb.append('-');
283                 sb.append(elements[idx]);
284                 ++idx;
285             }
286             sb.append("] ");
287             write(true,sb,elements);
288         }
289         return sb;
290     }
291     
292     private static boolean write(boolean first, StringBuilder sb, Object[] elements) {
293         String s;
294         for (Object o : elements) {
295             if (o!=null) {
296                 if(o.getClass().isArray()) {
297                         first = write(first,sb,(Object[])o);
298                 } else {
299                         s=o.toString();
300                         if (first) {
301                             first = false;
302                         } else {
303                             int l = s.length();
304                             if (l>0)    {
305                                 switch(s.charAt(l-1)) {
306                                     case ' ':
307                                         break;
308                                     default:
309                                         sb.append(' ');
310                                 }
311                             }
312                         }
313                         sb.append(s);
314                 }
315             }
316         }
317         return first;
318     }
319
320     @Override
321     public void log(Exception e, Object... elements) {
322         StringWriter sw = new StringWriter();
323         PrintWriter pw = new PrintWriter(sw);
324         pw.println();
325         e.printStackTrace(pw);
326         log(Level.ERROR,elements,sw.toString());
327     }
328
329     @Override
330     public void printf(Level level, String fmt, Object... elements) {
331         if (willLog(level)) {
332             log(level,String.format(fmt, elements));
333         }
334     }
335
336     @Override
337     public void setLogLevel(Level level) {
338         this.level = level.maskOf();
339     }
340
341     @Override
342     public boolean willLog(Level level) {
343         return level.inMask(this.level);
344     }
345
346     @Override
347     public ClassLoader classLoader() {
348         return ClassLoader.getSystemClassLoader();
349     }
350
351     @Override
352     public String getProperty(String tag, String def) {
353         return props.getProperty(tag,def);
354     }
355
356     @Override
357     public String decrypt(String encrypted, boolean anytext) throws IOException {
358         return (encrypted!=null && (anytext==true || encrypted.startsWith(Symm.ENC)))
359             ? symm.depass(encrypted)
360             : encrypted;
361     }
362     
363     public String encrypt(String unencrypted) throws IOException {
364         return Symm.ENC+symm.enpass(unencrypted);
365     }
366
367     //////////////////
368     // Additional
369     //////////////////
370     public String getProperty(String tag) {
371         return props.getProperty(tag);
372     }
373     
374
375     public Properties getProperties() {
376         return props;
377     }
378
379     public void setProperty(String tag, String value) {
380         if (value!=null) {
381             props.put(tag, value);
382             if (Config.CADI_KEYFILE.equals(tag)) {
383                 // reset decryption too
384                 try {
385                     symm = Symm.obtain(this);
386                 } catch (CadiException e) {
387                     System.err.append("FATAL ERROR: Cannot obtain Key Information.");
388                     e.printStackTrace(System.err);
389                     System.exit(1);
390                 }
391             }
392         }
393     }
394
395     public interface LogIt {
396         public void push(Level level, Object ... elements) ;
397     }
398     
399     private class StreamLogIt implements LogIt {
400         private PrintStream ps;
401         
402         public StreamLogIt(PrintStream ps) {
403             this.ps = ps;
404         }
405         @Override
406         public void push(Level level, Object ... elements) {
407             ps.println(buildMsg(level,elements));
408             ps.flush();
409         }
410     }
411
412     public void set(LogIt logit) {
413         logIt = logit;
414     }
415
416     public void setStreamLogIt(PrintStream ps) {
417         logIt = new StreamLogIt(ps);
418     }
419
420     public String toString() {
421         return props.toString();
422     }
423 }