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
http_cgi_local_redir(request_st * const r)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_clen(&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
http_cgi_encode_varname(buffer * const b,const char * const restrict s,const size_t len,const int is_http_header)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_truncate(b, j);
115 }
116 
117 
118 int
http_cgi_headers(request_st * const r,http_cgi_opts * const opts,http_cgi_header_append_cb cb,void * vdata)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_clen(&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_clen(&r->target_orig);
143     len = opts->strip_request_uri ? buffer_clen(opts->strip_request_uri) : 0;
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                         BUF_PTR_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                         BUF_PTR_LEN(&r->uri.path));
172         if (!buffer_is_blank(&r->pathinfo)) {
173             rc |= cb(vdata, CONST_STR_LEN("PATH_INFO"),
174                             BUF_PTR_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 = (opts->docroot)
179               ? opts->docroot
180               : &r->physical.basedir;
181             buffer_copy_path_len2(tb, BUF_PTR_LEN(bd),
182                                       BUF_PTR_LEN(&r->pathinfo));
183             rc |= cb(vdata, CONST_STR_LEN("PATH_TRANSLATED"),
184                             BUF_PTR_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 (opts->docroot) {
196         /* alternate docroot, e.g. for remote FastCGI or SCGI server */
197         buffer_copy_path_len2(tb, BUF_PTR_LEN(opts->docroot),
198                                   BUF_PTR_LEN(&r->uri.path));
199         rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
200                         BUF_PTR_LEN(tb));
201         rc |= cb(vdata, CONST_STR_LEN("DOCUMENT_ROOT"),
202                         BUF_PTR_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, BUF_PTR_LEN(&r->physical.path),
212                                       BUF_PTR_LEN(&r->pathinfo));
213             rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
214                             BUF_PTR_LEN(tb));
215         }
216         else
217             rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
218                             BUF_PTR_LEN(&r->physical.path));
219         rc |= cb(vdata, CONST_STR_LEN("DOCUMENT_ROOT"),
220                         BUF_PTR_LEN(&r->physical.basedir));
221     }
222 
223     const buffer * const m = http_method_buf(r->http_method);
224     rc |= cb(vdata, CONST_STR_LEN("REQUEST_METHOD"), BUF_PTR_LEN(m));
225 
226     s = get_http_version_name(r->http_version);
227     force_assert(s);
228     rc |= cb(vdata, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s));
229 
230     if (r->conf.server_tag) {
231         s = r->conf.server_tag->ptr;
232         n = buffer_clen(r->conf.server_tag);
233     }
234     else {
235         s = "";
236         n = 0;
237     }
238     rc |= cb(vdata, CONST_STR_LEN("SERVER_SOFTWARE"), s, n);
239 
240     rc |= cb(vdata, CONST_STR_LEN("GATEWAY_INTERFACE"),
241                     CONST_STR_LEN("CGI/1.1"));
242 
243     rc |= cb(vdata, CONST_STR_LEN("REQUEST_SCHEME"),
244                     BUF_PTR_LEN(&r->uri.scheme));
245 
246     if (buffer_is_equal_string(&r->uri.scheme, CONST_STR_LEN("https")))
247         rc |= cb(vdata, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
248 
249     const connection * const con = r->con;
250     const server_socket * const srv_sock = con->srv_socket;
251     const size_t tlen = buffer_clen(srv_sock->srv_token);
252     n = srv_sock->srv_token_colon;
253     if (n < tlen) { /*(n != tlen)*/
254         s = srv_sock->srv_token->ptr+n+1;
255         n = tlen - (n+1);
256     }
257     else {
258         s = "0";
259         n = 1;
260     }
261     rc |= cb(vdata, CONST_STR_LEN("SERVER_PORT"), s, n);
262 
263     n = 0;
264     switch (sock_addr_get_family(&srv_sock->addr)) {
265       case AF_INET:
266       case AF_INET6:
267         if (sock_addr_is_addr_wildcard(&srv_sock->addr)) {
268             sock_addr addrbuf;
269             socklen_t addrlen = sizeof(addrbuf);
270             if (0 == getsockname(con->fd,(struct sockaddr *)&addrbuf,&addrlen)){
271                 /* future: might add a one- or two- element cache
272                  * or use sock_addr_cache_inet_ntop_copy_buffer() into tb */
273                 s = sock_addr_inet_ntop(&addrbuf, buf, sizeof(buf));
274                 if (s)
275                     n = strlen(s);
276                 else
277                     s = "";
278             }
279             else
280                 s = "";
281         }
282         else {
283             s = srv_sock->srv_token->ptr;
284             n = srv_sock->srv_token_colon;
285         }
286         break;
287       default:
288         s = "";
289         break;
290     }
291     rc |= cb(vdata, CONST_STR_LEN("SERVER_ADDR"), s, n);
292 
293     n = buffer_clen(r->server_name);
294     if (n) {
295         s = r->server_name->ptr;
296         if (s[0] == '[') {
297             const char *colon = strstr(s, "]:");
298             if (colon) n = (colon + 1) - s;
299         }
300         else {
301             const char *colon = strchr(s, ':');
302             if (colon) n = colon - s;
303         }
304     } /* else set to be same as SERVER_ADDR (above) */
305     rc |= cb(vdata, CONST_STR_LEN("SERVER_NAME"), s, n);
306 
307     rc |= cb(vdata, CONST_STR_LEN("REMOTE_ADDR"),
308                     BUF_PTR_LEN(&con->dst_addr_buf));
309 
310     rc |= cb(vdata, CONST_STR_LEN("REMOTE_PORT"), buf,
311              li_utostrn(buf,sizeof(buf),sock_addr_get_port(&con->dst_addr)));
312 
313     for (n = 0; n < r->rqst_headers.used; n++) {
314         data_string *ds = (data_string *)r->rqst_headers.data[n];
315         if (!buffer_is_blank(&ds->value) && !buffer_is_unset(&ds->key)) {
316             /* Security: Do not emit HTTP_PROXY in environment.
317              * Some executables use HTTP_PROXY to configure
318              * outgoing proxy.  See also https://httpoxy.org/ */
319             if (ds->ext == HTTP_HEADER_OTHER
320                 && buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Proxy"))) {
321                 continue;
322             }
323             else if (ds->ext == HTTP_HEADER_CONTENT_TYPE)
324                 buffer_copy_string_len(tb, CONST_STR_LEN("CONTENT_TYPE"));
325             else
326                 http_cgi_encode_varname(tb, BUF_PTR_LEN(&ds->key), 1);
327             rc |= cb(vdata, BUF_PTR_LEN(tb),
328                             BUF_PTR_LEN(&ds->value));
329         }
330     }
331 
332     con->srv->request_env(r);
333 
334     for (n = 0; n < r->env.used; n++) {
335         data_string *ds = (data_string *)r->env.data[n];
336         if (!buffer_is_unset(&ds->value) && !buffer_is_unset(&ds->key)) {
337             http_cgi_encode_varname(tb, BUF_PTR_LEN(&ds->key), 0);
338             rc |= cb(vdata, BUF_PTR_LEN(tb),
339                             BUF_PTR_LEN(&ds->value));
340         }
341     }
342 
343     return rc;
344 }
345