summaryrefslogtreecommitdiff
path: root/p11p-daemon/src/p11p_remote_manager.erl
blob: ad7fbafaf94187370348e1cec64d7d8809abf440 (plain)
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
%%% Copyright (c) 2019, Sunet.
%%% See LICENSE for licensing information.

%% A remote manager is a genserver for coordination of remotes for all
%% tokens.

%% Provide a lookup service for servers in need of a remote to send
%% requests to, by keeping track of which module is current for a
%% given vtoken and spawn a p11p_remote genserver "on demand".
%%
%% Provide a client event and a server event API for servers and
%% remotes, respectively, where events like "remote timed out" and
%% "p11 client hung up" can be reported.
%%
%% Keep track of successful p11 requests which might cause state
%% changes in a token, like logins. When switching token under the
%% feet of the p11 client, replay whatever is needed to the new
%% token. This includes the p11-kit RPC protocol version octet.
%% Certain state changing p11 requests cannot be replayed, like
%% generation of a new key. Any such (successful) request invalidates
%% all other remotes for the given vtoken.

-module(p11p_remote_manager).

-behaviour(gen_server).

%% API.
-export([start_link/0]).
-export([remote_for_token/1, client_event/2]).	% For servers.
-export([server_event/2]).			% For remotes.

%% Genserver callbacks.
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
         code_change/3]).

%% Records and types.
-record(remote, {
	  tokname :: string(),
	  servid :: atom(),
	  modpath :: string(),
	  modenv :: [],
	  balance :: integer(),
	  pid :: pid() | undefined
	 }).

