summaryrefslogtreecommitdiff
path: root/p11p-daemon/src/p11p_server.erl
blob: e32a4395557785228e9406c4bfbb9804e4539fd4 (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
%% Create an AF_UNIX socket and accept connections. On connect, spawn
%% another p11p_server process.

-module(p11p_server).
-behaviour(gen_server).

-include("p11p_rpc.hrl").

%% API.
-export([start_link/1]).
-export([add_to_clientbuf/2, reply/2]).

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

%% Records and types.
-record(state, {
	  tokname :: string(),
	  remote :: pid() | undefined,
	  sockpath :: string(),
	  socket :: gen_tcp:socket(),
	  msg :: p11rpc_msg() | undefined,
	  clientbuf = <<>> :: binary()
	 }).

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

-spec add_to_clientbuf(pid(), binary()) -> {ok, non_neg_integer()}.
add_to_clientbuf(Pid, Data) ->
    gen_server:call(Pid, {add_to_clientbuf, Data}).

-spec reply(pid(), p11rpc_msg()) -> {ok, non_neg_integer()}.
reply(Pid, Response) ->
    gen_server:call(Pid, {response, Response}).

%% Genserver callbacks.
init([Token, SocketPath, Socket]) ->
    lager:debug("~p: p11p_server:init: ~s", [self(), SocketPath]),
    process_flag(trap_exit, true),		% We want terminate().
    gen_server:cast(self(), accept), % Perform accept in gen-server loop.
    {ok, #state{tokname = Token, sockpath = SocketPath, socket = Socket}}.

handle_call({add_to_clientbuf, Data}, _From, #state{clientbuf = Buf} = State) ->
    NewBuf = <<Buf/binary, Data/binary>>,
    {reply, {ok, size(NewBuf)}, State#state{clientbuf = NewBuf}};
handle_call({response, Response}, _From, #state{socket = ClientPort, clientbuf = Buf} = State) ->
    Data = p11p_rpc:serialise(Response),
    NewBuf = <<Buf/binary, Data/binary>>,
    %%lager:debug("~p: sending ~B octets back to client as reply", [self(), size(NewBuf)]),
    ok = gen_tcp:send(ClientPort, NewBuf), % TODO: what about short writes?
    {reply, {ok, size(NewBuf)}, State#state{clientbuf = <<>>}};
handle_call(Call, _From, State) ->
    lager:debug("~p: Unhandled call: ~p~n", [self(), Call]),
    {reply, unhandled, State}.

handle_cast(accept, State = #state{tokname = TokName, sockpath = SocketPath, socket = ListenSocket}) ->
    %% Blocking until client connects or timeout fires. Without a
    %% timeout our supervisor cannot terminate us.
    case gen_tcp:accept(ListenSocket, 900) of
	{ok, Sock} ->
	    lager:debug("~p: ~p: new connection accepted", [self(), Sock]),
	    p11p_server_sup:start_server([TokName, SocketPath, ListenSocket]), % Start a new acceptor.
	    {noreply, State#state{socket = Sock}}; % Use the new socket.
	{error, timeout} ->
	    gen_server:cast(self(), accept),	% Try again.
	    {noreply, State};
	{error, closed} ->
	    lager:debug("~p: listening socket closed", [self()]),
	    {stop, normal, State}
    end;
handle_cast(Cast, State) ->
    lager:debug("~p: Unhandled cast: ~p~n", [self(), Cast]),
    {noreply, State}.

handle_info({tcp, _Port, Data}, #state{tokname = TokName, remote = Remote} = State) when Remote == undefined ->
    %%lager:debug("~p: received ~B octets from client on socket ~p, from new client", [self(), size(Data), Port]),
    <<Version:8, NewData/binary>> = Data,
    NewRemote = p11p_remote_manager:remote_for_token(TokName),
    p11p_remote:add_to_outbuf(NewRemote, <<Version>>),
    NewState = handle_client_data(State, p11p_rpc:new(), NewData),
    {noreply, NewState#state{remote = NewRemote}};
handle_info({tcp, _Port, Data}, #state{msg = Msg} = State) ->
    %%lager:debug("~p: received ~B octets from client on socket ~p, with ~B octets already in buffer", [self(), size(Data), Port, size(Msg#p11rpc_msg.buffer)]),
    {noreply, handle_client_data(State, Msg, Data)};
handle_info({tcp_closed, Port}, State) ->
    lager:debug("~p: socket ~p closed", [self(), Port]),
    {stop, normal, State};
handle_info(Info, State) ->
    lager:debug("~p: Unhandled info: ~p~n", [self(), Info]),
    {noreply, State}.

terminate(Reason, #state{socket = Socket, tokname = TokName, remote = Remote}) ->
    gen_tcp:close(Socket),
    p11p_remote_manager:client_event(client_gone, [TokName, Remote]),
    lager:debug("~p: terminated with reason ~p", [self(), Reason]),
    ignored.

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

%% Private functions.
handle_client_data(#state{tokname = TokName} = State, Msg, Data) ->
    case p11p_rpc:parse(Msg, Data) of
	{done, NewMsg} ->
	    Remote = p11p_remote_manager:remote_for_token(TokName),
	    ok = p11p_remote:request(Remote, NewMsg),
	    State#state{msg = p11p_rpc:new(NewMsg#p11rpc_msg.buffer)};
	{needmore, NewMsg} ->
	    State#state{msg = NewMsg}
    end.