xref: /lighttpd1.4/src/http_cgi.c (revision 9c8b9ff0)
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 static void
95 http_cgi_encode_varname (buffer * const b, const char * const restrict s, const size_t len, const int is_http_header)
96 {
97     char * const restrict p = buffer_string_prepare_copy(b, len + 5);
98     size_t i, j = 0;
99 
100     if (is_http_header) {
101       #if 0 /*(special-cased in caller that sets is_http_header)*/
102         if (len == 12 && buffer_eq_icase_ssn(s, "Content-Type", 12)) {
103             buffer_copy_string_len(b, CONST_STR_LEN("CONTENT_TYPE"));
104             return;
105         }
106       #endif
107         memcpy(p, "HTTP_", 5);
108         j = 5; /* "HTTP_" */
109     }
110 
111     for (i = 0; i < len; ++i) {/* uppercase alpha, pass numeric, map rest '_' */
112         const unsigned char c = s[i];
113         p[j++] = light_isalpha(c) ? c & ~0x20 : light_isdigit(c) ? c : '_';
114     }
115     buffer_string_set_length(b, j);
116 }
117 
118 
119 int
120 http_cgi_headers (request_st * const r, http_cgi_opts * const opts, http_cgi_header_append_cb cb, void *vdata)
121 {
122     /* CGI-SPEC 6.1.2, FastCGI spec 6.3 and SCGI spec */
123 
124     /* note: string ptrs passed to cb() func must not be NULL */
125 
126     int rc = 0;
127     buffer * const tb = r->tmp_buf;
128     const char *s;
129     size_t n;
130     char buf[INET6_ADDRSTRLEN + 1]; /*(also larger than LI_ITOSTRING_LENGTH)*/
131 
132     /* (CONTENT_LENGTH must be first for SCGI) */
133     if (!opts->authorizer)
134         rc |= cb(vdata, CONST_STR_LEN("CONTENT_LENGTH"),
135                  buf, li_itostrn(buf,sizeof(buf),r->reqbody_length));
136 
137     if (!buffer_string_is_empty(&r->uri.query))
138         rc |= cb(vdata, CONST_STR_LEN("QUERY_STRING"),
139                         CONST_BUF_LEN(&r->uri.query));
140     else
141         rc |= cb(vdata, CONST_STR_LEN("QUERY_STRING"),
142                         CONST_STR_LEN(""));
143 
144     if (!buffer_string_is_empty(opts->strip_request_uri)) {
145         /**
146          * /app1/index/list
147          *
148          * stripping /app1 or /app1/ should lead to
149          *
150          * /index/list
151          *
152          */
153         size_t len = buffer_string_length(opts->strip_request_uri);
154         if ('/' == opts->strip_request_uri->ptr[len-1])
155             --len;
156 
157         if (buffer_string_length(&r->target_orig) >= len
158             && 0 == memcmp(r->target_orig.ptr,
159                            opts->strip_request_uri->ptr, len)
160             && r->target_orig.ptr[len] == '/') {
161             rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"),
162                             r->target_orig.ptr+len,
163                             buffer_string_length(&r->target_orig)-len);
164         }
165         else
166             rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"),
167                             CONST_BUF_LEN(&r->target_orig));
168     }
169     else
170         rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"),
171                         CONST_BUF_LEN(&r->target_orig));
172 
173     if (!buffer_is_equal(&r->target, &r->target_orig))
174         rc |= cb(vdata, CONST_STR_LEN("REDIRECT_URI"),
175                         CONST_BUF_LEN(&r->target));
176 
177     /* set REDIRECT_STATUS for php compiled with --force-redirect
178      * (if REDIRECT_STATUS has not already been set by error handler) */
179     if (0 == r->error_handler_saved_status)
180         rc |= cb(vdata, CONST_STR_LEN("REDIRECT_STATUS"),
181                         CONST_STR_LEN("200"));
182 
183     /*
184      * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
185      * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
186      * (6.1.14, 6.1.6, 6.1.7)
187      */
188     if (!opts->authorizer) {
189         rc |= cb(vdata, CONST_STR_LEN("SCRIPT_NAME"),
190                         CONST_BUF_LEN(&r->uri.path));
191         if (!buffer_string_is_empty(&r->pathinfo)) {
192             rc |= cb(vdata, CONST_STR_LEN("PATH_INFO"),
193                             CONST_BUF_LEN(&r->pathinfo));
194             /* PATH_TRANSLATED is only defined if PATH_INFO is set
195              * Note: not implemented: re-url-encode '?' '=' ';' for
196              * (RFC 3875 4.1.6) */
197             if (!buffer_string_is_empty(opts->docroot))
198                 buffer_copy_buffer(tb, opts->docroot);
199             else
200                 buffer_copy_buffer(tb, &r->physical.basedir);
201             buffer_append_path_len(tb, CONST_BUF_LEN(&r->pathinfo));
202             rc |= cb(vdata, CONST_STR_LEN("PATH_TRANSLATED"),
203                             CONST_BUF_LEN(tb));
204         }
205     }
206 
207    /*
208     * SCRIPT_FILENAME and DOCUMENT_ROOT for php
209     * The PHP manual http://www.php.net/manual/en/reserved.variables.php
210     * treatment of PATH_TRANSLATED is different from the one of CGI specs.
211     * (see php.ini cgi.fix_pathinfo = 1 config parameter)
212     */
213 
214     if (!buffer_string_is_empty(opts->docroot)) {
215         /* alternate docroot, e.g. for remote FastCGI or SCGI server */
216         buffer_copy_buffer(tb, opts->docroot);
217         buffer_append_path_len(tb, CONST_BUF_LEN(&r->uri.path));
218         rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
219                         CONST_BUF_LEN(tb));
220         rc |= cb(vdata, CONST_STR_LEN("DOCUMENT_ROOT"),
221                         CONST_BUF_LEN(opts->docroot));
222     }
223     else {
224         if (opts->break_scriptfilename_for_php) {
225             /* php.ini config cgi.fix_pathinfo = 1 need a broken SCRIPT_FILENAME
226              * to find out what PATH_INFO is itself
227              *
228              * see src/sapi/cgi_main.c, init_request_info()
229              */
230             buffer_copy_buffer(tb, &r->physical.path);
231             buffer_append_path_len(tb, CONST_BUF_LEN(&r->pathinfo));
232             rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
233                             CONST_BUF_LEN(tb));
234         }
235         else
236             rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
237                             CONST_BUF_LEN(&r->physical.path));
238         rc |= cb(vdata, CONST_STR_LEN("DOCUMENT_ROOT"),
239                         CONST_BUF_LEN(&r->physical.basedir));
240     }
241 
242     s = get_http_method_name(r->http_method);
243     force_assert(s);
244     rc |= cb(vdata, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s));
245 
246     s = get_http_version_name(r->http_version);
247     force_assert(s);
248     rc |= cb(vdata, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s));
249 
250     rc |= cb(vdata, CONST_STR_LEN("SERVER_SOFTWARE"),
251                     CONST_BUF_LEN(r->conf.server_tag));
252 
253     rc |= cb(vdata, CONST_STR_LEN("GATEWAY_INTERFACE"),
254                     CONST_STR_LEN("CGI/1.1"));
255 
256     rc |= cb(vdata, CONST_STR_LEN("REQUEST_SCHEME"),
257                     CONST_BUF_LEN(&r->uri.scheme));
258 
259     if (buffer_is_equal_string(&r->uri.scheme, CONST_STR_LEN("https")))
260         rc |= cb(vdata, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
261 
262     const connection * const con = r->con;
263     const server_socket * const srv_sock = con->srv_socket;
264     const size_t tlen = buffer_string_length(srv_sock->srv_token);
265     n = srv_sock->srv_token_colon;
266     if (n < tlen) { /*(n != tlen)*/
267         s = srv_sock->srv_token->ptr+n+1;
268         n = tlen - (n+1);
269     }
270     else {
271         s = "0";
272         n = 1;
273     }
274     rc |= cb(vdata, CONST_STR_LEN("SERVER_PORT"), s, n);
275 
276     n = 0;
277     switch (sock_addr_get_family(&srv_sock->addr)) {
278       case AF_INET:
279       case AF_INET6:
280         if (sock_addr_is_addr_wildcard(&srv_sock->addr)) {
281             sock_addr addrbuf;
282             socklen_t addrlen = sizeof(addrbuf);
283             if (0 == getsockname(con->fd,(struct sockaddr *)&addrbuf,&addrlen)){
284                 /* future: might add a one- or two- element cache
285                  * or use sock_addr_cache_inet_ntop_copy_buffer() into tb */
286                 s = sock_addr_inet_ntop(&addrbuf, buf, sizeof(buf));
287                 if (s)
288                     n = strlen(s);
289                 else
290                     s = "";
291             }
292             else
293                 s = "";
294         }
295         else {
296             s = srv_sock->srv_token->ptr;
297             n = srv_sock->srv_token_colon;
298         }
299         break;
300       default:
301         s = "";
302         break;
303     }
304     rc |= cb(vdata, CONST_STR_LEN("SERVER_ADDR"), s, n);
305 
306     if (!buffer_string_is_empty(r->server_name)) {
307         n = buffer_string_length(r->server_name);
308         s = r->server_name->ptr;
309         if (s[0] == '[') {
310             const char *colon = strstr(s, "]:");
311             if (colon) n = (colon + 1) - s;
312         }
313         else {
314             const char *colon = strchr(s, ':');
315             if (colon) n = colon - s;
316         }
317     } /* else set to be same as SERVER_ADDR (above) */
318     rc |= cb(vdata, CONST_STR_LEN("SERVER_NAME"), s, n);
319 
320     rc |= cb(vdata, CONST_STR_LEN("REMOTE_ADDR"),
321                     CONST_BUF_LEN(con->dst_addr_buf));
322 
323     rc |= cb(vdata, CONST_STR_LEN("REMOTE_PORT"), buf,
324              li_utostrn(buf,sizeof(buf),sock_addr_get_port(&con->dst_addr)));
325 
326     for (n = 0; n < r->rqst_headers.used; n++) {
327         data_string *ds = (data_string *)r->rqst_headers.data[n];
328         if (!buffer_string_is_empty(&ds->value) && !buffer_is_empty(&ds->key)) {
329             /* Security: Do not emit HTTP_PROXY in environment.
330              * Some executables use HTTP_PROXY to configure
331              * outgoing proxy.  See also https://httpoxy.org/ */
332             if (ds->ext == HTTP_HEADER_OTHER
333                 && buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Proxy"))) {
334                 continue;
335             }
336             else if (ds->ext == HTTP_HEADER_CONTENT_TYPE)
337                 buffer_copy_string_len(tb, CONST_STR_LEN("CONTENT_TYPE"));
338             else
339                 http_cgi_encode_varname(tb, CONST_BUF_LEN(&ds->key), 1);
340             rc |= cb(vdata, CONST_BUF_LEN(tb),
341                             CONST_BUF_LEN(&ds->value));
342         }
343     }
344 
345     con->srv->request_env(r);
346 
347     for (n = 0; n < r->env.used; n++) {
348         data_string *ds = (data_string *)r->env.data[n];
349         if (!buffer_is_empty(&ds->value) && !buffer_is_empty(&ds->key)) {
350             http_cgi_encode_varname(tb, CONST_BUF_LEN(&ds->key), 0);
351             rc |= cb(vdata, CONST_BUF_LEN(tb),
352                             CONST_BUF_LEN(&ds->value));
353         }
354     }
355 
356     return rc;
357 }
358