Adjust Agent for none K8s
[aaf/authz.git] / cadi / aaf / src / main / java / org / onap / aaf / cadi / configure / Agent.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.configure;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.net.ConnectException;
29 import java.net.HttpURLConnection;
30 import java.net.InetAddress;
31 import java.net.URISyntaxException;
32 import java.net.UnknownHostException;
33 import java.nio.file.Files;
34 import java.security.KeyPair;
35 import java.security.KeyStore;
36 import java.security.cert.X509Certificate;
37 import java.util.ArrayDeque;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.Deque;
41 import java.util.GregorianCalendar;
42 import java.util.HashMap;
43 import java.util.Iterator;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Map.Entry;
47 import java.util.Properties;
48
49 import org.onap.aaf.cadi.Access;
50 import org.onap.aaf.cadi.CadiException;
51 import org.onap.aaf.cadi.CmdLine;
52 import org.onap.aaf.cadi.LocatorException;
53 import org.onap.aaf.cadi.PropAccess;
54 import org.onap.aaf.cadi.Symm;
55 import org.onap.aaf.cadi.aaf.client.ErrMessage;
56 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
57 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
58 import org.onap.aaf.cadi.client.Future;
59 import org.onap.aaf.cadi.client.Rcli;
60 import org.onap.aaf.cadi.client.Retryable;
61 import org.onap.aaf.cadi.config.Config;
62 import org.onap.aaf.cadi.config.RegistrationPropHolder;
63 import org.onap.aaf.cadi.config.SecurityInfoC;
64 import org.onap.aaf.cadi.http.HBasicAuthSS;
65 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
66 import org.onap.aaf.cadi.sso.AAFSSO;
67 import org.onap.aaf.cadi.util.Chmod;
68 import org.onap.aaf.cadi.util.FQI;
69 import org.onap.aaf.misc.env.APIException;
70 import org.onap.aaf.misc.env.Data.TYPE;
71 import org.onap.aaf.misc.env.Env;
72 import org.onap.aaf.misc.env.TimeTaken;
73 import org.onap.aaf.misc.env.Trans;
74 import org.onap.aaf.misc.env.util.Chrono;
75 import org.onap.aaf.misc.env.util.Split;
76 import org.onap.aaf.misc.rosetta.env.RosettaDF;
77 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
78
79 import aaf.v2_0.Perm;
80 import aaf.v2_0.Perms;
81 import certman.v1_0.Artifacts;
82 import certman.v1_0.Artifacts.Artifact;
83 import certman.v1_0.CertInfo;
84 import certman.v1_0.CertificateRequest;
85 import locate.v1_1.Configuration;
86 import locate.v1_1.Configuration.Props;
87
88 public class Agent {
89     private static final String AGENT_LOAD_URLS = "Agent:loadURLs";
90         private static final String HASHES = "################################################################";
91     private static final String PRINT = "print";
92     private static final String FILE = "file";
93     public static final String PKCS12 = "pkcs12";
94     public static final String JKS = "jks";
95     private static final String SCRIPT="script";
96     
97     private static final String CM_VER = "1.0";
98     public static final int PASS_SIZE = 24;
99     private static int TIMEOUT;
100     
101     private static RosettaDF<CertificateRequest> reqDF;
102     private static RosettaDF<CertInfo> certDF;
103     private static RosettaDF<Artifacts> artifactsDF;
104     private static RosettaDF<Configuration> configDF;
105     private static RosettaDF<Perms> permDF;
106     private static ErrMessage errMsg;
107     private static Map<String,PlaceArtifact> placeArtifact;
108     private static RosettaEnv env;
109     
110     private static boolean doExit;
111     private static AAFCon<?> aafcon;
112     
113     private static List<String> CRED_TAGS = Arrays.asList(new String[] {
114             Config.CADI_KEYFILE,
115             Config.AAF_APPID, Config.AAF_APPPASS,
116             Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
117             Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
118             Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
119             });
120     private static List<String> LOC_TAGS = Arrays.asList(new String[] {
121                 Config.CADI_LATITUDE, Config.CADI_LONGITUDE
122                 });
123     // Note: This is set by loadURLs. Use that function as singleton, not directly.
124         private static Map<String,String> aaf_urls = null;
125
126
127     public static void main(String[] args) {
128         int exitCode = 0;
129         doExit = true;
130         if (args.length>0 && "cadi".equals(args[0])) {
131             String[] newArgs = new String[args.length-1];
132             System.arraycopy(args, 1, newArgs, 0, newArgs.length);
133             if (newArgs.length==0) {
134                 System.out.println(HASHES);
135                 System.out.println("Note: Cadi CmdLine is a separate component.  When running with\n\t"
136                         + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
137                 System.out.println(HASHES);
138             }
139             CmdLine.main(newArgs);
140         } else {
141             try {
142                 AAFSSO aafsso=null;
143                 PropAccess access=null; 
144                 
145                 String hasEtc = null;
146                 for(String a : args) {
147                         if(a.startsWith(Config.CADI_PROP_FILES)) {
148                                 access = new PropAccess(args);
149                                 break;
150                         } else if(a.startsWith(Config.CADI_ETCDIR)) {
151                                 int idx = a.indexOf('=');
152                                 if(idx>=0 && idx<a.length()) {
153                                         hasEtc = a.substring(idx+1);
154                                 }
155                         }
156                 }
157                 
158                 if(access==null) {
159                         if(args.length>1 && args[1].contains("@")) {
160                                 String domain = FQI.reverseDomain(args[1]);
161                                 if(domain!=null) {
162                                         if(hasEtc==null) {
163                                                 hasEtc = ".";
164                                         }
165                                         File etc = new File(hasEtc);
166                                         if(etc.exists()) {
167                                                 File nsprops = new File(etc,domain+".props");
168                                                 if(nsprops.exists()) {
169                                                         access = new PropAccess(new String[] {Config.CADI_PROP_FILES+'='+nsprops.getAbsolutePath()});
170                                                 }
171                                         }
172                                 }
173                         } 
174                 }
175                 
176                 if(access==null) {
177                         for(Entry<Object, Object> es : System.getProperties().entrySet()) {
178                                 if(Config.CADI_PROP_FILES.equals(es.getKey())) {
179                                         access = new PropAccess();
180                                 }
181                         }
182                 }
183
184                                 // When using Config file, check if Cred Exists, and if not, work with Deployer.
185                                 if(access!=null && !"config".equals(args[0]) && access.getProperty(Config.AAF_APPPASS)==null && access.getProperty(Config.CADI_ALIAS)==null) {
186                                         // not enough credentials to use Props.  Use AAFSSO 
187                                         access = null;
188                                 }
189
190                 if(access==null) {
191                         if (args.length>1 && args[0].equals("validate") ) {
192                             int idx = args[1].indexOf('=');
193                             aafsso = null;
194                             access = new PropAccess(
195                                         (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
196                                         '='+
197                                         (idx<0?args[1]:args[1].substring(idx+1)));
198                         } else {
199                             aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
200                                 @Override
201                                 public Properties process(String[] args, Properties props) {
202                                     if (args.length>1) {
203                                         if (!args[0].equals("keypairgen")) {
204                                             props.put(Config.AAF_APPID, args[1]);
205                                         }    
206                                     }
207                                     return props;
208                                 }
209                             });
210                             access = aafsso.access();
211                         }
212                 }
213                     
214                 if (aafsso!=null && aafsso.loginOnly()) {
215                     aafsso.setLogDefault();
216                     aafsso.writeFiles();
217                     System.out.println("AAF SSO information created in ~/.aaf");
218                 } else {
219                     env = new RosettaEnv(access.getProperties());
220                     Deque<String> cmds = new ArrayDeque<String>();
221                     for (String p : args) {
222                         int eq;
223                         if ("-noexit".equalsIgnoreCase(p)) {
224                             doExit = false;
225                         } else if ((eq=p.indexOf('=')) < 0) {
226                             cmds.add(p);
227                         } else {
228                                 access.setProperty(p.substring(0,eq), p.substring(eq+1));
229                         }
230                     }
231                     
232                     if (cmds.size()==0) {
233                         if (aafsso!=null) {
234                             aafsso.setLogDefault();
235                         }
236                         // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
237                         System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
238                         System.out.println("   create     <FQI> [<machine>]");
239                         System.out.println("   read       <FQI> [<machine>]");
240                         System.out.println("   update     <FQI> [<machine>]");
241                         System.out.println("   delete     <FQI> [<machine>]");
242                         System.out.println("   copy       <FQI> <machine> <newmachine>[,<newmachine>]*");
243                         System.out.println("   place      <FQI> [<machine>]");
244                         System.out.println("   showpass   <FQI> [<machine>]");
245                         System.out.println("   check      <FQI> [<machine>]");
246                         System.out.println("   keypairgen <FQI>");
247                         System.out.println("   config     <FQI>");
248                         System.out.println("   validate   <NS>.props>");
249                         System.out.println("   --- Additional Tool Access ---");
250                         System.out.println("     ** Type with no params for Tool Help");
251                         System.out.println("     ** If using with Agent, preface with \"cadi\"");
252                         System.out.println("   cadi <cadi tool params, see -?>");
253                         
254                         if (doExit) {
255                             System.exit(1);
256                         }
257                     }
258                     
259                     TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
260                 
261                     reqDF = env.newDataFactory(CertificateRequest.class);
262                     artifactsDF = env.newDataFactory(Artifacts.class);
263                     certDF = env.newDataFactory(CertInfo.class);
264                     configDF = env.newDataFactory(Configuration.class);
265                     permDF = env.newDataFactory(Perms.class);
266                     errMsg = new ErrMessage(env);
267         
268                     placeArtifact = new HashMap<>();
269                     placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
270                     placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
271                     placeArtifact.put(FILE, new PlaceArtifactInFiles());
272                     placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
273                     placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
274                     
275                     Trans trans = env.newTrans();
276                     String token;
277                     if ((token=access.getProperty("oauth_token"))!=null) {
278                         trans.setProperty("oauth_token", token);
279                     }
280                     try {
281                         if (aafsso!=null) {
282                         // show Std out again
283                             aafsso.setLogDefault();
284                             aafsso.setStdErrDefault();
285                             
286                             /*urls=*/loadURLs(access);
287                             aafsso.writeFiles();
288                         }
289     
290                         
291     
292                         String cmd = cmds.removeFirst();
293                         switch(cmd) {
294                             case "place":
295                                 placeCerts(trans,aafcon(access),cmds);
296                                 break;
297                             case "create":
298                                 createArtifact(trans, aafcon(access),cmds);
299                                 break;
300                             case "read":
301                                 readArtifact(trans, aafcon(access), cmds);
302                                 break;
303                             case "copy":
304                                 copyArtifact(trans, aafcon(access), cmds);
305                                 break;
306                             case "update":
307                                 updateArtifact(trans, aafcon(access), cmds);
308                                 break;
309                             case "delete":
310                                 deleteArtifact(trans, aafcon(access), cmds);
311                                 break;
312                             case "showpass":
313                                 showPass(trans, aafcon(access), cmds);
314                                 break;
315                             case "keypairgen":
316                                 keypairGen(trans, access, cmds);
317                                 break;
318                             case "config":
319                                 config(trans,access,args,cmds);
320                                 break;
321                             case "validate":
322                                 validate(access);
323                                 break;
324                             case "check":
325                                 try {
326                                     exitCode = check(trans,aafcon(access),cmds);
327                                 } catch (Exception e) {
328                                     exitCode = 1;
329                                     throw e;
330                                 }
331                                 break;
332                             default:
333                                 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
334                         }
335                     } finally {
336                         StringBuilder sb = new StringBuilder();
337                         trans.auditTrail(4, sb, Trans.REMOTE);
338                         if (sb.length()>0) {
339                             trans.info().log("Trans Info\n",sb);
340                         }
341                     }
342                     if (aafsso!=null) {
343                         aafsso.close();
344                     }
345                 }
346             } catch (Exception e) {
347                 e.printStackTrace();
348             }
349         }
350         if (exitCode != 0 && doExit) {
351             System.exit(exitCode);
352         }
353     }
354
355     public synchronized static Map<String,String> loadURLs(Access access) throws UnknownHostException, CadiException {
356                 if(aaf_urls==null) {
357                 Map<String,String> rv = new HashMap<>();
358                 RegistrationPropHolder rph = new RegistrationPropHolder(access, 0);
359                 String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null);
360                 dot_le=dot_le==null?"":'.'+dot_le;
361                 String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
362                 for(String u : new String[] {"locate","aaf","oauth","cm","gui","fs","hello","token","introspect"}) {
363                         String tag;
364                         String append=null;
365                         switch(u) {
366                                 case "aaf":   tag = Config.AAF_URL; break;
367                                 case "locate":tag = Config.AAF_LOCATE_URL; break;
368                                 case "oauth": tag = Config.AAF_URL_OAUTH; break;
369                                 case "token": tag = Config.AAF_OAUTH2_TOKEN_URL; append="/token"; break;
370                                 case "introspect": tag = Config.AAF_OAUTH2_INTROSPECT_URL; append="/introspect"; break;
371                                 case "cm":    tag = Config.AAF_URL_CM; break;
372                                 case "gui":   tag = Config.AAF_URL_GUI; break;
373                                 case "fs":    tag = Config.AAF_URL_FS; break;
374                                 case "hello": tag = Config.AAF_URL_HELLO; break;
375                                 default:
376                                         tag = "aaf_url_" + u;
377                         }
378                         String value;
379                         if((value=access.getProperty(tag,null))==null) {
380                                 String proto = "fs".equals(u)?"http://":"https://";
381                                 String lhost;
382                                 if("locate".equals(u)) {
383                                         lhost=rph.default_fqdn;
384                                 } else {
385                                         lhost=Config.AAF_LOCATE_URL_TAG;
386                                 }
387                                 value = rph.replacements(AGENT_LOAD_URLS,
388                                                 proto + lhost + "/%CNS.%AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version, 
389                                                 null,dot_le);
390                                 if(append!=null) {
391                                         value+=append;
392                                 }
393                         } else {
394                                 value = rph.replacements(AGENT_LOAD_URLS, value,null,dot_le);
395                         }
396                         rv.put(tag, value);
397                 };
398                 aaf_urls = rv;
399                 }
400             return aaf_urls;
401         }
402
403         public static void fillMissing(PropAccess access, Map<String, String> map) {
404                 for(Entry<String, String> es : map.entrySet()) {
405                         if(access.getProperty(es.getKey())==null) {
406                                 access.setProperty(es.getKey(),es.getValue());
407                         }
408                 }
409         }
410
411         private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
412         if (aafcon==null) {
413             aafcon = new AAFConHttp(access,Config.AAF_URL_CM);
414         }
415         return aafcon;
416     }
417
418     private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
419         String value;
420         if ((value=pa.getProperty(tag))==null) {
421             if (secure) {
422                 value = new String(AAFSSO.cons.readPassword(prompt, def));
423             } else {
424                 value = AAFSSO.cons.readLine(prompt,def).trim();
425             }
426             if (value!=null) {
427                 if (value.length()>0) {
428                     pa.setProperty(tag,value);
429                     env.setProperty(tag,value);
430                 } else if (def.length==1) {
431                     value=def[0].toString();
432                     pa.setProperty(tag,value);
433                     env.setProperty(tag,value);
434                 }
435             }
436         }
437         return value;
438     }
439
440     private static String fqi(Deque<String> cmds) {
441         if (cmds.size()<1) {
442             String alias = env.getProperty(Config.CADI_ALIAS);
443             if(alias==null) {
444                 alias = env.getProperty(Config.AAF_APPID);
445             }
446             return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
447         }
448         return cmds.removeFirst();    
449     }
450
451     private static String machine(Deque<String> cmds) throws UnknownHostException {
452         if (cmds.size()>0) {
453             return cmds.removeFirst();
454         } else {
455             String mach = env.getProperty(Config.HOSTNAME);
456             return mach!=null?mach:InetAddress.getLocalHost().getHostName();
457         }
458     }
459
460     private static String[] machines(Deque<String> cmds)  {
461         String machines;
462         if (cmds.size()>0) {
463             machines = cmds.removeFirst();
464         } else {
465             machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
466         }
467         return Split.split(',', machines);
468     }
469
470     private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
471         final String mechID = fqi(cmds);
472         final String machine = machine(cmds);
473
474         Artifacts artifacts = new Artifacts();
475         Artifact arti = new Artifact();
476         artifacts.getArtifact().add(arti);
477         arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
478         arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
479         arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
480         
481         String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
482         for (String s : Split.splitTrim(',', resp)) {
483             arti.getType().add(s);
484         }
485         // Always do Script
486         if (!resp.contains(SCRIPT)) {
487             arti.getType().add(SCRIPT);
488         }
489
490         // Note: Sponsor is set on Creation by CM
491         String configRootName = FQI.reverseDomain(arti.getMechid());
492         arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
493         arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
494         arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
495         arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
496         arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
497         
498         TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
499         try {
500             Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
501             if (future.get(TIMEOUT)) {
502                 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
503             } else {
504                 trans.error().printf("Call to AAF Certman failed, %s",
505                     errMsg.toMsg(future));
506             }
507         } finally {
508             tt.done();
509         }
510     }
511
512     private static String toNotification(String notification) {
513         if (notification==null) {
514             notification="";
515         } else if (notification.length()>0) {
516             if (notification.indexOf(':')<0) {
517                 notification = "mailto:" + notification;
518             }
519         }
520         return notification;
521     }
522     
523
524     private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
525         String mechID = fqi(cmds);
526         String machine = machine(cmds);
527
528         TimeTaken tt = trans.start("Read Artifact", Env.SUB);
529         try {
530             Future<Artifacts> future = aafcon.client(CM_VER)
531                     .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
532     
533             if (future.get(TIMEOUT)) {
534                 boolean printed = false;
535                 for (Artifact a : future.value.getArtifact()) {
536                     AAFSSO.cons.printf("AppID:          %s\n",a.getMechid()); 
537                     AAFSSO.cons.printf("  Sponsor:       %s\n",a.getSponsor()); 
538                     AAFSSO.cons.printf("Machine:         %s\n",a.getMachine()); 
539                     AAFSSO.cons.printf("CA:              %s\n",a.getCa()); 
540                     StringBuilder sb = new StringBuilder();
541                     boolean first = true;
542                     for (String t : a.getType()) {
543                         if (first) {first=false;}
544                         else{sb.append(',');}
545                         sb.append(t);
546                     }
547                     AAFSSO.cons.printf("Types:           %s\n",sb);
548                     AAFSSO.cons.printf("Namespace:       %s\n",a.getNs()); 
549                     AAFSSO.cons.printf("Directory:       %s\n",a.getDir());
550                     AAFSSO.cons.printf("O/S User:        %s\n",a.getOsUser());
551                     AAFSSO.cons.printf("Renew Days:      %d\n",a.getRenewDays());
552                     AAFSSO.cons.printf("Notification     %s\n",a.getNotification());
553                     printed = true;
554                 }
555                 if (!printed) {
556                     AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
557                 }
558             } else {
559                 trans.error().log(errMsg.toMsg(future));
560             }
561         } finally {
562             tt.done();
563         }
564     }
565     
566     private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
567         String mechID = fqi(cmds);
568         String machine = machine(cmds);
569         String[] newmachs = machines(cmds);
570         if (machine==null || newmachs == null) {
571             trans.error().log("No machines listed to copy to");
572         } else {
573             TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
574             try {
575                 Future<Artifacts> future = aafcon.client(CM_VER)
576                         .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
577             
578                 if (future.get(TIMEOUT)) {
579                     boolean printed = false;
580                     for (Artifact a : future.value.getArtifact()) {
581                         for (String m : newmachs) {
582                             a.setMachine(m);
583                             Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
584                             if (fup.get(TIMEOUT)) {
585                                 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
586                             } else {
587                                 trans.error().printf("Call to AAF Certman failed, %s",
588                                     errMsg.toMsg(fup));
589                             }
590     
591                             printed = true;
592                         }
593                     }
594                     if (!printed) {
595                         AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
596                     }
597                 } else {
598                     trans.error().log(errMsg.toMsg(future));
599                 }
600             } finally {
601                 tt.done();
602             }
603         }
604     }
605
606     private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
607         String mechID = fqi(cmds);
608         String machine = machine(cmds);
609
610         TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
611         try {
612             Future<Artifacts> fread = aafcon.client(CM_VER)
613                     .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
614     
615             if (fread.get(TIMEOUT)) {
616                 Artifacts artifacts = new Artifacts();
617                 for (Artifact a : fread.value.getArtifact()) {
618                     Artifact arti = new Artifact();
619                     artifacts.getArtifact().add(arti);
620                     
621                     AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
622                     arti.setMechid(a.getMechid());
623                     arti.setMachine(a.getMachine());
624                     arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
625                     StringBuilder sb = new StringBuilder();
626                     boolean first = true;
627                     for (String t : a.getType()) {
628                         if (first) {first=false;}
629                         else{sb.append(',');}
630                         sb.append(t);
631                     }
632     
633                     String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
634                     for (String s : Split.splitTrim(',', resp)) {
635                         arti.getType().add(s);
636                     }
637                     // Always do Script
638                     if (!resp.contains(SCRIPT)) {
639                         arti.getType().add(SCRIPT);
640                     }
641
642                     // Note: Sponsor is set on Creation by CM
643                     arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
644                     arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
645                     arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
646                     arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
647                     arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
648     
649                 }
650                 if (artifacts.getArtifact().size()==0) {
651                     AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
652                 } else {
653                     Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
654                     if (fup.get(TIMEOUT)) {
655                         trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
656                     } else {
657                         trans.error().printf("Call to AAF Certman failed, %s",
658                             errMsg.toMsg(fup));
659                     }
660                 }
661             } else {
662                 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
663                         errMsg.toMsg(fread),mechID,machine);
664             }
665         } finally {
666             tt.done();
667         }
668     }
669     
670     private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
671         String mechid = fqi(cmds);
672         String machine = machine(cmds);
673         
674         TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
675         try {
676             Future<Void> future = aafcon.client(CM_VER)
677                     .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
678     
679             if (future.get(TIMEOUT)) {
680                 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
681             } else {
682                 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
683                     errMsg.toMsg(future),mechid,machine);
684             }
685         } finally {
686             tt.done();
687         }
688     }
689
690     
691
692     private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
693         boolean rv = false;
694         String mechID = fqi(cmds);
695         String machine = machine(cmds);
696         String[] fqdns = Split.split(':', machine);
697         String key;
698         if (fqdns.length>1) {
699             key = fqdns[0];
700             machine = fqdns[1];
701         } else {
702             key = machine;
703         }
704         
705         TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
706         try {
707             Future<Artifacts> acf = aafcon.client(CM_VER)
708                     .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
709             if (acf.get(TIMEOUT)) {
710                 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
711                     AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
712                 } else {
713                     for (Artifact a : acf.value.getArtifact()) {
714                         String osID = System.getProperty("user.name");
715                         if (a.getOsUser().equals(osID)) {
716                             CertificateRequest cr = new CertificateRequest();
717                             cr.setMechid(a.getMechid());
718                             cr.setSponsor(a.getSponsor());
719                             for (int i=0;i<fqdns.length;++i) {
720                                 cr.getFqdns().add(fqdns[i]);
721                             }
722                             Future<String> f = aafcon.client(CM_VER)
723                                     .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
724                             if (f.get(TIMEOUT)) {
725                                 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
726                                 for (String type : a.getType()) {
727                                     PlaceArtifact pa = placeArtifact.get(type);
728                                     if (pa!=null) {
729                                         if (rv = pa.place(trans, capi, a,machine)) {
730                                             notifyPlaced(a,rv);
731                                         }
732                                     }
733                                 }
734                                 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
735                             } else {
736                                 trans.error().log(errMsg.toMsg(f));
737                             }
738                         } else {
739                             trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
740                         }
741                     }
742                 }
743                 PropHolder.writeAll();
744             } else {
745                 trans.error().log(errMsg.toMsg(acf));
746             }
747         } finally {
748             tt.done();
749         }
750         return rv;
751     }
752     
753     private static void notifyPlaced(Artifact a, boolean rv) {
754     }
755
756     private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
757         String mechID = fqi(cmds);
758         String machine = machine(cmds);
759
760         TimeTaken tt = trans.start("Show Password", Env.REMOTE);
761         try {
762             Future<Artifacts> acf = aafcon.client(CM_VER)
763                     .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
764             if (acf.get(TIMEOUT)) {
765                 // Have to wait for JDK 1.7 source...
766                 //switch(artifact.getType()) {
767                 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
768                     AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
769                 } else {
770                     String id = aafcon.defID();
771                     boolean allowed;
772                     for (Artifact a : acf.value.getArtifact()) {
773                         allowed = id!=null && (id.equals(a.getSponsor()) ||
774                                 (id.equals(a.getMechid()) 
775                                         && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
776                         if (!allowed) {
777                             Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" + 
778                                     a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
779                             if (pf.get(TIMEOUT)) {
780                                 allowed = true;
781                             } else {
782                                 trans.error().log(errMsg.toMsg(pf));
783                             }
784                         }
785                         if (allowed) {
786                             File dir = new File(a.getDir());
787                             Properties props = new Properties();
788                             FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
789                             try {
790                                 props.load(fis);
791                                 File chalFile = new File(dir,a.getNs()+".chal");
792                                 if(chalFile.exists()) {
793                                     fis.close();
794                                         fis = new FileInputStream(chalFile);
795                                         props.load(fis);
796                                 }
797                             } finally {
798                                 fis.close();
799                             }
800                             
801                             File f = new File(dir,a.getNs()+".keyfile");
802                             if (f.exists()) {
803                                 Symm symm = ArtifactDir.getSymm(f);
804                                 
805                                 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
806                                     Entry<Object,Object> en = iter.next();
807                                     if (en.getValue().toString().startsWith("enc:")) {
808                                         System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
809                                     }
810                                 }
811                             } else {
812                                 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
813                                         f.getAbsolutePath(),a.getMechid(), a.getMachine());
814                             }
815                         }
816                     }
817                 }
818             } else {
819                 trans.error().log(errMsg.toMsg(acf));
820             }
821         } finally {
822             tt.done();
823         }
824
825     }
826     
827     private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
828         final String fqi = fqi(cmds);
829         final String ns = FQI.reverseDomain(fqi);
830         File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
831         File f = new File(dir,ns+".key");
832         
833         if (f.exists()) {
834             String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
835             if (!"Y".equalsIgnoreCase(line)) {
836                 System.out.println("Canceling...");
837                 return;
838             }
839         }
840         
841         KeyPair kp = Factory.generateKeyPair(trans);
842         ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
843         System.out.printf("Wrote %s\n", f.getCanonicalFile());
844
845         f=new File(dir,ns+".pubkey");
846         ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
847         System.out.printf("Wrote %s\n", f.getCanonicalFile());
848     }
849     
850     private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
851         TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
852         try {
853                 final String fqi = fqi(cmds);
854                 Artifact arti = new Artifact();
855                 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, System.getProperty("user.dir")));
856                 arti.setNs(FQI.reverseDomain(fqi));
857             PropHolder loc = PropHolder.get(arti, "location.props");
858             PropHolder cred = PropHolder.get(arti,"cred.props");
859             PropHolder app= PropHolder.get(arti,"props");
860             for(String c : args) {
861                 int idx = c.indexOf('=');
862                 if(idx>0) {
863                         app.add(c.substring(0,idx), c.substring(idx+1));
864                 }
865             }
866             app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
867
868             for (String tag : LOC_TAGS) {
869                 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
870             }
871             
872             String keyfile = cred.getKeyPath();
873             if(keyfile!=null) {
874                 File fkeyfile = new File(keyfile);
875                 if(!fkeyfile.exists()) {
876                         ArtifactDir.write(fkeyfile,Chmod.to400,Symm.keygen());
877                 }
878             }
879             cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
880             final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
881             if(fqi!=null && fqi.equals(ssoAppID)) {
882                 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
883             // only Ask for Password when starting scratch
884             } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
885                 char[] pwd = AAFSSO.cons.readPassword("Password for %s (leave blank for NO password): ", fqi);
886                 if(pwd.length>0) {
887                         cred.addEnc(Config.AAF_APPPASS, new String(pwd));
888                 }
889             }
890             
891             // load all properties that are already setup.
892             Map<String, String> aaf_urls = loadURLs(propAccess);
893             for(Entry<String, String> es : aaf_urls.entrySet()) {
894                 app.add(es.getKey(), es.getValue());
895             }
896             
897             app.add(Config.AAF_LOCATE_URL, Config.getAAFLocateUrl(propAccess));
898             app.add(Config.AAF_ENV,propAccess, "DEV");
899             String release = propAccess.getProperty(Config.AAF_DEPLOYED_VERSION);
900             if(release==null) {
901                 release = System.getProperty(Config.AAF_DEPLOYED_VERSION,null);
902             }
903             if(release!=null) {
904                 app.add(Config.AAF_DEPLOYED_VERSION, release);
905             }
906             for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
907                 String key = aaf_loc_prop.getKey().toString();
908                 if(key.startsWith("aaf_locator")) {
909                         app.add(key, aaf_loc_prop.getValue().toString());
910                 }
911             }
912             
913             app.add(Config.AAF_APPID, fqi);
914
915             String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
916             System.out.println("Passed in Truststore is " + cts);
917             if (cts!=null) {
918                 File origTruststore = new File(cts);
919                 File newTruststore = new File(app.getDir(),origTruststore.getName());
920                 if(!newTruststore.exists()) {
921                         if (!origTruststore.exists()) {
922                             // Try same directory as cadi_prop_files
923                             String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
924                             if (cpf!=null) {
925                                 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
926                                     File fcpf = new File(f);
927                                     if (fcpf.exists()) {
928                                         int lastSep = cts.lastIndexOf(File.pathSeparator);
929                                         origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
930                                         if (origTruststore.exists()) { 
931                                             break;
932                                         }
933                                     }
934                                 }
935                                 if (!origTruststore.exists()) {
936                                     throw new CadiException(cts + " does not exist");
937                                 }
938                             }
939                             
940                         }
941                         if (!newTruststore.exists() && origTruststore.exists()) {
942                             Files.copy(origTruststore.toPath(), newTruststore.toPath());
943                         }
944                 }
945
946                 System.out.println("New Truststore is " + newTruststore);
947                 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
948                 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
949                     
950                 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
951                 if (cpf!=null){
952                         String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf); 
953                     for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
954                         String f = propFiles[pfi];
955                         System.out.format("Reading %s\n",f);
956                         FileInputStream fis = new FileInputStream(f); 
957                         try {
958                             Properties props = new Properties();
959                             props.load(fis);
960                             for (Entry<Object, Object> prop : props.entrySet()) {
961                                 boolean lower = true;
962                                 String key = prop.getKey().toString();
963                                 if(LOC_TAGS.contains(key)) {
964                                         break;
965                                 }
966                                 for(int i=0;lower && i<key.length();++i) {
967                                         if(Character.isUpperCase(key.charAt(i))) {
968                                                 lower = false;
969                                         }
970                                 }
971                                 if(lower) {
972                                         PropHolder ph = CRED_TAGS.contains(key)?cred:app;
973                                         if(key.endsWith("_password")) {
974                                                 ph.addEnc(key, prop.getValue().toString());
975                                         } else {
976                                                 ph.add(key, prop.getValue().toString());
977                                         }
978                                 }
979                             }
980                         } finally {
981                             fis.close();
982                         }
983                     }
984                 } else {
985                     aafcon = aafcon(propAccess);
986                     if (aafcon!=null) { // get Properties from Remote AAF
987                         for (Props props : aafProps(trans,aafcon,getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "),fqi)) {
988                                 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
989                                 if(props.getTag().endsWith("_password")) {
990                                         ph.addEnc(props.getTag(), props.getValue());
991                                 } else {
992                                         ph.add(props.getTag(), props.getValue());
993                                 }
994                         }
995
996                     }
997                 }
998             }
999             
1000             PropHolder.writeAll();
1001         } finally {
1002             tt.done();
1003         }
1004     }
1005
1006     public static List<Props> aafProps(Trans trans, AAFCon<?> aafcon, String locator, String fqi) throws CadiException, APIException, URISyntaxException {
1007         Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
1008                 .read("/configure/"+fqi+"/aaf", configDF);
1009         if (acf.get(TIMEOUT)) {
1010                 return acf.value.getProps();
1011         } else if (acf.code()==401){
1012             trans.error().log("Bad Password sent to AAF");
1013         } else if (acf.code()==404){
1014             trans.error().log("This version of AAF does not support remote Properties");
1015         } else {
1016             trans.error().log(errMsg.toMsg(acf));
1017         }
1018         return new ArrayList<>();
1019     }
1020
1021     private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
1022         System.out.println("Validating Configuration...");
1023         final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
1024         aafcon.best(new Retryable<Void>() {
1025             @Override
1026             public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
1027                 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
1028                 if (fc.get(aafcon.timeout)) {
1029                     System.out.print("Success connecting to ");
1030                     System.out.println(client.getURI());
1031                     System.out.print("   Permissions for ");
1032                     System.out.println(aafcon.defID());
1033                     for (Perm p : fc.value.getPerm()) {
1034                         System.out.print('\t');
1035                         System.out.print(p.getType());
1036                         System.out.print('|');
1037                         System.out.print(p.getInstance());
1038                         System.out.print('|');
1039                         System.out.println(p.getAction());
1040                     }
1041                 } else {
1042                     System.err.println("Error: " + fc.code() + ' ' + fc.body());
1043                 }
1044                 return null;
1045             }
1046         });
1047     }
1048
1049     /**
1050      * Check returns Error Codes, so that Scripts can know what to do
1051      * 
1052      *   0 - Check Complete, nothing to do
1053      *   1 - General Error
1054      *   2 - Error for specific Artifact - read check.msg
1055      *   10 - Certificate Updated - check.msg is email content
1056      *   
1057      * @param trans
1058      * @param aafcon
1059      * @param cmds
1060      * @return
1061      * @throws Exception
1062      */
1063     private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
1064         int exitCode=1;
1065         String mechID = fqi(cmds);
1066         String machine = machine(cmds);
1067         
1068         TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
1069         try {
1070         
1071             Future<Artifacts> acf = aafcon.client(CM_VER)
1072                     .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
1073             if (acf.get(TIMEOUT)) {
1074                 // Have to wait for JDK 1.7 source...
1075                 //switch(artifact.getType()) {
1076                 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1077                     AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1078                 } else {
1079                     String id = aafcon.defID();
1080                     GregorianCalendar now = new GregorianCalendar();
1081                     for (Artifact a : acf.value.getArtifact()) {
1082                         if (id.equals(a.getMechid())) {
1083                             File dir = new File(a.getDir());
1084                             Properties props = new Properties();
1085                             FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1086                             try {
1087                                 props.load(fis);
1088                             } finally {
1089                                 fis.close();
1090                             }
1091                             
1092                             String prop;                        
1093                             File f;
1094     
1095                             if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1096                                 !(f=new File(prop)).exists()) {
1097                                     trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1098                                         a.getMechid(), a.getMachine());
1099                             } else {
1100                                 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1101                                 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1102                                 if (ksf==null || ksps == null) {
1103                                     trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1104                                             Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1105                                 } else {
1106                                     Symm symm = ArtifactDir.getSymm(f);
1107
1108                                     KeyStore ks = KeyStore.getInstance("JKS");
1109                                     
1110                                     fis = new FileInputStream(ksf);
1111                                     try {
1112                                         ks.load(fis,symm.depass(ksps).toCharArray());
1113                                     } finally {
1114                                         fis.close();
1115                                     }
1116                                     X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1117                                     String msg = null;
1118
1119                                     if (cert==null) {
1120                                         msg = String.format("X509Certificate does not exist for %s on %s in %s",
1121                                                 a.getMechid(), a.getMachine(), ksf);
1122                                         trans.error().log(msg);
1123                                         exitCode = 2;
1124                                     } else {
1125                                         GregorianCalendar renew = new GregorianCalendar();
1126                                         renew.setTime(cert.getNotAfter());
1127                                         renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1128                                         if (renew.after(now)) {
1129                                             msg = String.format("X509Certificate for %s on %s has been checked on %s. It expires on %s; it will not be renewed until %s.\n", 
1130                                                     a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1131                                             trans.info().log(msg);
1132                                             exitCode = 0; // OK
1133                                         } else {
1134                                             trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n", 
1135                                                     a.getMechid(), a.getMachine(),cert.getNotAfter());
1136                                             cmds.offerLast(mechID);
1137                                             cmds.offerLast(machine);
1138                                             if (placeCerts(trans,aafcon,cmds)) {
1139                                                 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n", 
1140                                                         a.getMechid(), a.getMachine());
1141                                                 exitCode = 10; // Refreshed
1142                                             } else {
1143                                                 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n", 
1144                                                         a.getMechid(), a.getMachine());
1145                                                 exitCode = 1; // Error Renewing
1146                                             }
1147                                         }
1148                                     }
1149                                     if (msg!=null) {
1150                                         FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1151                                         try {
1152                                             fos.write(msg.getBytes());
1153                                         } finally {
1154                                             fos.close();
1155                                         }
1156                                     }
1157                                 }
1158                                 
1159                             }
1160                         }
1161                     }
1162                 }
1163             } else {
1164                 trans.error().log(errMsg.toMsg(acf));
1165                 exitCode=1;
1166             }
1167         } finally {
1168             tt.done();
1169         }
1170         return exitCode;
1171     }
1172
1173 }
1174             
1175         
1176
1177