Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module(webserver).
- -export([start/1, loop/1]).
- -include("debug.hrl").
- start(_) ->
- Port = 8080,
- {ok, Sock} = gen_tcp:listen(Port, [{active, false}, {packet, line}, {reuseaddr, true}]),
- loop(Sock).
- loop(Sock) ->
- case gen_tcp:accept(Sock) of
- {ok, ConnSock} ->
- spawn(fun () -> handle(ConnSock) end);
- Err ->
- error({webserver_sock_accept,Err})
- end,
- receive
- code_change ->
- ?MODULE:loop(Sock);
- Unknown ->
- error({unhandled, Unknown})
- after 0 ->
- loop(Sock)
- end.
- handle(Conn) ->
- Timeout = 20000 + (erlang:crc32(pid_to_list(self())) band 8191),
- Got = get_request(Conn),
- % ?DEBUG("Got request: ~p", [Got]),
- {ok, {IP,_Port}} = inet:peername(Conn),
- flood_activity(IP, Got, 1),
- send_request_to_lua(Got),
- Reply = handle_loop(Conn, IP, Timeout, Got),
- gen_tcp:send(Conn, create_response(Reply)),
- gen_tcp:close(Conn),
- exit('replied').
- handle_loop(Conn, IP, Timeout, Got) ->
- receive
- {flooding,_FloodInfo} ->
- "<h2>Flooding attempt detected from this address, sorry...<p>Please leave for a few minutes, otherwise you'll be kept locked out.</h2>";
- {http_reply, Body} -> Body;
- {flood_activity, Score} ->
- flood_activity(IP, Got, Score),
- handle_loop(Conn, IP, Timeout, Got);
- Dunno ->
- error({websocket_dunno, Dunno})
- after Timeout ->
- luaserver ! {webserver, self(), connection_aborted},
- "IDLE"
- end.
- get_request(Conn) ->
- RevParts = get_request(Conn, []),
- lists:concat(lists:reverse(RevParts)).
- get_request(Conn, RevParts) ->
- Part = gen_tcp:recv(Conn, 0, 5000),
- case Part of
- {ok,"\r\n"} -> %konec requestu
- RevParts;
- {ok, Bytes} ->
- get_request(Conn, [Bytes | RevParts]);
- {error, _Err} ->
- luaserver ! {webserver, self(), connection_aborted},
- gen_tcp:close(Conn),
- exit(socket_error);
- Any ->
- ?DEBUG("?? Webserver socket got: ~p", [Any]),
- throw(unknown_socket_data)
- end.
- send_request_to_lua(String) ->
- true = is_pid(whereis(luaserver)),
- whereis(luaserver) ! {webserver, self(), new_connection, String}.
- create_response(Str) ->
- string_to_response(Str).
- string_to_response(Str) ->
- B = iolist_to_binary(Str),
- iolist_to_binary(
- io_lib:fwrite(
- "HTTP/1.0 200 OK\nContent-Type: text/html\nAccess-Control-Allow-Origin: *\nContent-Length: ~p\n\n~s",
- [size(B), B])).
- flood_activity(IP, Request, Score) ->
- floodbot ! {self(), {flood_activity, Score, IP, Request}}.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement