mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

lutoff
06.24.2007 f3e3cc3a3ee4086856eb2336e21cd8fb62dcc0a3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Portions Copyright 2007 Sun Microsystems, Inc.
 */
package org.opends.server.tools.dsconfig;
 
 
import static org.opends.messages.DSConfigMessages.*;
import static org.opends.messages.ToolMessages.*;
 
import java.io.File;
import java.io.FileInputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.util.LinkedHashSet;
 
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.net.ssl.KeyManager;
import javax.net.ssl.TrustManager;
 
import org.opends.admin.ads.util.ApplicationKeyManager;
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.messages.Message;
import org.opends.messages.MessageBuilder;
import org.opends.server.admin.client.AuthenticationException;
import org.opends.server.admin.client.AuthenticationNotSupportedException;
import org.opends.server.admin.client.CommunicationException;
import org.opends.server.admin.client.ManagementContext;
import org.opends.server.admin.client.cli.DsFrameworkCliReturnCode;
import org.opends.server.admin.client.cli.SecureConnectionCliArgs;
import org.opends.server.admin.client.ldap.JNDIDirContextAdaptor;
import org.opends.server.admin.client.ldap.LDAPConnection;
import org.opends.server.admin.client.ldap.LDAPManagementContext;
import org.opends.server.protocols.ldap.LDAPResultCode;
import org.opends.server.tools.ClientException;
import org.opends.server.util.SelectableCertificateKeyManager;
import org.opends.server.util.args.Argument;
import org.opends.server.util.args.ArgumentException;
import org.opends.server.util.args.SubCommandArgumentParser;
import org.opends.server.util.cli.CLIException;
import org.opends.server.util.cli.ConsoleApplication;
import org.opends.server.util.cli.Menu;
import org.opends.server.util.cli.MenuBuilder;
import org.opends.server.util.cli.MenuResult;
import org.opends.server.util.cli.ValidationCallback;
 
 
 
/**
 * An LDAP management context factory.
 */
