Skip to content

Commit 82fb18e

Browse files
committed
Initial commit (with the history of previous commits discarded)
0 parents  commit 82fb18e

11 files changed

+352
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
ebin/

LICENSE

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
Copyright (c) 2012, Grzegorz Junka
2+
All rights reserved.
3+
4+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5+
6+
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7+
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
8+
9+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
charreada
2+
=========
3+
4+
Simple Erlang reverse proxy leveraging Cowboy

priv/app.config

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
% -*- mode: erlang -*-
2+
[{charreada,
3+
[{nb_acceptors, 50},
4+
{port, 8088}
5+
]
6+
}
7+
].

rebar.config

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
%% -*- mode: erlang -*-
2+
{deps,
3+
[
4+
{cowboy, ".*", {git, "git://github.com/extend/cowboy.git", "master"}},
5+
{ibrowse, ".*", {git, "git://github.com/cmullaparthi/ibrowse.git", "master"}}
6+
]
7+
}.

src/charreada.app.src

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{application, charreada,
2+
[
3+
{description, "Simple Erlang reverse proxy leveraging Cowboy"},
4+
{vsn, "0.1.0"},
5+
{applications, [kernel, stdlib, cowboy, ibrowse]},
6+
{registered, [charreada_config]},
7+
{mod, {charreada_app, []}}
8+
]
9+
}.

src/charreada.erl

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
-module(charreada).
2+
3+
%% API
4+
5+
-export([start_http_proxy/3, stop_proxy/0]).
6+
7+
start_http_proxy(NbAcceptors, TransOpts, Timeout) ->
8+
Dispatch = [{'_', [ {'_', charreada_handler, []} ]} ],
9+
Fun = fun(Req) -> charreada_handler:onrequest(Req, Timeout) end,
10+
ProtoOpts = [ {dispatch, Dispatch}, {onrequest, Fun} ],
11+
{ok, _} = cowboy:start_http(http, NbAcceptors, TransOpts, ProtoOpts),
12+
ok.
13+
14+
stop_proxy() ->
15+
ok = cowboy:stop_listener(http),
16+
ok.

src/charreada_app.erl

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
-module(charreada_app).
2+
-behaviour(application).
3+
4+
%% API.
5+
6+
-export([start/2, stop/1]).
7+
8+
%% API.
9+
10+
start(_Type, _Args) ->
11+
NbAcceptors = get_nb_acceptors(application:get_env(nb_acceptors)),
12+
Port = get_port(application:get_env(port)),
13+
Timeout = get_timeout(application:get_env(timeout_seconds)),
14+
charreada:start_http_proxy(NbAcceptors, [{port, Port}], Timeout),
15+
charreada_sup:start_link().
16+
17+
stop(_State) ->
18+
charreada:stop_proxy(),
19+
ok.
20+
21+
get_nb_acceptors(undefined) -> 100;
22+
get_nb_acceptors({ok, Value}) -> Value.
23+
24+
get_port(undefined) -> 8080;
25+
get_port({ok, Value}) -> Value.
26+
27+
get_timeout(undefined) -> 30*1000;
28+
get_timeout({ok, Value}) -> Value*1000.

src/charreada_config.erl

