xref: /lighttpd1.4/src/http_cgi.c (revision c95f832f)
1 /*
2  * http_cgi - Common Gateway Interface (CGI) interfaces (RFC 3875)
3  *
4  * Copyright(c) 2016-2017 Glenn Strauss gstrauss()gluelogic.com  All rights reserved
5  * License: BSD 3-clause (same as lighttpd)
6  */
7 #include "first.h"
8 
9 #include "http_cgi.h"
10 
11 #include "sys-socket.h"
12 #include <string.h>
13 
14 #include "base.h"
15 #include "array.h"
16 #include "buffer.h"
17 #include "chunk.h"
18 #include "log.h"
19 #include "http_header.h"
20 #include "sock_addr.h"
21 
22 handler_t
23 http_cgi_local_redir (request_st * const r)
24 {
25     /* [RFC3875] The Common Gateway Interface (CGI) Version 1.1
26      * [RFC3875] 6.2.2 Local Redirect Response
27      *
28      *    The CGI script can return a URI path and query-string
29      *    ('local-pathquery') for a local resource in a Location header field.
30      *    This indicates to the server that it should reprocess the request
31      *    using the path specified.
32      *
33      *      local-redir-response = local-Location NL
34      *
35      *    The script MUST NOT return any other header fields or a message-body,
36      *    and the server MUST generate the response that it would have produced
37      *    in response to a request containing the URL
38      *
39      *      scheme "://" server-name ":" server-port local-pathquery
40      *
41      * (While not required by the RFC, do not send local-redir back to same URL
42      *  since CGI should have handled it internally if it really wanted to do
43      *  that internally)
44      */
45 
46     size_t ulen = buffer_string_length(&r->uri.path);
47     const buffer *vb = http_header_response_get(r, HTTP_HEADER_LOCATION,
48                                                 CONST_STR_LEN("Location"));
49     if (NULL != vb
50         && vb->ptr[0] == '/'
51         && (0 != strncmp(vb->ptr, r->uri.path.ptr, ulen)
52             || (   vb->ptr[ulen] != '\0'
53                 && vb->ptr[ulen] != '/'
54                 && vb->ptr[ulen] != '?'))
55         && !light_btst(r->resp_htags, HTTP_HEADER_STATUS)
56         && 1 == r->resp_headers.used /*"Location"; no "Status" or NPH response*/
57         && r->http_status >= 300 && r->http_status < 400) {
58         if (++r->loops_per_request > 5) {
59             log_error(r->conf.errh, __FILE__, __LINE__,
60               "too many internal loops while processing request: %s",
61               r->target_orig.ptr);
62             r->http_status = 500; /* Internal Server Error */
63             r->resp_body_started = 0;
64             r->handler_module = NULL;
65             return HANDLER_FINISHED;
66         }
67 
68         buffer_copy_buffer(&r->target, vb);
69 
70         if (r->reqbody_length) {
71             if (r->reqbody_length != r->reqbody_queue.bytes_in)
72                 r->keep_alive = 0;
73             r->reqbody_length = 0;
74             chunkqueue_reset(&r->reqbody_queue);
75         }
76 
77         if (r->http_status != 307 && r->http_status != 308) {
78             /* Note: request body (if any) sent to initial dynamic handler
79              * and is not available to the internal redirect */
80             r->http_method = HTTP_METHOD_GET;
81         }
82 
83         /*(caller must reset request as follows)*/
84         /*http_response_reset(r);*/ /*(sets r->http_status = 0)*/
85         /*plugins_call_handle_request_reset(r);*/
86 
87         return HANDLER_COMEBACK;
88     }
89 
90     return HANDLER_GO_ON;
91 }
92 
93 
94 int
95 http_cgi_headers (request_st * const r, http_cgi_opts * const opts, http_cgi_header_append_cb cb, void *vdata)
96 {
97     /* CGI-SPEC 6.1.2, FastCGI spec 6.3 and SCGI spec */
98 
99     int rc = 0;
100     const connection * const con = r->con;
101     server_socket * const srv_sock = con->srv_socket;
102     buffer * const tb = r->tmp_buf;
103     const char *s;
104     size_t n;
105     char buf[LI_ITOSTRING_LENGTH];
106     sock_addr *addr;
107     sock_addr addrbuf;
108     char b2[INET6_ADDRSTRLEN + 1];
109 
110     /* (CONTENT_LENGTH must be first for SCGI) */
111     if (!opts->authorizer)
112         rc |= cb(vdata, CONST_STR_LEN("CONTENT_LENGTH"),
113                  buf, li_itostrn(buf,sizeof(buf),r->reqbody_length));
114 
115     if (!buffer_string_is_empty(&r->uri.query))
116         rc |= cb(vdata, CONST_STR_LEN("QUERY_STRING"),
117                         CONST_BUF_LEN(&r->uri.query));
118     else
119         rc |= cb(vdata, CONST_STR_LEN("QUERY_STRING"),
120                         CONST_STR_LEN(""));
121 
122     if (!buffer_string_is_empty(opts->strip_request_uri)) {
123         /**
124          * /app1/index/list
125          *
126          * stripping /app1 or /app1/ should lead to
127          *
128          * /index/list
129          *
130          */
131         size_t len = buffer_string_length(opts->strip_request_uri);
132         if ('/' == opts->strip_request_uri->ptr[len-1])
133             --len;
134 
135         if (buffer_string_length(&r->target_orig) >= len
136             && 0 == memcmp(r->target_orig.ptr,
137                            opts->strip_request_uri->ptr, len)
138             && r->target_orig.ptr[len] == '/') {
139             rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"),
140                             r->target_orig.ptr+len,
141                             buffer_string_length(&r->target_orig)-len);
142         }
143         else
144             rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"),
145                             CONST_BUF_LEN(&r->target_orig));
146     }
147     else
148         rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"),
149                         CONST_BUF_LEN(&r->target_orig));
150 
151     if (!buffer_is_equal(&r->target, &r->target_orig))
152         rc |= cb(vdata, CONST_STR_LEN("REDIRECT_URI"),
153                         CONST_BUF_LEN(&r->target));
154 
155     /* set REDIRECT_STATUS for php compiled with --force-redirect
156      * (if REDIRECT_STATUS has not already been set by error handler) */
157     if (0 == r->error_handler_saved_status)
158         rc |= cb(vdata, CONST_STR_LEN("REDIRECT_STATUS"),
159                         CONST_STR_LEN("200"));
160 
161     /*
162      * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
163      * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
164      * (6.1.14, 6.1.6, 6.1.7)
165      */
166     if (!opts->authorizer) {
167         rc |= cb(vdata, CONST_STR_LEN("SCRIPT_NAME"),
168                         CONST_BUF_LEN(&r->uri.path));
169         if (!buffer_string_is_empty(&r->pathinfo)) {
170             rc |= cb(vdata, CONST_STR_LEN("PATH_INFO"),
171                             CONST_BUF_LEN(&r->pathinfo));
172             /* PATH_TRANSLATED is only defined if PATH_INFO is set
173              * Note: not implemented: re-url-encode '?' '=' ';' for
174              * (RFC 3875 4.1.6) */
175             if (!buffer_string_is_empty(opts->docroot))
176                 buffer_copy_buffer(tb, opts->docroot);
177             else
178                 buffer_copy_buffer(tb, &r->physical.basedir);
179             buffer_append_path_len(tb, CONST_BUF_LEN(&r->pathinfo));
180             rc |= cb(vdata, CONST_STR_LEN("PATH_TRANSLATED"),
181                             CONST_BUF_LEN(tb));
182         }
183     }
184 
185    /*
186     * SCRIPT_FILENAME and DOCUMENT_ROOT for php
187     * The PHP manual http://www.php.net/manual/en/reserved.variables.php
188     * treatment of PATH_TRANSLATED is different from the one of CGI specs.
189     * (see php.ini cgi.fix_pathinfo = 1 config parameter)
190     */
191 
192     if (!buffer_string_is_empty(opts->docroot)) {
193         /* alternate docroot, e.g. for remote FastCGI or SCGI server */
194         buffer_copy_buffer(tb, opts->docroot);
195         buffer_append_path_len(tb, CONST_BUF_LEN(&r->uri.path));
196         rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
197                         CONST_BUF_LEN(tb));
198         rc |= cb(vdata, CONST_STR_LEN("DOCUMENT_ROOT"),
199                         CONST_BUF_LEN(opts->docroot));
200     }
201     else {
202         if (opts->break_scriptfilename_for_php) {
203             /* php.ini config cgi.fix_pathinfo = 1 need a broken SCRIPT_FILENAME
204              * to find out what PATH_INFO is itself
205              *
206              * see src/sapi/cgi_main.c, init_request_info()
207              */
208             buffer_copy_buffer(tb, &r->physical.path);
209             buffer_append_path_len(tb, CONST_BUF_LEN(&r->pathinfo));
210             rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
211                             CONST_BUF_LEN(tb));
212         }
213         else
214             rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
215                             CONST_BUF_LEN(&r->physical.path));
216         rc |= cb(vdata, CONST_STR_LEN("DOCUMENT_ROOT"),
217                         CONST_BUF_LEN(&r->physical.basedir));
218     }
219 
220     s = get_http_method_name(r->http_method);
221     force_assert(s);
222     rc |= cb(vdata, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s));
223 
224     s = get_http_version_name(r->http_version);
225     force_assert(s);
226     rc |= cb(vdata, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s));
227 
228     rc |= cb(vdata, CONST_STR_LEN("SERVER_SOFTWARE"),
229                     CONST_BUF_LEN(r->conf.server_tag));
230 
231     rc |= cb(vdata, CONST_STR_LEN("GATEWAY_INTERFACE"),
232                     CONST_STR_LEN("CGI/1.1"));
233 
234     rc |= cb(vdata, CONST_STR_LEN("REQUEST_SCHEME"),
235                     CONST_BUF_LEN(&r->uri.scheme));
236 
237     if (buffer_is_equal_string(&r->uri.scheme, CONST_STR_LEN("https")))
238         rc |= cb(vdata, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
239 
240     addr = &srv_sock->addr;
241     rc |= cb(vdata, CONST_STR_LEN("SERVER_PORT"),
242              buf, li_utostrn(buf,sizeof(buf),sock_addr_get_port(addr)));
243 
244     switch (sock_addr_get_family(addr)) {
245     case AF_INET:
246     case AF_INET6:
247         if (sock_addr_is_addr_wildcard(addr)) {
248             socklen_t addrlen = sizeof(addrbuf);
249             if (0 == getsockname(con->fd,(struct sockaddr *)&addrbuf,&addrlen)){
250                 addr = &addrbuf;
251             }
252             else {
253                 s = "";
254                 break;
255             }
256         }
257         s = sock_addr_inet_ntop(addr, b2, sizeof(b2)-1);
258         if (NULL == s) s = "";
259         break;
260     default:
261         s = "";
262         break;
263     }
264     force_assert(s);
265     rc |= cb(vdata, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s));
266 
267     if (!buffer_string_is_empty(r->server_name)) {
268         size_t len = buffer_string_length(r->server_name);
269 
270         if (r->server_name->ptr[0] == '[') {
271             const char *colon = strstr(r->server_name->ptr, "]:");
272             if (colon) len = (colon + 1) - r->server_name->ptr;
273         }
274         else {
275             const char *colon = strchr(r->server_name->ptr, ':');
276             if (colon) len = colon - r->server_name->ptr;
277         }
278 
279         rc |= cb(vdata, CONST_STR_LEN("SERVER_NAME"),
280                         r->server_name->ptr, len);
281     }
282     else /* set to be same as SERVER_ADDR (above) */
283         rc |= cb(vdata, CONST_STR_LEN("SERVER_NAME"), s, strlen(s));
284 
285     rc |= cb(vdata, CONST_STR_LEN("REMOTE_ADDR"),
286                     CONST_BUF_LEN(con->dst_addr_buf));
287 
288     rc |= cb(vdata, CONST_STR_LEN("REMOTE_PORT"), buf,
289              li_utostrn(buf,sizeof(buf),sock_addr_get_port(&con->dst_addr)));
290 
291     for (n = 0; n < r->rqst_headers.used; n++) {
292         data_string *ds = (data_string *)r->rqst_headers.data[n];
293         if (!buffer_string_is_empty(&ds->value) && !buffer_is_empty(&ds->key)) {
294             /* Security: Do not emit HTTP_PROXY in environment.
295              * Some executables use HTTP_PROXY to configure
296              * outgoing proxy.  See also https://httpoxy.org/ */
297             if (ds->ext == HTTP_HEADER_OTHER
298                 && buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Proxy"))) {
299                 continue;
300             }
301             buffer_copy_string_encoded_cgi_varnames(tb,
302                                                     CONST_BUF_LEN(&ds->key), 1);
303             rc |= cb(vdata, CONST_BUF_LEN(tb),
304                             CONST_BUF_LEN(&ds->value));
305         }
306     }
307 
308     con->srv->request_env(r);
309 
310     for (n = 0; n < r->env.used; n++) {
311         data_string *ds = (data_string *)r->env.data[n];
312         if (!buffer_is_empty(&ds->value) && !buffer_is_empty(&ds->key)) {
313             buffer_copy_string_encoded_cgi_varnames(tb,
314                                                     CONST_BUF_LEN(&ds->key), 0);
315             rc |= cb(vdata, CONST_BUF_LEN(tb),
316                             CONST_BUF_LEN(&ds->value));
317         }
318     }
319 
320     return rc;
321 }
322