1%%
2%% %CopyrightBegin%
3%%
4%% Copyright Ericsson AB 2005-2017. All Rights Reserved.
5%%
6%% Licensed under the Apache License, Version 2.0 (the "License");
7%% you may not use this file except in compliance with the License.
8%% You may obtain a copy of the License at
9%%
10%%     http://www.apache.org/licenses/LICENSE-2.0
11%%
12%% Unless required by applicable law or agreed to in writing, software
13%% distributed under the License is distributed on an "AS IS" BASIS,
14%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15%% See the License for the specific language governing permissions and
16%% limitations under the License.
17%%
18%% %CopyrightEnd%
19%%
20
21%%
22
23%%% Description: user interaction for SSH
24
25-module(ssh_io).
26
27-export([yes_no/2, read_password/2, read_line/2, format/2]).
28-include("ssh.hrl").
29
30read_line(Prompt, Opts) ->
31    format("~s", [listify(Prompt)]),
32    ?GET_INTERNAL_OPT(user_pid, Opts) ! {self(), question},
33    receive
34	Answer when is_list(Answer) or is_binary(Answer) ->
35	    unicode:characters_to_list(Answer)
36    end.
37
38yes_no(Prompt, Opts) ->
39    format("~s [y/n]?", [Prompt]),
40    ?GET_INTERNAL_OPT(user_pid, Opts) ! {self(), question},
41    receive
42	%% I can't see that the atoms y and n are ever received, but it must
43	%% be investigated before removing
44	y -> yes;
45	n -> no;
46
47	Answer when is_list(Answer) or is_binary(Answer) ->
48	    case trim(Answer) of
49		"y" -> yes;
50		"n" -> no;
51		"Y" -> yes;
52		"N" -> no;
53		_ ->
54		    format("please answer y or n\n",[]),
55		    yes_no(Prompt, Opts)
56	    end
57    end.
58
59read_password(Prompt, Opts) ->
60    format("~s", [listify(Prompt)]),
61    ?GET_INTERNAL_OPT(user_pid, Opts) ! {self(), user_password},
62    receive
63	Answer when is_list(Answer) or is_binary(Answer) ->
64	     case trim(Answer) of
65		 "" ->
66		     read_password(Prompt, Opts);
67		 Pwd ->
68		     Pwd
69	     end
70    end.
71
72
73format(Fmt, Args) ->
74    io:format(Fmt, Args).
75
76%%%================================================================
77listify(A) when is_atom(A)   -> atom_to_list(A);
78listify(L) when is_list(L)   -> L;
79listify(B) when is_binary(B) -> binary_to_list(B).
80
81
82trim(Line) when is_list(Line) ->
83    lists:reverse(trim1(lists:reverse(trim1(Line))));
84trim(Line) when is_binary(Line) ->
85    trim(unicode:characters_to_list(Line));
86trim(Other) -> Other.
87
88trim1([$\s|Cs]) -> trim(Cs);
89trim1([$\r|Cs]) -> trim(Cs);
90trim1([$\n|Cs]) -> trim(Cs);
91trim1([$\t|Cs]) -> trim(Cs);
92trim1(Cs) -> Cs.
93