1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 package org.apache.commons.net.examples.mail;
19 
20 import java.io.BufferedReader;
21 import java.io.Console;
22 import java.io.IOException;
23 import java.io.InputStreamReader;
24 import java.util.Locale;
25 
26 /**
27  * Utilities for mail examples
28  */
29 class Utils {
30 
Utils()31     private Utils() {
32         // not instantiable
33     }
34 
35     /**
36      * If the initial password is:
37      * '*' - replace it with a line read from the system console
38      * '-' - replace it with next line from STDIN
39      * 'ABCD' - if the input is all upper case, use the field as an environment variable name
40      *
41      * Note: there are no guarantees that the password cannot be snooped.
42      *
43      * Even using the console may be subject to memory snooping,
44      * however it should be safer than the other methods.
45      *
46      * STDIN may require creating a temporary file which could be read by others
47      * Environment variables may be visible by using PS
48      */
getPassword(final String username, String password)49     static String getPassword(final String username, String password) throws IOException {
50         if ("-".equals(password)) { // stdin
51             final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
52             password = in.readLine();
53         } else if ("*".equals(password)) { // console
54             final Console con = System.console(); // Java 1.6
55             if (con != null) {
56                 final char[] pwd = con.readPassword("Password for " + username + ": ");
57                 password = new String(pwd);
58             } else {
59                 throw new IOException("Cannot access Console");
60             }
61         } else if (password.equals(password.toUpperCase(Locale.ROOT))) { // environment variable name
62             final String tmp = System.getenv(password);
63             if (tmp != null) { // don't overwrite if variable does not exist (just in case password is all uppers)
64                 password=tmp;
65             }
66         }
67         return password;
68     }
69 
70 }
71