[erlang-questions] Erlang way for process-as-library?

Ulf Wiger <>
Tue Feb 6 09:10:55 CET 2007


Den 2007-02-06 08:55:19 skrev Bengt Kleberg <>:

> On 2007-02-06 02:17, Robert Baruch wrote:
> ...deleted
>> Now, the next question I have is: is there an Erlang way to forbid
>> "ordinary users" from calling the server's callback functions
>> directly (e.g. init, terminate, and so on), while allowing gen_server
>> access to them?
>
> short answer: no.
>
> long answer: how about including something in the server state that the
> user can not forge? presumably this is expensive since it would need to
> change for each call (btw, i am considering the user as a ''man in the
> middle'' here).

I've experimented with that sort of thing, at least trying to
guarantee that the caller is using the official exported functions:

%%% (simplified)

call(Server, Req) ->
    Ref = make_ref(),
    Server ! {self(), Ref, Req},
    await_reply(Ref).

%% this function mustn't be exported
await_reply(Ref) ->
    receive
       {Ref, Reply} -> Reply
    end.


server_loop(St) ->
    receive
       {From, Ref, Req} ->
          case is_valid_call(From) of
             true ->
                {Reply, St1} = handle_call(Req, St),
                From ! {Ref, Reply},
                server_loop(St1);
             false ->
                %% ignore
                server_loop(St)
    end.

is_valid_call(Pid) when is_pid(Pid) ->
    case process_info(Pid, current_function) of
       {current_function, {?MODULE,await_reply,1}} ->
          true;
       _ ->
          false
    end;
is_valid_call(_) ->
    false.


... at least it's pretty lightweight.  (:

BR,
Ulf W
-- 
Ulf Wiger




More information about the erlang-questions mailing list