+136
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
-module(charreada_config).
2+
-behaviour(gen_server).
3+
4+
%% API
5+
-export([start_link/1]).
6+
-export([add_proxy/1, remove_proxy/1, redirect_req/6]).
7+
8+
%% gen_server callbacks
9+
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
10+
11+
%% Internal functions
12+
-export([wait_for_connect/6]).
13+
14+
-define(SERVER, ?MODULE).
15+
16+
%%% API
17+
start_link(Tid) ->
18+
gen_server:start_link({local, ?SERVER}, ?MODULE, Tid, []).
19+
20+
-spec add_proxy ({atom(), term()}) -> ok; ({binary(), term()}) -> ok.
21+
add_proxy(Proxy) ->
22+
gen_server:cast(?SERVER, {add, Proxy}).
23+
24+
-spec remove_proxy (atom()) -> ok; (binary()) -> ok.
25+
remove_proxy(Name) ->
26+
gen_server:cast(?SERVER, {remove, Name}).
27+
28+
-spec redirect_req(
29+
binary(), binary(), binary(), [{binary(), binary()}], function(), timeout()) ->
30+
ok | {error, cowboy_http:status()}.
31+
redirect_req(Method, Host, Path, Headers, BodyFun, Timeout) ->
32+
Msg = {redirect, self(), Method, Host, Path, Headers, BodyFun, Timeout},
33+
gen_server:call(?SERVER, Msg).
34+
35+
%%% gen_server callbacks
36+
37+
init(Tid) ->
38+
{ok, Tid}.
39+
40+
handle_call({redirect, Pid, Method, Host, Path, Headers, BodyFun, Timeout}, _From, Tid) ->
41+
Proxy = match_host(Tid, binary:split(Host, <<".">>)),
42+
Reply = start_redirect(Proxy, Pid, Method, Path, Headers, BodyFun, Timeout),
43+
{reply, Reply, Tid}.
44+
45+
handle_cast({add, Proxy}, Tid) ->
46+
ets:insert(Tid, normalize(Proxy)),
47+
{noreply, Tid};
48+
handle_cast({remove, Name}, Tid) ->
49+
ets:delete(Tid, normalize_key(Name)),
50+
{noreply, Tid}.
51+
52+
handle_info(_, State) ->
53+
{noreply, State}.
54+
55+
terminate(_Reason, _State) ->
56+
ok.
57+
58+
code_change(_OldVsn, State, _Extra) ->
59+
{ok, State}.
60+
61+
%%% Internal methods
62+
63+
normalize({Name, Transport, Host, Port, User, Password}) ->
64+
{to_lower_binary(Name), Transport, Host, Port, User, Password}.
65+
66+
normalize_key(Name) ->
67+
to_lower_binary(Name).
68+
69+
match_host(Tid, [Subdomain | _T]) ->
70+
ets:lookup(Tid, to_lower_binary(Subdomain));
71+
match_host(_Tid, []) ->
72+
[].
73+
74+
start_redirect([], _Pid, _Method, _Path, _Headers, _BodyFun, _Timeout) ->
75+
{error, 404};
76+
start_redirect([{_, Transport, Host, Port, User, Password}],
77+
Pid, OrgMethod, Path, OrgHeaders, BodyFun, Timeout) ->
78+
Url = url(Transport, Host, Port, Path),
79+
Headers = to_strings(OrgHeaders, []),
80+
Method = to_atom(OrgMethod),
81+
Options = to_ibrowse_options(Pid, User, Password),
82+
Params = [Url, Headers, Method, BodyFun, Options, Timeout],
83+
proc_lib:spawn(?MODULE, wait_for_connect, Params),
84+
ok.
85+
86+
wait_for_connect(Url, Headers, Method, BodyFun, Options, Timeout) ->
87+
ibrowse:send_req(Url, Headers, Method, BodyFun, Options, Timeout).
88+
89+
url(Transport, Host, Port, Path) ->
90+
to_string(Transport) ++ "://" ++ to_string(Host) ++ ":" ++ to_string(Port) ++ to_string(Path).
91+
92+
to_lower_binary(Value) when is_binary(Value) ->
93+
list_to_binary(string:to_lower(binary_to_list(Value)));
94+
to_lower_binary(Value) when is_atom(Value) ->
95+
list_to_binary(string:to_lower(atom_to_list(Value)));
96+
to_lower_binary(Value) when is_list(Value) ->
97+
list_to_binary(string:to_lower(Value)).
98+
99+
to_string(Value) when is_binary(Value) ->
100+
binary_to_list(Value);
101+
to_string(Value) when is_atom(Value) ->
102+
atom_to_list(Value);
103+
to_string(Value) when is_integer(Value) ->
104+
integer_to_list(Value);
105+
to_string({IP1, IP2, IP3, IP4}) ->
106+
to_string(IP1) ++ "." ++ to_string(IP2) ++ "." ++ to_string(IP3) ++ "." ++ to_string(IP4).
107+
108+
to_atom(<<"GET">>) -> get;
109+
to_atom(<<"POST">>) -> post;
110+
to_atom(<<"HEAD">>) -> head;
111+
to_atom(<<"OPTIONS">>) -> options;
112+
to_atom(<<"PUT">>) -> put;
113+
to_atom(<<"DELETE">>) -> delete;
114+
to_atom(<<"TRACE">>) -> trace;
115+
to_atom(<<"MKCOL">>) -> mkcol;
116+
to_atom(<<"PROPFIND">>) -> propfind;
117+
to_atom(<<"PROPPATCH">>) -> proppatch;
118+
to_atom(<<"LOCK">>) -> lock;
119+
to_atom(<<"UNLOCK">>) -> unlock;
120+
to_atom(<<"MOVE">>) -> move;
121+
to_atom(<<"COPY">>) -> copy.
122+
123+
to_strings([{Key, Value}|T], Acc) ->
124+
to_strings(T, [{to_string(Key), to_string(Value)}|Acc]);
125+
to_strings([], Acc) ->
126+
lists:reverse(Acc).
127+
128+
to_ibrowse_options(Pid, undefined, _Password) ->
129+
to_ibrowse_options([], Pid);
130+
to_ibrowse_options(Pid, _User, undefined) ->
131+
to_ibrowse_options([], Pid);
132+
to_ibrowse_options(Pid, User, Password) ->
133+
to_ibrowse_options([{basic_auth, {to_string(User), to_string(Password)}}], Pid).
134+
135+
to_ibrowse_options(Acc, Pid) ->
136+
[{stream_to, {Pid, once}}|Acc].