public final class LDAPManagementContextFactory implements
    ManagementContextFactory {
 
  // The SecureConnectionCliArgsList object.
  private SecureConnectionCliArgs secureArgsList = null;
 
  // The management context.
  private ManagementContext context = null;
 
  // Indicate if we need to display the heading
  private boolean isHeadingDisplayed = false;
 
  // the Console application
  private ConsoleApplication app;
 
  /**
   * Enumeration description protocols for interactive CLI choices.
   */
  private enum Protocols
  {
    LDAP(1, INFO_DSCFG_PROMPT_SECURITY_LDAP.get()), SSL(2,
        INFO_DSCFG_PROMPT_SECURITY_USE_SSL.get()), START_TSL(3,
        INFO_DSCFG_PROMPT_SECURITY_USE_START_TSL.get());
 
    private Integer choice;
 
    private Message msg;
 
    /**
     * Private constructor.
     *
     * @param i
     *          the menu return value.
     * @param s
     *          the message message.
     */
    private Protocols(int i, Message msg)
    {
      choice = new Integer(i);
      this.msg = msg;
    }
 
    /**
     * Returns the choice number.
     *
     * @return the attribute name.
     */
    public Integer getChoice()
    {
      return choice;
    }
 
    /**
     * Return the menu message.
     *
     * @return the menu message.
     */
    public Message getMenuMessage()
    {
      return msg;
    }
  };
 
  /**
   * Creates a new LDAP management context factory.
   */
  public LDAPManagementContextFactory() {
    // No implementation required.
  }
 
  /**
   * {@inheritDoc}
   */
  public ManagementContext getManagementContext(ConsoleApplication app)
      throws ArgumentException, ClientException
  {
    // Lazily create the LDAP management context.
    if (context == null)
    {
      this.app = app;
      isHeadingDisplayed = false;
 
      boolean secureConnection =
        (
            secureArgsList.useSSLArg.isPresent()
            ||
            secureArgsList.useStartTLSArg.isPresent()
            ||
            secureArgsList.trustAllArg.isPresent()
            ||
            secureArgsList.trustStorePathArg.isPresent()
            ||
            secureArgsList.trustStorePasswordArg.isPresent()
            ||
            secureArgsList.trustStorePasswordFileArg.isPresent()
            ||
            secureArgsList.keyStorePathArg.isPresent()
            ||
            secureArgsList.keyStorePasswordArg.isPresent()
            ||
            secureArgsList.keyStorePasswordFileArg.isPresent()
        );
 
      // Get the LDAP host.
      String hostName = secureArgsList.hostNameArg.getValue();
      final String tmpHostName = hostName;
      if (app.isInteractive() && !secureArgsList.hostNameArg.isPresent())
      {
        if (!isHeadingDisplayed)
        {
          app.println();
          app.println();
          app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
          isHeadingDisplayed = true;
        }
 
        ValidationCallback<String> callback = new ValidationCallback<String>()
        {
 
          public String validate(ConsoleApplication app, String input)
              throws CLIException
          {
            String ninput = input.trim();
            if (ninput.length() == 0)
            {
              return tmpHostName;
            }
            else
            {
              try
              {
                InetAddress.getByName(ninput);
                return ninput;
              }
              catch (UnknownHostException e)
              {
                // Try again...
                app.println();
                app.println(ERR_DSCFG_BAD_HOST_NAME.get(ninput));
                app.println();
                return null;
              }
            }
          }
 
        };
 
        try
        {
          app.println();
          hostName = app.readValidatedInput(INFO_DSCFG_PROMPT_HOST_NAME
              .get(hostName), callback);
        }
        catch (CLIException e)
        {
          throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
        }
      }
 
      boolean useSSL = secureArgsList.useSSL();
      boolean useStartTLS = secureArgsList.useStartTLS();
      KeyManager keyManager = null;
      TrustManager trustManager = null;
      boolean connectionTypeIsSet =
        (
          secureArgsList.useSSLArg.isPresent()
          ||
          secureArgsList.useStartTLSArg.isPresent()
        );
      if (app.isInteractive() && !connectionTypeIsSet)
      {
        if (!isHeadingDisplayed)
        {
          app.println();
          app.println();
          app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
          isHeadingDisplayed = true;
        }
 
        MenuBuilder<Integer> builder = new MenuBuilder<Integer>(app);
        builder.setPrompt(INFO_DSCFG_PROMPT_SECURITY_USE_SECURE_CTX.get());
 
        Protocols defaultProtocol ;
        if (secureConnection)
        {
          defaultProtocol = Protocols.SSL;
        }
        else
        {
          defaultProtocol = Protocols.LDAP;
        }
        for (Protocols p : Protocols.values())
        {
          if (secureConnection && p.equals(Protocols.LDAP))
          {
            continue ;
          }
          int i = builder.addNumberedOption(p.getMenuMessage(), MenuResult
              .success(p.getChoice()));
          if (p.equals(defaultProtocol))
          {
            builder.setDefault(
                INFO_DSCFG_PROMPT_SECURITY_PROTOCOL_DEFAULT_CHOICE
                    .get(new Integer(i)), MenuResult.success(p.getChoice()));
          }
        }
 
        Menu<Integer> menu = builder.toMenu();
        try
        {
          MenuResult<Integer> result = menu.run();
          if (result.isSuccess())
          {
            if (result.getValue().equals(Protocols.SSL.getChoice()))
            {
              useSSL = true;
            }
            else if (result.getValue()
                .equals(Protocols.START_TSL.getChoice()))
            {
              useStartTLS = true;
            }
          }
          else
          {
            // Should never happen.
            throw new RuntimeException();
          }
        }
        catch (CLIException e)
        {
          throw new RuntimeException(e);
        }
      }
 
      if (useSSL || useStartTLS)
      {
        // Get truststore info
        trustManager = getTrustManager();
 
        // Check if we need client side authentication
        keyManager = getKeyManager();
      }
 
      // Get the LDAP port.
      int portNumber;
      if (!useSSL)
      {
        portNumber = secureArgsList.portArg.getIntValue();
      }
      else
      {
        if (secureArgsList.portArg.isPresent())
        {
          portNumber = secureArgsList.portArg.getIntValue();
        }
        else
        {
          portNumber = 636;
        }
      }
      final int tmpPortNumber = portNumber;
      if (app.isInteractive() && !secureArgsList.portArg.isPresent())
      {
        if (!isHeadingDisplayed)
        {
          app.println();
          app.println();
          app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
          isHeadingDisplayed = true;
        }
 
        ValidationCallback<Integer> callback = new ValidationCallback<Integer>()
        {
 
          public Integer validate(ConsoleApplication app, String input)
              throws CLIException
          {
            String ninput = input.trim();
            if (ninput.length() == 0)
            {
              return tmpPortNumber;
            }
            else
            {
              try
              {
                int i = Integer.parseInt(ninput);
                if (i < 1 || i > 65535)
                {
                  throw new NumberFormatException();
                }
                return i;
              }
              catch (NumberFormatException e)
              {
                // Try again...
                app.println();
                app.println(ERR_DSCFG_BAD_PORT_NUMBER.get(ninput));
                app.println();
                return null;
              }
            }
          }
 
        };
 
        try
        {
          app.println();
          portNumber = app.readValidatedInput(INFO_DSCFG_PROMPT_PORT_NUMBER
              .get(portNumber), callback);
        }
        catch (CLIException e)
        {
          throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
        }
      }
 
      // Get the LDAP bind credentials.
      String bindDN = secureArgsList.bindDnArg.getValue();
      final String tmpBindDN = bindDN;
      if (keyManager == null)
      {
        if (app.isInteractive() && !secureArgsList.bindDnArg.isPresent())
        {
          if (!isHeadingDisplayed)
          {
            app.println();
            app.println();
            app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
            isHeadingDisplayed = true;
          }
 
          ValidationCallback<String> callback = new ValidationCallback<String>()
          {
 
            public String validate(ConsoleApplication app, String input)
                throws CLIException
            {
              String ninput = input.trim();
              if (ninput.length() == 0)
              {
                return tmpBindDN;
              }
              else
              {
                return ninput;
              }
            }
 
          };
 
          try
          {
            app.println();
            bindDN = app.readValidatedInput(INFO_DSCFG_PROMPT_BIND_DN
                .get(bindDN), callback);
          }
          catch (CLIException e)
          {
            throw ArgumentExceptionFactory
                .unableToReadConnectionParameters(e);
          }
        }
      }
      else
      {
        bindDN = null ;
      }
 
      String bindPassword = secureArgsList.bindPasswordArg.getValue();
      if (keyManager == null)
      {
        if (secureArgsList.bindPasswordFileArg.isPresent())
        {
          // Read from file if it exists.
          bindPassword = secureArgsList.bindPasswordFileArg.getValue();
 
          if (bindPassword == null)
          {
            throw ArgumentExceptionFactory.missingBindPassword(bindDN);
          }
        }
        else if (bindPassword == null || bindPassword.equals("-"))
        {
          // Read the password from the stdin.
          if (!app.isInteractive())
          {
            throw ArgumentExceptionFactory
                .unableToReadBindPasswordInteractively();
          }
 
          if (!isHeadingDisplayed)
          {
            app.println();
            app.println();
            app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
            isHeadingDisplayed = true;
          }
 
          try
          {
            app.println();
            Message prompt = INFO_LDAPAUTH_PASSWORD_PROMPT.get(bindDN);
            bindPassword = app.readPassword(prompt);
          }
          catch (Exception e)
          {
            throw ArgumentExceptionFactory
                .unableToReadConnectionParameters(e);
          }
        }
      }
 
      // Do we have a secure connection ?
      LDAPConnection conn ;
      if (useSSL)
      {
        InitialLdapContext ctx = null;
        String ldapsUrl = "ldaps://" + hostName + ":" + portNumber;
        try
        {
          ctx = ConnectionUtils.createLdapsContext(ldapsUrl, bindDN,
              bindPassword, ConnectionUtils.getDefaultLDAPTimeout(), null,
              trustManager, keyManager);
          conn = JNDIDirContextAdaptor.adapt(ctx);
        }
        catch (NamingException e)
        {
          Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(
              hostName, String.valueOf(portNumber));
          throw new ClientException(LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR,
              message) ;
        }
      }
      else if (useStartTLS)
      {
        InitialLdapContext ctx = null;
        String ldapUrl = "ldap://" + hostName + ":" + portNumber;
        try
        {
          ctx = ConnectionUtils.createStartTLSContext(ldapUrl, bindDN,
              bindPassword, ConnectionUtils.getDefaultLDAPTimeout(), null,
              trustManager, keyManager, null);
          conn = JNDIDirContextAdaptor.adapt(ctx);
        }
        catch (NamingException e)
        {
          Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(
              hostName, String.valueOf(portNumber));
          throw new ClientException(LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR,
              message) ;
        }
      }
      else
      {
        // Create the management context.
        try
        {
          conn = JNDIDirContextAdaptor.simpleBind(hostName, portNumber,
              bindDN, bindPassword);
        }
        catch (AuthenticationNotSupportedException e)
        {
          Message message = ERR_DSCFG_ERROR_LDAP_SIMPLE_BIND_NOT_SUPPORTED
              .get();
          throw new ClientException(LDAPResultCode.AUTH_METHOD_NOT_SUPPORTED,
              message);
        }
        catch (AuthenticationException e)
        {
          Message message = ERR_DSCFG_ERROR_LDAP_SIMPLE_BIND_FAILED
              .get(bindDN);
          throw new ClientException(LDAPResultCode.INVALID_CREDENTIALS,
              message);
        }
        catch (CommunicationException e)
        {
          Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(
              hostName, String.valueOf(portNumber));
          throw new ClientException(LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR,
              message);
        }
      }
      context = LDAPManagementContext.createFromContext(conn);
    }
    return context;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  public void registerGlobalArguments(SubCommandArgumentParser parser)
      throws ArgumentException {
    // Create the global arguments.
    secureArgsList = new SecureConnectionCliArgs();
    LinkedHashSet<Argument> args = secureArgsList.createGlobalArguments();
 
 
    // Register the global arguments.
    for (Argument arg : args)
    {
      parser.addGlobalArgument(arg);
    }
 
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  public void validateGlobalArguments() throws ArgumentException {
    // Make sure that the user didn't specify any conflicting
    // arguments.
    MessageBuilder buf = new MessageBuilder();
    int v = secureArgsList.validateGlobalOptions(buf);
    if (v != DsFrameworkCliReturnCode.SUCCESSFUL_NOP.getReturnCode())
    {
      throw new ArgumentException(buf.toMessage());
    }
  }
 
  /**
   * Get the trust manager.
   *
   * @return The trust manager based on CLI args on interactive prompt.
   * @throws ArgumentException If an error occurs when getting args values.
   */
  private ApplicationTrustManager getTrustManager()
  throws ArgumentException
  {
    boolean trustAll = secureArgsList.trustAllArg.isPresent();
    if (app.isInteractive() && !secureArgsList.trustAllArg.isPresent())
    {
      if (!isHeadingDisplayed)
      {
        app.println();
        app.println();
        app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
        isHeadingDisplayed = true;
      }
 
      try
      {
        app.println();
        trustAll = app.confirmAction(INFO_DSCFG_PROMPT_SECURITY_USE_TRUST_ALL
            .get(), false);
      }
      catch (CLIException e)
      {
        // Should never happen.
        throw new RuntimeException(e);
      }
    }
 
    // Trust everything, so no trust manager
    if (trustAll)
    {
      return null;
    }
 
    // If we not trust all server certificates, we have to get info
    // about truststore. First get the truststore path.
    String truststorePath = secureArgsList.trustStorePathArg.getValue();
    if (app.isInteractive() && !secureArgsList.trustStorePathArg.isPresent())
    {
      if (!isHeadingDisplayed)
      {
        app.println();
        app.println();
        app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
        isHeadingDisplayed = true;
      }
 
      ValidationCallback<String> callback = new ValidationCallback<String>()
      {
        public String validate(ConsoleApplication app, String input)
            throws CLIException
        {
          String ninput = input.trim();
          if (ninput.length() == 0)
          {
            app.println();
            app.println(ERR_DSCFG_PROMPT_SECURITY_INVALID_FILE_PATH
                .get());
            app.println();
            return null;
          }
          File f = new File(ninput);
          if (f.exists() && f.canRead() && !f.isDirectory())
          {
            return ninput;
          }
          else
          {
            app.println();
            app.println(ERR_DSCFG_PROMPT_SECURITY_INVALID_FILE_PATH
                .get());
            app.println();
            return null;
          }
        }
      };
 
      try
      {
        app.println();
        truststorePath = app.readValidatedInput(
            INFO_DSCFG_PROMPT_SECURITY_TRUSTSTORE_PATH.get(), callback);
      }
      catch (CLIException e)
      {
        throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
      }
    }
 
    // Then the truststore password.
    //  As the most common case is to have no password for truststore,
    // we don't ask it in the interactive mode.
    String truststorePassword = secureArgsList.trustStorePasswordArg
        .getValue();
 
    if (secureArgsList.trustStorePasswordFileArg.isPresent())
    {
      // Read from file if it exists.
      truststorePassword = secureArgsList.trustStorePasswordFileArg
          .getValue();
    }
    if ((truststorePassword !=  null) && (truststorePassword.equals("-")))
    {
      // Read the password from the stdin.
      if (!app.isInteractive())
      {
        truststorePassword = null;
      }
      else
      {
        if (!isHeadingDisplayed)
        {
          app.println();
          app.println();
          app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
          isHeadingDisplayed = true;
        }
 
        try
        {
          app.println();
          Message prompt = INFO_DSCFG_PROMPT_SECURITY_TRUSTSTORE_PASSWORD
              .get(truststorePath);
          truststorePassword = app.readPassword(prompt);
        }
        catch (Exception e)
        {
          throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
        }
      }
    }
    // We'we got all the information to get the truststore manager
    try
    {
      FileInputStream fos = new FileInputStream(truststorePath);
      KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
      if (truststorePassword != null)
      {
        truststore.load(fos, truststorePassword.toCharArray());
      }
      else
      {
        truststore.load(fos, null);
      }
      fos.close();
      return new ApplicationTrustManager(truststore);
    }
    catch (Exception e)
    {
      throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
    }
  }
 
  /**
   * Get the key manager.
   *
   * @return The key manager based on CLI args on interactive prompt.
   * @throws ArgumentException If an error occurs when getting args values.
   */
  private KeyManager getKeyManager()
  throws ArgumentException
  {
    // Do we need client side authentication ?
    // If one of the client side authentication args is set, we assume
    // that we
    // need client side authentication.
    boolean weDontKnowIfWeNeedKeystore = !(secureArgsList.keyStorePathArg
        .isPresent()
        || secureArgsList.keyStorePasswordArg.isPresent()
        || secureArgsList.keyStorePasswordFileArg.isPresent()
        || secureArgsList.certNicknameArg
        .isPresent());
 
    // We don't have specific key manager parameter.
    // We assume that no client side authentication is required
    // Client side authentication is not the common use case. As a
    // consequence, interactive mode doesn't add an extra question
    // which will be in most cases useless.
    if (weDontKnowIfWeNeedKeystore)
    {
      return null;
    }
 
    // Get info about keystore. First get the keystore path.
    String keystorePath = secureArgsList.keyStorePathArg.getValue();
    if (app.isInteractive() && !secureArgsList.keyStorePathArg.isPresent())
    {
      if (!isHeadingDisplayed)
      {
        app.println();
        app.println();
        app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
        isHeadingDisplayed = true;
      }
 
      ValidationCallback<String> callback = new ValidationCallback<String>()
      {
        public String validate(ConsoleApplication app, String input)
            throws CLIException
        {
          String ninput = input.trim();
          if (ninput.length() == 0)
          {
            return ninput;
          }
          File f = new File(ninput);
          if (f.exists() && f.canRead() && !f.isDirectory())
          {
            return ninput;
          }
          else
          {
            app.println();
            app.println(ERR_DSCFG_PROMPT_SECURITY_INVALID_FILE_PATH
                .get());
            app.println();
            return null;
          }
        }
      };
 
      try
      {
        app.println();
        keystorePath = app.readValidatedInput(
            INFO_DSCFG_PROMPT_SECURITY_KEYSTORE_PATH.get(), callback);
      }
      catch (CLIException e)
      {
        throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
      }
    }
 
    // Then the keystore password.
    String keystorePassword = secureArgsList.keyStorePasswordArg.getValue();
 
    if (secureArgsList.keyStorePasswordFileArg.isPresent())
    {
      // Read from file if it exists.
      keystorePassword = secureArgsList.keyStorePasswordFileArg.getValue();
 
      if (keystorePassword == null)
      {
        throw ArgumentExceptionFactory.missingBindPassword(keystorePassword);
      }
    }
    else if (keystorePassword == null || keystorePassword.equals("-"))
    {
      // Read the password from the stdin.
      if (!app.isInteractive())
      {
        throw ArgumentExceptionFactory
            .unableToReadBindPasswordInteractively();
      }
 
      if (!isHeadingDisplayed)
      {
        app.println();
        app.println();
        app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
        isHeadingDisplayed = true;
      }
 
      try
      {
        app.println();
        Message prompt = INFO_DSCFG_PROMPT_SECURITY_KEYSTORE_PASSWORD
            .get(keystorePath);
        keystorePassword = app.readPassword(prompt);
      }
      catch (Exception e)
      {
        throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
      }
    }
 
    // finally the certificate name, if needed.
    String certifNickname = secureArgsList.certNicknameArg.getValue();
    if (app.isInteractive() && !secureArgsList.certNicknameArg.isPresent())
    {
      if (!isHeadingDisplayed)
      {
        app.println();
        app.println();
        app.println(INFO_DSCFG_HEADING_CONNECTION_PARAMETERS.get());
        isHeadingDisplayed = true;
      }
      ValidationCallback<String> callback = new ValidationCallback<String>()
      {
 
        public String validate(ConsoleApplication app, String input)
            throws CLIException
        {
          return input.trim();
        }
      };
 
      try
      {
        app.println();
        certifNickname = app.readValidatedInput(
            INFO_DSCFG_PROMPT_SECURITY_CERTIFICATE_NAME.get(), callback);
      }
      catch (CLIException e)
      {
        throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
      }
    }
 
    // We'we got all the information to get the keystore manager
    try
    {
      FileInputStream fos = new FileInputStream(keystorePath);
      KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
      keystore.load(fos, keystorePassword.toCharArray());
      fos.close();
      ApplicationKeyManager akm = new ApplicationKeyManager(keystore,
          keystorePassword.toCharArray());
 
      if (certifNickname.length() != 0)
      {
        return new SelectableCertificateKeyManager(akm, certifNickname);
      }
      else
      {
        return akm ;
      }
    }
    catch (Exception e)
    {
      throw ArgumentExceptionFactory.unableToReadConnectionParameters(e);
    }
  }
}