-record(token, {
	  mode :: p11p_config:token_mode_t(),
	  balance_count :: integer(),
	  remotes :: [#remote{}]	      % Active remote in hd().
	 }).

-record(state, {
	  tokens :: #{string() => #token{}}
	 }).

%% API implementation.
-spec start_link() -> {ok, pid()} | {error, term()}.
start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

-spec remote_for_token(string()) -> pid().
remote_for_token(TokName) ->
    gen_server:call(?MODULE, {remote_for_token, TokName}).
client_event(Event, Args) ->
    gen_server:cast(?MODULE, {client_event, Event, Args}).

server_event(Event, Args) ->
    gen_server:cast(?MODULE, {server_event, Event, Args}).

%% Genserver callbacks.
init([]) ->
    {ok, #state{tokens = init_tokens(p11p_config:tokens())}}.

handle_call({remote_for_token, TokNameIn}, _, #state{tokens = Tokens} = S) ->
    #{TokNameIn := TokenIn} = Tokens,
    RemotesIn = TokenIn#token.remotes,
    lager:debug("all remotes: ~p", [RemotesIn]),
    {Remotes, BalanceCount} =
	case TokenIn#token.balance_count of
	    0 ->
		lager:debug("~p: balancing: next remote", [self()]),
		Rotated = rotate_remotes(RemotesIn),
		First = hd(Rotated),
		{Rotated, First#remote.balance - 1};
	    N when N > 0 ->
		lager:debug("~p: balancing: ~B more invocations", [self(), N]),
		{RemotesIn, N - 1};
	    -1 ->
		{RemotesIn, -1}
	end,
    #remote{tokname = TokNameIn,
	    servid = ServId,
	    modpath = ModPath,
	    modenv = ModEnv,
	    pid = PidIn} = SelectedRemote = hd(Remotes),
    case PidIn of
	undefined ->
	    {ok, Pid} =
		p11p_remote:start_link(ServId, TokNameIn, ModPath, ModEnv),
	    Remote = SelectedRemote#remote{pid = Pid},
	    Token = TokenIn#token{remotes = [Remote | tl(Remotes)],
				   balance_count = BalanceCount},
	    {reply, Pid, S#state{tokens = Tokens#{TokNameIn := Token}}};
	_ ->
	    {reply, PidIn, S}
    end;
handle_call(Call, _From, State) ->
    lager:debug("Unhandled call: ~p~n", [Call]),
    {reply, unhandled, State}.

handle_cast({server_event, timeout, [TokNameIn, Server]},
	    #state{tokens = Tokens} = S) ->
    lager:debug("~p: ~s: timed out, stopping ~p", [self(), TokNameIn, Server]),
    gen_server:stop(Server),		      % Hang up on p11 client.
    %% TODO: do some code dedup with remote_for_token?
    #{TokNameIn := TokenIn} = Tokens,
    Remotes = TokenIn#token.remotes,
    SelectedRemote = hd(Remotes),
    Remote = SelectedRemote#remote{pid = undefined},
    Token = TokenIn#token{remotes = tl(Remotes) ++ [Remote]},
    lager:debug("~p: ~s: updated token: ~p", [self(), TokNameIn, Token]),
    {noreply, S#state{tokens = Tokens#{TokNameIn := Token}}};

handle_cast({client_event, client_gone, [TokName, Pid]},
	    #state{tokens = Tokens} = S) ->
    lager:debug("~p: asking remote ~p to stop", [self(), Pid]),
    p11p_remote:stop(Pid, normal),
    #{TokName := TokenIn} = Tokens,
    Remotes = lists:map(fun(E) ->
				case E#remote.pid of
				    Pid -> E#remote{pid = undefined};
				    _ -> E
				end
			end, TokenIn#token.remotes),
    Token = TokenIn#token{remotes = Remotes},
    {noreply, S#state{tokens = Tokens#{TokName := Token}}};

handle_cast(Cast, State) ->
    lager:debug("Unhandled cast: ~p~n", [Cast]),
    {noreply, State}.

handle_info({Port, {exit_status, Status}}, State) ->
    %% FIXME: do we need to be trapping exits explicitly?
    lager:info("~p: process ~p exited with ~p", [self(), Port, Status]),
    {noreply, State};
handle_info(Info, State) ->
    lager:debug("~p: Unhandled info: ~p~n", [self(), Info]),
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVersion, State, _Extra) ->
    {ok, State}.

%% Private functions
-spec init_tokens([p11p_config:token()]) -> #{string() => #token{}}.
init_tokens(ConfTokens) ->
    init_tokens(ConfTokens, #{}).
init_tokens([], Acc)->
    lager:debug("~p: created tokens from config: ~p", [self(), Acc]),
    Acc;
init_tokens([H|T], Acc)->
    init_tokens(T, Acc#{p11p_config:nameof(H) => new_token(H)}).

new_token(Conf) ->
    Name = p11p_config:nameof(Conf),
    Mode = p11p_config:token_mode(Name),
    Remotes = remotes(Name,
		      p11p_config:modules_for_token(Name),
		      Mode),
    R0 = hd(Remotes),
    #token{
       mode = p11p_config:token_mode(Name),
       balance_count = R0#remote.balance,
       remotes = Remotes
      }.

remotes(TokName, ConfModules, ConfMode) ->
    remotes(TokName, ConfModules, ConfMode, []).
remotes(_, [], _, Acc) ->
    Acc;
remotes(TokName, [H|T], ConfMode, Acc) ->
    ModName = p11p_config:nameof(H),
    ServName = "p11p_remote:" ++ TokName ++ ":" ++ ModName,
    ModPath = p11p_config:module_path(H),
    ModEnv = p11p_config:module_env(H),
    remotes(TokName, T, ConfMode, [#remote{
				      tokname = TokName,
				      servid = list_to_atom(ServName),
				      modpath = ModPath,
				      modenv = ModEnv,
				      balance = balance(ConfMode, length(T) + 1)
				     }
				   | Acc]).

-spec balance(p11p_config:token_mode_t(), non_neg_integer()) -> integer().
balance({balance, Ratios}, N) ->
    lists:nth(N, Ratios);
balance(_, _) ->
    -1.

%% -spec balance_count(p11p_config:token_mode_t()) -> integer().
%% balance_count(#token{mode = {balance, _}, balance_count = C}) ->
%%     C - 1;
%% balance_count(_) ->
%%     -1.

rotate_remotes(L) ->
    lists:reverse([hd(L) | lists:reverse(tl(L))]).