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
|
%% Create an AF_UNIX socket and accept connections. On connect, spawn
%% a p11p_server process.
-module(p11p_listener).
-behaviour(gen_server).
%% API.
-export([start_link/0]).
%% Genserver callbacks.
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
code_change/3]).
%% Records and types.
-include("p11p_defs.hrl").
-record(state, {tokens}).
%% API.
-spec start_link() -> {ok, pid()} | {error, term()}.
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
%% Genserver callbacks.
%%-spec init([[token()]]) -> {ok, #state{}}.
init([]) ->
TokensCfg = p11p_config:tokens(),
lager:debug("TokensCfg: ~p", [TokensCfg]),
{ok, Tokens} = init_tokens(TokensCfg, []),
{ok, #state{tokens = Tokens}}.
handle_call(Request, _From, State) ->
lager:debug("Unhandled call: ~p~n", [Request]),
{reply, unhandled, State}.
handle_cast(Request, State) ->
lager:debug("Unhandled cast: ~p~n", [Request]),
{noreply, State}.
handle_info(Info, State) ->
lager:debug("Unhandled info: ~p~n", [Info]),
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVersion, State, _Extra) ->
{ok, State}.
%% Private functions.
init_tokens([], Acc) ->
{ok, lists:reverse(Acc)};
init_tokens([TokenCfg | T], Acc) ->
#token{name = Name} = TokenCfg,
SocketPath = socket_path(mkdir_socket_basepath(), Name),
file:delete(SocketPath),
{ok, ListenSocket} = gen_udp:open(0, [{ifaddr, {local, SocketPath}}]),
init_tokens(T, [ListenSocket | Acc]).
mkdir_socket_basepath() ->
Path = "/run/user/1000/p11p",
ok = case file:make_dir(Path) of
ok -> ok;
{error, eexist} -> ok;
Err ->
lager:error("~s: unable to create directory: ~p", [Path, Err]),
err
end,
Path.
-spec socket_path(string(), string()) -> string().
socket_path(BasePath, Name) ->
%%"/run/user/$UID/p11p/$TokenCfg-$UNIXPID"
BasePath ++ "/" ++ Name.
|