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

%% FIXME: Run _one_ socket per instance of this server!

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

%% API.
-export([start_link/1]).

%% 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, {socket :: gen_tcp:socket()}).

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

%% Genserver callbacks.
init(Socket) ->
    gen_server:cast(self(), accept), % Perform accept in gen-server loop.
    {ok, #state{socket = Socket}}.

handle_call(Request, _From, State) ->
    lager:debug("Unhandled call: ~p~n", [Request]),
    {reply, unhandled, State}.

handle_cast(accept, State = #state{socket = ListenSocket}) ->
    {ok, Sock} = gen_tcp:accept(ListenSocket),
    %% TODO: authz
    lager:debug("new connection accepted: ~p", [Sock]),
    p11p_server_sup:start_server(),		% New acceptor.
    {noreply, State#state{socket = Sock}};
handle_cast(Request, State) ->
    lager:debug("Unhandled cast: ~p~n", [Request]),
    {noreply, State}.

handle_info({tcp, _Socket, Data}, State) ->
    lager:debug("~p: received: ~s", [self(), Data]),
    {noreply, State};
handle_info(Info, State) ->
    lager:debug("Unhandled info: ~p~n", [Info]),
    {noreply, State}.

terminate(_Reason, #state{socket = Socket}) ->
    gen_tcp:close(Socket),			% FIXME: correct?
    ok.

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

%% Private functions.