src/charreada_handler.erl

+110
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
-module(charreada_handler).
2+
3+
%% Cowboy handler
4+
5+
-export([onrequest/2]).
6+
-export([init/3]).
7+
-export([info/3]).
8+
-export([terminate/2]).
9+
10+
onrequest(Req, Timeout) ->
11+
proxy_host(cowboy_req:header(<<"host">>, Req), Timeout).
12+
13+
proxy_host({undefined, Req}, _Timeout) ->
14+
{ok, ReplyReq} = cowboy_req:reply(404, Req),
15+
ReplyReq;
16+
proxy_host({Host, Req}, Timeout) ->
17+
{Method, Req} = cowboy_req:method(Req),
18+
{Path, Req} = cowboy_req:path(Req),
19+
{OrgHeaders, Req} = cowboy_req:headers(Req),
20+
Headers = lists:keydelete(<<"host">>, 1, OrgHeaders),
21+
BodyFun = {fun post_body/1, self()},
22+
Resp = charreada_config:redirect_req(Method, Host, Path, Headers, BodyFun, Timeout),
23+
handle_redirect(Resp, Req, Timeout).
24+
25+
handle_redirect(ok, Req, Timeout) ->
26+
cowboy_req:set_meta(timeout, Timeout, Req);
27+
handle_redirect({error, Status}, Req, _Timeout) ->
28+
{ok, ReplyReq} = cowboy_req:reply(Status, Req),
29+
ReplyReq.
30+
31+
init(_Transport, OrgReq, []) ->
32+
{Timeout, Req} = cowboy_req:meta(timeout, OrgReq),
33+
{loop, Req, {Timeout, undefined}, Timeout}.
34+
35+
info({ibrowse_get_body, Pid}, Req, State) ->
36+
stream(cowboy_req:stream_body(Req), Req, Pid, State);
37+
info({ibrowse_async_headers, RequestId, Code, HeadersOrg}, Req, {Timeout, undefined}) ->
38+
{Headers, Length} = process_headers(HeadersOrg, [], 0),
39+
{ok, Transport, Socket} = cowboy_req:transport(Req),
40+
Fun = fun() -> stream_reply({RequestId, Transport, Socket, Length}, Length) end,
41+
{ok, ReplyReq} = cowboy_req:reply(list_to_integer(Code), Headers, {Length, Fun}, Req),
42+
{loop, ReplyReq, {Timeout, Length}};
43+
info({ibrowse_async_response, _RequestId, []}, Req, State) ->
44+
{loop, Req, State};
45+
info({ibrowse_async_response_end, _RequestId}, Req, State) ->
46+
{ok, Req, State};
47+
info({cowboy_req, resp_sent}, Req, State) ->
48+
{loop, Req, State};
49+
info({error, _Reason}, Req, State) ->
50+
reply(502, Req, State).
51+
52+
terminate(_Req, _State) ->
53+
ok.
54+
55+
post_body(Pid) ->
56+
Pid ! {ibrowse_get_body, self()},
57+
receive
58+
{ok, Data} ->
59+
{ok, Data, Pid};
60+
eof ->
61+
eof
62+
end.
63+
64+
stream({done, Req}, _Req, Pid, State) ->
65+
Pid ! eof,
66+
{loop, Req, State};
67+
stream({ok, Data, Req}, _Req, Pid, State) ->
68+
Pid ! {ok, Data},
69+
{loop, Req, State};
70+
stream({error, _Reason}, Req, Pid, State) ->
71+
Pid ! eof,
72+
reply(502, Req, State).
73+
74+
process_headers([{Key, Value}|T], Acc, Length) ->
75+
BKey = list_to_binary(string:to_lower(Key)),
76+
process_headers(BKey, Value, T, Acc, Length);
77+
process_headers([], Acc, Length) ->
78+
{lists:reverse(Acc), Length}.
79+
80+
process_headers(<<"content-length">>, Value, Headers, Acc, _Length) ->
81+
process_headers(Headers, Acc, list_to_integer(Value));
82+
process_headers(Key, Value, Headers, Acc, Length) ->
83+
process_headers(Headers, [{Key, Value}|Acc], Length).
84+
85+
stream_reply({RequestId, Transport, Socket, _Length} = ReqInfo, ToSend) ->
86+
ibrowse:stream_next(RequestId),
87+
receive
88+
{ibrowse_async_response, RequestId, Data} ->
89+
ChunkLength = length(Data),
90+
Result = Transport:send(Socket, Data),
91+
check_send(Result, ReqInfo, ToSend, ChunkLength)
92+
end.
93+
94+
check_send(ok, ReqInfo, ToSend, ChunkLength) ->
95+
check_send(ReqInfo, ToSend - ChunkLength);
96+
check_send({error, _}, {RequestId, Transport, Socket, Length}, ToSend, _ChunkLength) ->
97+
ibrowse:stream_close(RequestId),
98+
Transport:close(Socket),
99+
{sent, Length - ToSend}.
100+
101+
check_send({_RequestId, _Transport, _Socket, Length}, ToSend) when ToSend =< 0 ->
102+
{sent, Length};
103+
check_send(ReqInfo, ToSend) ->
104+
stream_reply(ReqInfo, ToSend).
105+
106+
reply({ok, Req}, State) ->
107+
{ok, Req, State}.
108+
109+
reply(Code, Req, State) ->
110+
reply(cowboy_req:reply(Code, Req), State).

src/charreada_sup.erl

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
-module(charreada_sup).
2+
-behaviour(supervisor).
3+
4+
%% API.
5+
6+
-export([start_link/0]).
7+
8+
%% Supervisor callbacks
9+
10+
-export([init/1]).
11+
12+
%% Helper macro for declaring supervisor worker
13+
-define(WORKER(I, P), {I, {I, start_link, [P]}, permanent, 5000, worker, [I]}).
14+
15+
%% API
16+
17+
start_link() ->
18+
supervisor:start_link(?MODULE, []).
19+
20+
%% Supervisor callbacks
21+
22+
init([]) ->
23+
Tid = ets:new(?MODULE, [public, {read_concurrency, true}]),
24+
Procs = [?WORKER(charreada_config, Tid)],
25+
{ok, {{one_for_one, 5, 15}, Procs}}.

0 commit comments

Comments
 (0)