summaryrefslogtreecommitdiff
path: root/src/couch_inets/mod_cgi.erl
blob: 0e682d841ca5aef660e9b0ae10e4c2bf4435e4df (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
%% ``The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved via the world wide web at http://www.erlang.org/.
%% 
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%% 
%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
%% AB. All Rights Reserved.''
%% 
%%     $Id$
%%
%% Implements  The WWW Common Gateway Interface Version 1.1

-module(mod_cgi).

-export([env/3]).

%%% Callback API
-export([do/1, load/2]).

-include("http_internal.hrl").
-include("httpd.hrl").

%% We will not make the change to use base64 in stdlib in inets just yet.
%% it will be included in the next major release of inets. 
-compile({nowarn_deprecated_function, {http_base_64, encode, 1}}).

-define(VMODULE,"CGI").

-define(DEFAULT_CGI_TIMEOUT, 15000).

%%%=========================================================================
%%%  API
%%%=========================================================================
%%--------------------------------------------------------------------------
%% do(ModData, _, AfterScript) ->  [{EnvVariable, Value}]
%%                
%%     AfterScript = string()
%%     ModData = #mod{}
%%     EnvVariable = string() 
%%     Value = term()
%% Description: Keep for now as it is documented in the man page
%%-------------------------------------------------------------------------
env(ModData, _Script, AfterScript) ->
    ScriptElements = script_elements(ModData, AfterScript),
    httpd_script_env:create_env(cgi, ModData, ScriptElements).

%%%=========================================================================
%%%  Callback API
%%%=========================================================================

%%--------------------------------------------------------------------------
%% do(ModData) -> {proceed, OldData} | {proceed, NewData} | {break, NewData} 
%%                | done
%%     ModData = #mod{}
%%
%% Description:  See httpd(3) ESWAPI CALLBACK FUNCTIONS
%%-------------------------------------------------------------------------
do(ModData) ->
    case httpd_util:key1search(ModData#mod.data, status) of
	%% A status code has been generated!
	{_StatusCode, _PhraseArgs, _Reason} ->
	    {proceed, ModData#mod.data};
	%% No status code has been generated!
	undefined ->
	    case httpd_util:key1search(ModData#mod.data, response) of
		undefined ->
		    generate_response(ModData);
		_Response ->
		    {proceed, ModData#mod.data}
	    end
    end.

%%--------------------------------------------------------------------------
%% load(Line, Context) ->  eof | ok | {ok, NewContext} | 
%%                     {ok, NewContext, Directive} | 
%%                     {ok, NewContext, DirectiveList} | {error, Reason}
%% Line = string()
%% Context = NewContext = DirectiveList = [Directive]
%% Directive = {DirectiveKey , DirectiveValue}
%% DirectiveKey = DirectiveValue = term()
%% Reason = term() 
%%
%% Description: See httpd(3) ESWAPI CALLBACK FUNCTIONS
%%-------------------------------------------------------------------------

%% ScriptNoCache true|false, defines whether the server shall add     
%%                           header fields to stop proxies and          
%%                           clients from saving the page in history  
%%                           or cache                                 
%%                                                                             
load("ScriptNoCache " ++ CacheArg, [])->
    case catch list_to_atom(httpd_conf:clean(CacheArg)) of
        true ->
	    {ok, [], {script_nocache, true}};
	false ->
	   {ok, [], {script_nocache, false}};
	_ ->
	   {error, ?NICE(httpd_conf:clean(CacheArg)++
			 " is an invalid ScriptNoCache directive")}
    end;
%% ScriptTimeout Seconds, The number of seconds that the server       
%%                        maximum will wait for the script to         
%%                        generate a part of the document   
load("ScriptTimeout " ++ Timeout, [])->
    case catch list_to_integer(httpd_conf:clean(Timeout)) of
	TimeoutSec when integer(TimeoutSec)  ->
	   {ok, [], {script_timeout,TimeoutSec*1000}};
	_ ->
	   {error, ?NICE(httpd_conf:clean(Timeout)++
			 " is an invalid ScriptTimeout")}
    end.
	
%%%========================================================================
%%% Internal functions
%%%========================================================================
generate_response(ModData) ->
    RequestURI =
	case httpd_util:key1search(ModData#mod.data, new_request_uri) of
	    undefined ->
		ModData#mod.request_uri;
	    Value ->
		Value
	end,
    ScriptAliases =
	httpd_util:multi_lookup(ModData#mod.config_db, script_alias),
    case mod_alias:real_script_name(ModData#mod.config_db, RequestURI,
				    ScriptAliases) of
	{Script, AfterScript} ->
	    exec_script(ModData, Script, AfterScript, 
			RequestURI);
	not_a_script ->
	    {proceed, ModData#mod.data}
    end.

is_executable(File) ->
    Dir      = filename:dirname(File),
    FileName = filename:basename(File),
    case os:type() of
	{win32,_} ->
	    %% temporary (hopefully) fix for win32 OTP-3627
	    is_win32_executable(Dir,FileName);
	_ ->
	    is_executable(Dir, FileName) 
    end.

is_executable(Dir, FilName) ->
    case os:find_executable(FilName, Dir) of
	false ->
	    false;
	_ ->
	    true
    end.

%% Start temporary (hopefully) fix for win32 OTP-3627
%% ---------------------------------
is_win32_executable(Dir, FileName) ->
    NewFileName = strip_extention(FileName, [".bat",".exe",".com", ".cmd"]),
    is_executable(Dir, NewFileName).

strip_extention(FileName, []) ->
    FileName;
strip_extention(FileName, [Extention | Extentions]) ->
    case filename:basename(FileName, Extention) of
	FileName ->
	    strip_extention(FileName, Extentions); 
	NewFileName ->
	    NewFileName
    end.

%% End fix
%% ---------------------------------

exec_script(ModData, Script, AfterScript, RequestURI) ->
    exec_script(is_executable(Script), ModData, Script, 
		AfterScript, RequestURI).

exec_script(true, ModData, Script, AfterScript, _RequestURI) ->
    process_flag(trap_exit,true),
    Dir  = filename:dirname(Script),
    ScriptElements = script_elements(ModData, AfterScript),
    Env = (catch httpd_script_env:create_env(cgi, ModData, ScriptElements)),

    %% Run script
    Port = (catch open_port({spawn, Script},[binary, stream,
					     {cd, Dir}, {env, Env}])),
    case Port of
	Port when is_port(Port) ->
	    send_request_body_to_script(ModData, Port),
	    deliver_webpage(ModData, Port); % Take care of script output
	Error ->
	    exit({open_port_failed, Error,
		  [{mod,?MODULE},
		   {uri,ModData#mod.request_uri}, {script,Script},
		   {env,Env},{dir,Dir}]})
    end;

exec_script(false, ModData, _Script, _AfterScript, _RequestURI) ->
    {proceed,
     [{status,
       {404,ModData#mod.request_uri,
	?NICE("You don't have permission to execute " ++
	      ModData#mod.request_uri ++ " on this server")}}|
      ModData#mod.data]}.
    
send_request_body_to_script(ModData, Port) ->
    case ModData#mod.entity_body of
	[] ->
	    ok;
	EntityBody ->
	    port_command(Port, EntityBody)
    end.	
	   
deliver_webpage(#mod{config_db = Db} = ModData, Port) ->
    Timeout = cgi_timeout(Db),    
    case receive_headers(Port, httpd_cgi, parse_headers, 
			 [<<>>, [], []], Timeout) of
	{Headers, Body} ->
	    case httpd_cgi:handle_headers(Headers) of
		{proceed, AbsPath} ->
		    {proceed, [{real_name, 
				httpd_util:split_path(AbsPath)} | 
			       ModData#mod.data]};
		{ok, HTTPHeaders, Status} ->
		    IsDisableChunkedSend = 
			httpd_response:is_disable_chunked_send(Db),
		    case (ModData#mod.http_version =/= "HTTP/1.1") or 
			(IsDisableChunkedSend) of
			true ->
			    send_headers(ModData, Status, 
					 [{"connection", "close"}
					   | HTTPHeaders]);
			false ->
			    send_headers(ModData, Status,
					 [{"transfer-encoding",
					   "chunked"} | HTTPHeaders])
		    end,
		    handle_body(Port, ModData, Body, Timeout, size(Body),
				IsDisableChunkedSend)
	    end;
	{'EXIT', Port, Reason} ->
	    process_flag(trap_exit, false),
	    {proceed, [{status, {400, none, reason(Reason)}} |
		       ModData#mod.data]};
	timeout ->
	    (catch port_close(Port)), % KILL the port !!!!
	    send_headers(ModData, {504, "Timeout"}, []),
	    httpd_socket:close(ModData#mod.socket_type, ModData#mod.socket),
	    process_flag(trap_exit,false),
	    {proceed,[{response, {already_sent, 200, 0}} | ModData#mod.data]}
    end.
	    
receive_headers(Port, Module, Function, Args, Timeout) ->
      receive
	  {Port, {data, Response}} when is_port(Port) ->
	      case Module:Function([Response | Args]) of
		  {NewModule, NewFunction, NewArgs} ->
		      receive_headers(Port, NewModule, 
				      NewFunction, NewArgs, Timeout);
		  {ok, {Headers, Body}} ->
		      {Headers, Body}
	      end;
	  {'EXIT', Port, Reason} when is_port(Port) ->
	      {'EXIT', Port, Reason};
	  {'EXIT', Pid, Reason} when is_pid(Pid) ->
	      exit({linked_process_died, Pid, Reason})
      after Timeout ->
	      timeout
      end.

send_headers(ModData, {StatusCode, _}, HTTPHeaders) ->
    ExtraHeaders = httpd_response:cache_headers(ModData),
    httpd_response:send_header(ModData, StatusCode, 
			       ExtraHeaders ++ HTTPHeaders).

handle_body(Port, #mod{method = "HEAD"} = ModData, _, _, Size, _) ->
    (catch port_close(Port)), % KILL the port !!!!
    process_flag(trap_exit,false),
    {proceed, [{response, {already_sent, 200, Size}} | ModData#mod.data]};

handle_body(Port, ModData, Body, Timeout, Size, IsDisableChunkedSend) ->
    httpd_response:send_chunk(ModData, Body, IsDisableChunkedSend),
    receive 
	{Port, {data, Data}} when port(Port) ->
	    handle_body(Port, ModData, Data, Timeout, Size + size(Data),
			IsDisableChunkedSend);
	{'EXIT', Port, normal} when is_port(Port) ->
	    httpd_response:send_final_chunk(ModData, IsDisableChunkedSend),
	    process_flag(trap_exit,false),
	    {proceed, [{response, {already_sent, 200, Size}} |
		       ModData#mod.data]};
	{'EXIT', Port, Reason} when is_port(Port) ->
	    process_flag(trap_exit, false),
	    {proceed, [{status, {400, none, reason(Reason)}} | 
		       ModData#mod.data]};
	{'EXIT', Pid, Reason} when is_pid(Pid) ->
	    exit({mod_cgi_linked_process_died, Pid, Reason})
    after Timeout ->
	    (catch port_close(Port)), % KILL the port !!!!
	    process_flag(trap_exit,false),
	    {proceed,[{response, {already_sent, 200, Size}} |
		      ModData#mod.data]}
    end.

script_elements(#mod{method = "GET"}, {[], QueryString}) ->
    [{query_string, QueryString}];
script_elements(#mod{method = "GET"}, {PathInfo, []}) ->
    [{path_info, PathInfo}];
script_elements(#mod{method = "GET"}, {PathInfo, QueryString}) ->
    [{query_string, QueryString}, {path_info, PathInfo}];
script_elements(#mod{method = "POST", entity_body = Body}, _) ->
    [{entity_body, Body}];
script_elements(_, _) ->
    [].

cgi_timeout(Db) ->
    httpd_util:lookup(Db, cgi_timeout, ?DEFAULT_CGI_TIMEOUT).

%% Convert error to printable string
%%
reason({error,emfile})     -> ": To many open files";
reason({error,{enfile,_}}) -> ": File/port table overflow";
reason({error,enomem})     -> ": Not enough memory";
reason({error,eagain})     -> ": No more available OS processes";
reason(Reason) -> lists:flatten(io_lib:format("Reason: ~p~n", [Reason])).