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