1%%
2%% %CopyrightBegin%
3%%
4%% Copyright Ericsson AB 1997-2016. All Rights Reserved.
5%%
6%% Licensed under the Apache License, Version 2.0 (the "License");
7%% you may not use this file except in compliance with the License.
8%% You may obtain a copy of the License at
9%%
10%%     http://www.apache.org/licenses/LICENSE-2.0
11%%
12%% Unless required by applicable law or agreed to in writing, software
13%% distributed under the License is distributed on an "AS IS" BASIS,
14%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15%% See the License for the specific language governing permissions and
16%% limitations under the License.
17%%
18%% %CopyrightEnd%
19%%
20%%
21-module(mod_head).
22-export([do/1]).
23
24-include("httpd.hrl").
25
26-define(VMODULE,"HEAD").
27
28%% do
29
30do(Info) ->
31    case Info#mod.method of
32	"HEAD" ->
33	    case proplists:get_value(status, Info#mod.data) of
34		%% A status code has been generated!
35		{_StatusCode, _PhraseArgs, _Reason} ->
36		    {proceed,Info#mod.data};
37		%% No status code has been generated!
38		_undefined ->
39		    case proplists:get_value(response, Info#mod.data) of
40			%% No response has been generated!
41			undefined ->
42			    do_head(Info);
43			%% A response has been sent! Nothing to do about it!
44			{already_sent, _StatusCode, _Size} ->
45			    {proceed,Info#mod.data};
46			{response, Header, _Body} -> %% New way
47			    {proceed,
48			     lists:keyreplace(response, 1, Info#mod.data,
49					      {response, Header, nobody})};
50			%% A response has been generated!
51			{_StatusCode, _Response} ->
52			    {proceed,Info#mod.data}
53		    end
54	    end;
55	%% Not a HEAD method!
56	_ ->
57	    {proceed,Info#mod.data}
58    end.
59
60do_head(Info) ->
61    Path = mod_alias:path(Info#mod.data,
62			  Info#mod.config_db,
63			  Info#mod.request_uri),
64    Suffix = httpd_util:strip_extension_dot(Path),
65    %% Does the file exists?
66    case file:read_file_info(Path) of
67	{ok, #file_info{type = directory}} ->
68            Status = httpd_file:handle_error(eacces, "access", Info, Path),
69            {proceed,
70             [{status, Status} | Info#mod.data]};
71	{ok, FileInfo} ->
72	    MimeType =
73		httpd_util:lookup_mime_default(Info#mod.config_db,
74					       Suffix,"text/plain"),
75	    Length = io_lib:write(FileInfo#file_info.size),
76	    Head =
77		[{content_type, MimeType},
78		 {content_length, Length}, {code,200}],
79	    {proceed,[{response, {response, Head,  nobody}} | Info#mod.data]};
80	{error, Reason} ->
81	    Status = httpd_file:handle_error(Reason, "access", Info, Path),
82	    {proceed,
83	     [{status, Status} | Info#mod.data]}
84    end.
85