xref: /lighttpd1.4/src/mod_proxy.c (revision dc01487e)
1 #include "first.h"
2 
3 #include <string.h>
4 #include <stdlib.h>
5 
6 #include "gw_backend.h"
7 #include "base.h"
8 #include "array.h"
9 #include "buffer.h"
10 #include "fdevent.h"
11 #include "http_kv.h"
12 #include "http_header.h"
13 #include "log.h"
14 #include "sock_addr.h"
15 #include "status_counter.h"
16 
17 /**
18  *
19  * HTTP reverse proxy
20  *
21  * TODO:      - HTTP/1.1
22  *            - HTTP/1.1 persistent connection with upstream servers
23  */
24 
25 /* (future: might split struct and move part to http-header-glue.c) */
26 typedef struct http_header_remap_opts {
27     const array *urlpaths;
28     const array *hosts_request;
29     const array *hosts_response;
30     int force_http10;
31     int https_remap;
32     int upgrade;
33     int connect_method;
34     /*(not used in plugin_config, but used in handler_ctx)*/
35     const buffer *http_host;
36     const buffer *forwarded_host;
37     const data_string *forwarded_urlpath;
38 } http_header_remap_opts;
39 
40 typedef enum {
41 	PROXY_FORWARDED_NONE         = 0x00,
42 	PROXY_FORWARDED_FOR          = 0x01,
43 	PROXY_FORWARDED_PROTO        = 0x02,
44 	PROXY_FORWARDED_HOST         = 0x04,
45 	PROXY_FORWARDED_BY           = 0x08,
46 	PROXY_FORWARDED_REMOTE_USER  = 0x10
47 } proxy_forwarded_t;
48 
49 typedef struct {
50     gw_plugin_config gw; /* start must match layout of gw_plugin_config */
51     unsigned int replace_http_host;
52     unsigned int forwarded;
53     http_header_remap_opts header;
54 } plugin_config;
55 
56 typedef struct {
57     PLUGIN_DATA;
58     pid_t srv_pid; /* must match layout of gw_plugin_data through conf member */
59     plugin_config conf;
60     plugin_config defaults;
61 } plugin_data;
62 
63 static int proxy_check_extforward;
64 
65 typedef struct {
66 	gw_handler_ctx gw;
67 	http_response_opts opts;
68 	plugin_config conf;
69 } handler_ctx;
70 
71 
72 INIT_FUNC(mod_proxy_init) {
73     return calloc(1, sizeof(plugin_data));
74 }
75 
76 
77 static void mod_proxy_free_config(plugin_data * const p)
78 {
79     if (NULL == p->cvlist) return;
80     /* (init i to 0 if global context; to 1 to skip empty global context) */
81     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
82         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
83         for (; -1 != cpv->k_id; ++cpv) {
84             switch (cpv->k_id) {
85               case 5: /* proxy.header */
86                 if (cpv->vtype == T_CONFIG_LOCAL) free(cpv->v.v);
87                 break;
88               default:
89                 break;
90             }
91         }
92     }
93 }
94 
95 
96 FREE_FUNC(mod_proxy_free) {
97     plugin_data * const p = p_d;
98     mod_proxy_free_config(p);
99     gw_free(p);
100 }
101 
102 static void mod_proxy_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv)
103 {
104     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
105       case 0: /* proxy.server */
106         if (cpv->vtype == T_CONFIG_LOCAL) {
107             gw_plugin_config * const gw = cpv->v.v;
108             pconf->gw.exts      = gw->exts;
109             pconf->gw.exts_auth = gw->exts_auth;
110             pconf->gw.exts_resp = gw->exts_resp;
111         }
112         break;
113       case 1: /* proxy.balance */
114         /*if (cpv->vtype == T_CONFIG_LOCAL)*//*always true here for this param*/
115             pconf->gw.balance = (int)cpv->v.u;
116         break;
117       case 2: /* proxy.debug */
118         pconf->gw.debug = (int)cpv->v.u;
119         break;
120       case 3: /* proxy.map-extensions */
121         pconf->gw.ext_mapping = cpv->v.a;
122         break;
123       case 4: /* proxy.forwarded */
124         /*if (cpv->vtype == T_CONFIG_LOCAL)*//*always true here for this param*/
125             pconf->forwarded = cpv->v.u;
126         break;
127       case 5: /* proxy.header */
128         /*if (cpv->vtype == T_CONFIG_LOCAL)*//*always true here for this param*/
129         pconf->header = *(http_header_remap_opts *)cpv->v.v; /*(copies struct)*/
130         break;
131       case 6: /* proxy.replace-http-host */
132         pconf->replace_http_host = cpv->v.u;
133         break;
134       default:/* should not happen */
135         return;
136     }
137 }
138 
139 
140 static void mod_proxy_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv)
141 {
142     do {
143         mod_proxy_merge_config_cpv(pconf, cpv);
144     } while ((++cpv)->k_id != -1);
145 }
146 
147 
148 static void mod_proxy_patch_config(request_st * const r, plugin_data * const p)
149 {
150     memcpy(&p->conf, &p->defaults, sizeof(plugin_config));
151     for (int i = 1, used = p->nconfig; i < used; ++i) {
152         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
153             mod_proxy_merge_config(&p->conf, p->cvlist+p->cvlist[i].v.u2[0]);
154     }
155 }
156 
157 
158 static unsigned int mod_proxy_parse_forwarded(server *srv, const array *a)
159 {
160     unsigned int forwarded = 0;
161     for (uint32_t j = 0, used = a->used; j < used; ++j) {
162         proxy_forwarded_t param;
163         data_unset *du = a->data[j];
164         if (buffer_eq_slen(&du->key, CONST_STR_LEN("by")))
165             param = PROXY_FORWARDED_BY;
166         else if (buffer_eq_slen(&du->key, CONST_STR_LEN("for")))
167             param = PROXY_FORWARDED_FOR;
168         else if (buffer_eq_slen(&du->key, CONST_STR_LEN("host")))
169             param = PROXY_FORWARDED_HOST;
170         else if (buffer_eq_slen(&du->key, CONST_STR_LEN("proto")))
171             param = PROXY_FORWARDED_PROTO;
172         else if (buffer_eq_slen(&du->key, CONST_STR_LEN("remote_user")))
173             param = PROXY_FORWARDED_REMOTE_USER;
174         else {
175             log_error(srv->errh, __FILE__, __LINE__,
176               "proxy.forwarded keys must be one of: "
177               "by, for, host, proto, remote_user, but not: %s", du->key.ptr);
178             return UINT_MAX;
179         }
180         int val = config_plugin_value_tobool(du, 2);
181         if (2 == val) {
182             log_error(srv->errh, __FILE__, __LINE__,
183               "proxy.forwarded values must be one of: "
184               "0, 1, enable, disable; error for key: %s", du->key.ptr);
185             return UINT_MAX;
186         }
187         if (val)
188             forwarded |= param;
189     }
190     return forwarded;
191 }
192 
193 
194 static http_header_remap_opts * mod_proxy_parse_header_opts(server *srv, const array *a)
195 {
196     http_header_remap_opts header;
197     memset(&header, 0, sizeof(header));
198     for (uint32_t j = 0, used = a->used; j < used; ++j) {
199         data_array *da = (data_array *)a->data[j];
200         if (buffer_eq_slen(&da->key, CONST_STR_LEN("https-remap"))) {
201             int val = config_plugin_value_tobool((data_unset *)da, 2);
202             if (2 == val) {
203                 log_error(srv->errh, __FILE__, __LINE__,
204                   "unexpected value for proxy.header; "
205                   "expected \"https-remap\" => \"enable\" or \"disable\"");
206                 return NULL;
207             }
208             header.https_remap = val;
209             continue;
210         }
211         else if (buffer_eq_slen(&da->key, CONST_STR_LEN("force-http10"))) {
212             int val = config_plugin_value_tobool((data_unset *)da, 2);
213             if (2 == val) {
214                 log_error(srv->errh, __FILE__, __LINE__,
215                   "unexpected value for proxy.header; "
216                   "expected \"force-http10\" => \"enable\" or \"disable\"");
217                 return NULL;
218             }
219             header.force_http10 = val;
220             continue;
221         }
222         else if (buffer_eq_slen(&da->key, CONST_STR_LEN("upgrade"))) {
223             int val = config_plugin_value_tobool((data_unset *)da, 2);
224             if (2 == val) {
225                 log_error(srv->errh, __FILE__, __LINE__,
226                   "unexpected value for proxy.header; "
227                   "expected \"upgrade\" => \"enable\" or \"disable\"");
228                 return NULL;
229             }
230             header.upgrade = val;
231             continue;
232         }
233         else if (buffer_eq_slen(&da->key, CONST_STR_LEN("connect"))) {
234             int val = config_plugin_value_tobool((data_unset *)da, 2);
235             if (2 == val) {
236                 log_error(srv->errh, __FILE__, __LINE__,
237                   "unexpected value for proxy.header; "
238                   "expected \"connect\" => \"enable\" or \"disable\"");
239                 return NULL;
240             }
241             header.connect_method = val;
242             continue;
243         }
244         if (da->type != TYPE_ARRAY || !array_is_kvstring(&da->value)) {
245             log_error(srv->errh, __FILE__, __LINE__,
246               "unexpected value for proxy.header; "
247               "expected ( \"param\" => ( \"key\" => \"value\" ) ) near key %s",
248               da->key.ptr);
249             return NULL;
250         }
251         if (buffer_eq_slen(&da->key, CONST_STR_LEN("map-urlpath"))) {
252             header.urlpaths = &da->value;
253         }
254         else if (buffer_eq_slen(&da->key, CONST_STR_LEN("map-host-request"))) {
255             header.hosts_request = &da->value;
256         }
257         else if (buffer_eq_slen(&da->key, CONST_STR_LEN("map-host-response"))) {
258             header.hosts_response = &da->value;
259         }
260         else {
261             log_error(srv->errh, __FILE__, __LINE__,
262               "unexpected key for proxy.header; "
263               "expected ( \"param\" => ( \"key\" => \"value\" ) ) near key %s",
264               da->key.ptr);
265             return NULL;
266         }
267     }
268 
269     http_header_remap_opts *opts = malloc(sizeof(header));
270     force_assert(opts);
271     memcpy(opts, &header, sizeof(header));
272     return opts;
273 }
274 
275 
276 SETDEFAULTS_FUNC(mod_proxy_set_defaults)
277 {
278     static const config_plugin_keys_t cpk[] = {
279       { CONST_STR_LEN("proxy.server"),
280         T_CONFIG_ARRAY_KVARRAY,
281         T_CONFIG_SCOPE_CONNECTION }
282      ,{ CONST_STR_LEN("proxy.balance"),
283         T_CONFIG_STRING,
284         T_CONFIG_SCOPE_CONNECTION }
285      ,{ CONST_STR_LEN("proxy.debug"),
286         T_CONFIG_INT,
287         T_CONFIG_SCOPE_CONNECTION }
288      ,{ CONST_STR_LEN("proxy.map-extensions"),
289         T_CONFIG_ARRAY_KVSTRING,
290         T_CONFIG_SCOPE_CONNECTION }
291      ,{ CONST_STR_LEN("proxy.forwarded"),
292         T_CONFIG_ARRAY_KVANY,
293         T_CONFIG_SCOPE_CONNECTION }
294      ,{ CONST_STR_LEN("proxy.header"),
295         T_CONFIG_ARRAY_KVANY,
296         T_CONFIG_SCOPE_CONNECTION }
297      ,{ CONST_STR_LEN("proxy.replace-http-host"),
298         T_CONFIG_BOOL,
299         T_CONFIG_SCOPE_CONNECTION }
300      ,{ NULL, 0,
301         T_CONFIG_UNSET,
302         T_CONFIG_SCOPE_UNSET }
303     };
304 
305     plugin_data * const p = p_d;
306     if (!config_plugin_values_init(srv, p, cpk, "mod_proxy"))
307         return HANDLER_ERROR;
308 
309     /* process and validate config directives
310      * (init i to 0 if global context; to 1 to skip empty global context) */
311     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
312         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
313         gw_plugin_config *gw = NULL;
314         for (; -1 != cpv->k_id; ++cpv) {
315             switch (cpv->k_id) {
316               case 0: /* proxy.server */
317                 gw = calloc(1, sizeof(gw_plugin_config));
318                 force_assert(gw);
319                 if (!gw_set_defaults_backend(srv, (gw_plugin_data *)p, cpv->v.a,
320                                              gw, 0, cpk[cpv->k_id].k)) {
321                     gw_plugin_config_free(gw);
322                     return HANDLER_ERROR;
323                 }
324                 /* error if "mode" = "authorizer";
325                  * proxy can not act as authorizer */
326                 /*(check after gw_set_defaults_backend())*/
327                 if (gw->exts_auth && gw->exts_auth->used) {
328                     log_error(srv->errh, __FILE__, __LINE__,
329                       "%s must not define any hosts with "
330                       "attribute \"mode\" = \"authorizer\"", cpk[cpv->k_id].k);
331                     gw_plugin_config_free(gw);
332                     return HANDLER_ERROR;
333                 }
334                 cpv->v.v = gw;
335                 cpv->vtype = T_CONFIG_LOCAL;
336                 break;
337               case 1: /* proxy.balance */
338                 cpv->v.u = (unsigned int)gw_get_defaults_balance(srv, cpv->v.b);
339                 break;
340               case 2: /* proxy.debug */
341               case 3: /* proxy.map-extensions */
342                 break;
343               case 4: /* proxy.forwarded */
344                 cpv->v.u = mod_proxy_parse_forwarded(srv, cpv->v.a);
345                 if (UINT_MAX == cpv->v.u) return HANDLER_ERROR;
346                 cpv->vtype = T_CONFIG_LOCAL;
347                 break;
348               case 5: /* proxy.header */
349                 cpv->v.v = mod_proxy_parse_header_opts(srv, cpv->v.a);
350                 if (NULL == cpv->v.v) return HANDLER_ERROR;
351                 cpv->vtype = T_CONFIG_LOCAL;
352                 break;
353               case 6: /* proxy.replace-http-host */
354                 break;
355               default:/* should not happen */
356                 break;
357             }
358         }
359 
360         /* disable check-local for all exts (default enabled) */
361         if (gw && gw->exts) { /*(check after gw_set_defaults_backend())*/
362             gw_exts_clear_check_local(gw->exts);
363         }
364     }
365 
366     /* default is 0 */
367     /*p->defaults.balance = (unsigned int)gw_get_defaults_balance(srv, NULL);*/
368 
369     p->defaults.header.force_http10 =
370       srv->srvconf.feature_flags
371       && config_plugin_value_tobool(
372            array_get_element_klen(srv->srvconf.feature_flags,
373                                   CONST_STR_LEN("proxy.force-http10")), 0);
374 
375     /* initialize p->defaults from global config context */
376     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
377         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
378         if (-1 != cpv->k_id)
379             mod_proxy_merge_config(&p->defaults, cpv);
380     }
381 
382     /* special-case behavior if mod_extforward is loaded */
383     for (uint32_t i = 0; i < srv->srvconf.modules->used; ++i) {
384         buffer *m = &((data_string *)srv->srvconf.modules->data[i])->value;
385         if (buffer_eq_slen(m, CONST_STR_LEN("mod_extforward"))) {
386             proxy_check_extforward = 1;
387             break;
388         }
389     }
390 
391     return HANDLER_GO_ON;
392 }
393 
394 
395 /* (future: might move to http-header-glue.c) */
396 static const buffer * http_header_remap_host_match (buffer *b, size_t off, http_header_remap_opts *remap_hdrs, int is_req, size_t alen)
397 {
398     const array *hosts = is_req
399       ? remap_hdrs->hosts_request
400       : remap_hdrs->hosts_response;
401     if (hosts) {
402         const char * const s = b->ptr+off;
403         for (size_t i = 0, used = hosts->used; i < used; ++i) {
404             const data_string * const ds = (data_string *)hosts->data[i];
405             const buffer *k = &ds->key;
406             size_t mlen = buffer_string_length(k);
407             if (1 == mlen && k->ptr[0] == '-') {
408                 /* match with authority provided in Host (if is_req)
409                  * (If no Host in client request, then matching against empty
410                  *  string will probably not match, and no remap will be
411                  *  performed) */
412                 k = is_req
413                   ? remap_hdrs->http_host
414                   : remap_hdrs->forwarded_host;
415                 if (NULL == k) continue;
416                 mlen = buffer_string_length(k);
417             }
418             if (buffer_eq_icase_ss(s, alen, k->ptr, mlen)) {
419                 if (buffer_is_equal_string(&ds->value, CONST_STR_LEN("-"))) {
420                     return remap_hdrs->http_host;
421                 }
422                 else if (!buffer_string_is_empty(&ds->value)) {
423                     /*(save first matched request host for response match)*/
424                     if (is_req && NULL == remap_hdrs->forwarded_host)
425                         remap_hdrs->forwarded_host = &ds->value;
426                     return &ds->value;
427                 } /*(else leave authority as-is and stop matching)*/
428                 break;
429             }
430         }
431     }
432     return NULL;
433 }
434 
435 
436 /* (future: might move to http-header-glue.c) */
437 static size_t http_header_remap_host (buffer *b, size_t off, http_header_remap_opts *remap_hdrs, int is_req, size_t alen)
438 {
439     const buffer * const m =
440       http_header_remap_host_match(b, off, remap_hdrs, is_req, alen);
441     if (NULL == m) return alen; /*(no match; return original authority length)*/
442 
443     buffer_substr_replace(b, off, alen, m);
444     return buffer_string_length(m); /*(length of replacement authority)*/
445 }
446 
447 
448 /* (future: might move to http-header-glue.c) */
449 static size_t http_header_remap_urlpath (buffer *b, size_t off, http_header_remap_opts *remap_hdrs, int is_req)
450 {
451     const array *urlpaths = remap_hdrs->urlpaths;
452     if (urlpaths) {
453         const char * const s = b->ptr+off;
454         const size_t plen = buffer_string_length(b) - off; /*(urlpath len)*/
455         if (is_req) { /* request */
456             for (size_t i = 0, used = urlpaths->used; i < used; ++i) {
457                 const data_string * const ds = (data_string *)urlpaths->data[i];
458                 const size_t mlen = buffer_string_length(&ds->key);
459                 if (mlen <= plen && 0 == memcmp(s, ds->key.ptr, mlen)) {
460                     if (NULL == remap_hdrs->forwarded_urlpath)
461                         remap_hdrs->forwarded_urlpath = ds;
462                     buffer_substr_replace(b, off, mlen, &ds->value);
463                     return buffer_string_length(&ds->value);/*(replacement len)*/
464                 }
465             }
466         }
467         else {        /* response; perform reverse map */
468             if (NULL != remap_hdrs->forwarded_urlpath) {
469                 const data_string * const ds = remap_hdrs->forwarded_urlpath;
470                 const size_t mlen = buffer_string_length(&ds->value);
471                 if (mlen <= plen && 0 == memcmp(s, ds->value.ptr, mlen)) {
472                     buffer_substr_replace(b, off, mlen, &ds->key);
473                     return buffer_string_length(&ds->key); /*(replacement len)*/
474                 }
475             }
476             for (size_t i = 0, used = urlpaths->used; i < used; ++i) {
477                 const data_string * const ds = (data_string *)urlpaths->data[i];
478                 const size_t mlen = buffer_string_length(&ds->value);
479                 if (mlen <= plen && 0 == memcmp(s, ds->value.ptr, mlen)) {
480                     buffer_substr_replace(b, off, mlen, &ds->key);
481                     return buffer_string_length(&ds->key); /*(replacement len)*/
482                 }
483             }
484         }
485     }
486     return 0;
487 }
488 
489 
490 /* (future: might move to http-header-glue.c) */
491 static void http_header_remap_uri (buffer *b, size_t off, http_header_remap_opts *remap_hdrs, int is_req)
492 {
493     /* find beginning of URL-path (might be preceded by scheme://authority
494      * (caller should make sure any leading whitespace is prior to offset) */
495     if (b->ptr[off] != '/') {
496         char *s = b->ptr+off;
497         size_t alen; /*(authority len (host len))*/
498         size_t slen; /*(scheme len)*/
499         const buffer *m;
500         /* skip over scheme and authority of URI to find beginning of URL-path
501          * (value might conceivably be relative URL-path instead of URI) */
502         if (NULL == (s = strchr(s, ':')) || s[1] != '/' || s[2] != '/') return;
503         slen = s - (b->ptr+off);
504         s += 3;
505         off = (size_t)(s - b->ptr);
506         if (NULL != (s = strchr(s, '/'))) {
507             alen = (size_t)(s - b->ptr) - off;
508             if (0 == alen) return; /*(empty authority, e.g. "http:///")*/
509         }
510         else {
511             alen = buffer_string_length(b) - off;
512             if (0 == alen) return; /*(empty authority, e.g. "http:///")*/
513             buffer_append_string_len(b, CONST_STR_LEN("/"));
514         }
515 
516         /* remap authority (if configured) and set offset to url-path */
517         m = http_header_remap_host_match(b, off, remap_hdrs, is_req, alen);
518         if (NULL != m) {
519             if (remap_hdrs->https_remap
520                 && (is_req ? 5==slen && 0==memcmp(b->ptr+off-slen-3,"https",5)
521                            : 4==slen && 0==memcmp(b->ptr+off-slen-3,"http",4))){
522                 if (is_req) {
523                     memcpy(b->ptr+off-slen-3+4,"://",3);  /*("https"=>"http")*/
524                     --off;
525                     ++alen;
526                 }
527                 else {/*(!is_req)*/
528                     memcpy(b->ptr+off-slen-3+4,"s://",4); /*("http" =>"https")*/
529                     ++off;
530                     --alen;
531                 }
532             }
533             buffer_substr_replace(b, off, alen, m);
534             alen = buffer_string_length(m);/*(length of replacement authority)*/
535         }
536         off += alen;
537     }
538 
539     /* remap URLs (if configured) */
540     http_header_remap_urlpath(b, off, remap_hdrs, is_req);
541 }
542 
543 
544 /* (future: might move to http-header-glue.c) */
545 static void http_header_remap_setcookie (buffer *b, size_t off, http_header_remap_opts *remap_hdrs)
546 {
547     /* Given the special-case of Set-Cookie and the (too) loosely restricted
548      * characters allowed, for best results, the Set-Cookie value should be the
549      * entire string in b from offset to end of string.  In response headers,
550      * lighttpd may concatenate multiple Set-Cookie headers into single entry
551      * in r->resp_headers, separated by "\r\nSet-Cookie: " */
552     for (char *s = b->ptr+off, *e; *s; s = e) {
553         size_t len;
554         {
555             while (*s != ';' && *s != '\n' && *s != '\0') ++s;
556             if (*s == '\n') {
557                 /*(include +1 for '\n', but leave ' ' for ++s below)*/
558                 s += sizeof("Set-Cookie:");
559             }
560             if ('\0' == *s) return;
561             do { ++s; } while (*s == ' ' || *s == '\t');
562             if ('\0' == *s) return;
563             e = s+1;
564             if ('=' == *s) continue;
565             /*(interested only in Domain and Path attributes)*/
566             while (*e != '=' && *e != '\0') ++e;
567             if ('\0' == *e) return;
568             ++e;
569             switch ((int)(e - s - 1)) {
570               case 4:
571                 if (buffer_eq_icase_ssn(s, "path", 4)) {
572                     if (*e == '"') ++e;
573                     if (*e != '/') continue;
574                     off = (size_t)(e - b->ptr);
575                     len = http_header_remap_urlpath(b, off, remap_hdrs, 0);
576                     e = b->ptr+off+len; /*(b may have been reallocated)*/
577                     continue;
578                 }
579                 break;
580               case 6:
581                 if (buffer_eq_icase_ssn(s, "domain", 6)) {
582                     size_t alen = 0;
583                     if (*e == '"') ++e;
584                     if (*e == '.') ++e;
585                     if (*e == ';') continue;
586                     off = (size_t)(e - b->ptr);
587                     for (char c; (c = e[alen]) != ';' && c != ' ' && c != '\t'
588                                           && c != '\r' && c != '\0'; ++alen);
589                     len = http_header_remap_host(b, off, remap_hdrs, 0, alen);
590                     e = b->ptr+off+len; /*(b may have been reallocated)*/
591                     continue;
592                 }
593                 break;
594               default:
595                 break;
596             }
597         }
598     }
599 }
600 
601 
602 static void buffer_append_string_backslash_escaped(buffer *b, const char *s, size_t len) {
603     /* (future: might move to buffer.c) */
604     size_t j = 0;
605     char *p;
606 
607     buffer_string_prepare_append(b, len*2 + 4);
608     p = b->ptr + buffer_string_length(b);
609 
610     for (size_t i = 0; i < len; ++i) {
611         int c = s[i];
612         if (c == '"' || c == '\\' || c == 0x7F || (c < 0x20 && c != '\t'))
613             p[j++] = '\\';
614         p[j++] = c;
615     }
616 
617     buffer_commit(b, j);
618 }
619 
620 static void proxy_set_Forwarded(connection * const con, request_st * const r, const unsigned int flags) {
621     buffer *b = NULL, *efor = NULL, *eproto = NULL, *ehost = NULL;
622     int semicolon = 0;
623 
624     if (proxy_check_extforward) {
625         efor   =
626           http_header_env_get(r, CONST_STR_LEN("_L_EXTFORWARD_ACTUAL_FOR"));
627         eproto =
628           http_header_env_get(r, CONST_STR_LEN("_L_EXTFORWARD_ACTUAL_PROTO"));
629         ehost  =
630           http_header_env_get(r, CONST_STR_LEN("_L_EXTFORWARD_ACTUAL_HOST"));
631     }
632 
633     /* note: set "Forwarded" prior to updating X-Forwarded-For (below) */
634 
635     if (flags)
636         b = http_header_request_get(r, HTTP_HEADER_FORWARDED, CONST_STR_LEN("Forwarded"));
637 
638     if (flags && NULL == b) {
639         const buffer *xff =
640           http_header_request_get(r, HTTP_HEADER_X_FORWARDED_FOR, CONST_STR_LEN("X-Forwarded-For"));
641         b = http_header_request_set_ptr(r, HTTP_HEADER_FORWARDED,
642                                         CONST_STR_LEN("Forwarded"));
643         if (NULL != xff) {
644             /* use X-Forwarded-For contents to seed Forwarded */
645             char *s = xff->ptr;
646             size_t used = buffer_string_length(xff);
647             for (size_t i=0, j, ipv6; i < used; ++i) {
648                 while (s[i] == ' ' || s[i] == '\t' || s[i] == ',') ++i;
649                 if (s[i] == '\0') break;
650                 j = i;
651                 do {
652                     ++i;
653                 } while (s[i]!=' ' && s[i]!='\t' && s[i]!=',' && s[i]!='\0');
654                 /* over-simplified test expecting only IPv4 or IPv6 addresses,
655                  * (not expecting :port, so treat existence of colon as IPv6,
656                  *  and not expecting unix paths, especially not containing ':')
657                  * quote all strings, backslash-escape since IPs not validated*/
658                 ipv6 = (NULL != memchr(s+j, ':', i-j)); /*(over-simplified) */
659                 ipv6
660                   ? buffer_append_string_len(b, CONST_STR_LEN("for=\"["))
661                   : buffer_append_string_len(b, CONST_STR_LEN("for=\""));
662                 buffer_append_string_backslash_escaped(b, s+j, i-j);
663                 ipv6
664                   ? buffer_append_string_len(b, CONST_STR_LEN("]\", "))
665                   : buffer_append_string_len(b, CONST_STR_LEN("\", "));
666             }
667         }
668     } else if (flags) { /*(NULL != b)*/
669         buffer_append_string_len(b, CONST_STR_LEN(", "));
670     }
671 
672     if (flags & PROXY_FORWARDED_FOR) {
673         int family = sock_addr_get_family(&con->dst_addr);
674         buffer_append_string_len(b, CONST_STR_LEN("for="));
675         if (NULL != efor) {
676             /* over-simplified test expecting only IPv4 or IPv6 addresses,
677              * (not expecting :port, so treat existence of colon as IPv6,
678              *  and not expecting unix paths, especially not containing ':')
679              * quote all strings and backslash-escape since IPs not validated
680              * (should be IP from original con->dst_addr_buf,
681              *  so trustable and without :port) */
682             int ipv6 = (NULL != strchr(efor->ptr, ':'));
683             ipv6
684               ? buffer_append_string_len(b, CONST_STR_LEN("\"["))
685               : buffer_append_string_len(b, CONST_STR_LEN("\""));
686             buffer_append_string_backslash_escaped(b, CONST_BUF_LEN(efor));
687             ipv6
688               ? buffer_append_string_len(b, CONST_STR_LEN("]\""))
689               : buffer_append_string_len(b, CONST_STR_LEN("\""));
690         } else if (family == AF_INET) {
691             /*(Note: if :port is added, then must be quoted-string:
692              * e.g. for="...:port")*/
693             buffer_append_string_buffer(b, con->dst_addr_buf);
694         } else if (family == AF_INET6) {
695             buffer_append_str3(b, CONST_STR_LEN("\"["),
696                                   CONST_BUF_LEN(con->dst_addr_buf),
697                                   CONST_STR_LEN("]\""));
698         } else {
699             buffer_append_string_len(b, CONST_STR_LEN("\""));
700             buffer_append_string_backslash_escaped(
701               b, CONST_BUF_LEN(con->dst_addr_buf));
702             buffer_append_string_len(b, CONST_STR_LEN("\""));
703         }
704         semicolon = 1;
705     }
706 
707     if (flags & PROXY_FORWARDED_BY) {
708         int family = sock_addr_get_family(&con->srv_socket->addr);
709         /* Note: getsockname() and inet_ntop() are expensive operations.
710          * (recommendation: do not to enable by=... unless required)
711          * future: might use con->srv_socket->srv_token if addr is not
712          *   INADDR_ANY or in6addr_any, but must omit optional :port
713          *   from con->srv_socket->srv_token for consistency */
714 
715         if (semicolon) buffer_append_string_len(b, CONST_STR_LEN(";"));
716         buffer_append_string_len(b, CONST_STR_LEN("by=\""));
717       #ifdef HAVE_SYS_UN_H
718         /* special-case: might need to encode unix domain socket path */
719         if (family == AF_UNIX) {
720             buffer_append_string_backslash_escaped(
721               b, CONST_BUF_LEN(con->srv_socket->srv_token));
722         }
723         else
724       #endif
725         {
726             sock_addr addr;
727             socklen_t addrlen = sizeof(addr);
728             if (0 == getsockname(con->fd,(struct sockaddr *)&addr, &addrlen)) {
729                 sock_addr_stringify_append_buffer(b, &addr);
730             }
731         }
732         buffer_append_string_len(b, CONST_STR_LEN("\""));
733         semicolon = 1;
734     }
735 
736     if (flags & PROXY_FORWARDED_PROTO) {
737         /* expecting "http" or "https"
738          * (not checking if quoted-string and encoding needed) */
739         if (semicolon) buffer_append_string_len(b, CONST_STR_LEN(";"));
740         if (NULL != eproto) {
741             buffer_append_str2(b,CONST_STR_LEN("proto="),CONST_BUF_LEN(eproto));
742         } else if (con->srv_socket->is_ssl) {
743             buffer_append_string_len(b, CONST_STR_LEN("proto=https"));
744         } else {
745             buffer_append_string_len(b, CONST_STR_LEN("proto=http"));
746         }
747         semicolon = 1;
748     }
749 
750     if (flags & PROXY_FORWARDED_HOST) {
751         if (NULL != ehost) {
752             if (semicolon)
753                 buffer_append_string_len(b, CONST_STR_LEN(";"));
754             buffer_append_string_len(b, CONST_STR_LEN("host=\""));
755             buffer_append_string_backslash_escaped(
756               b, CONST_BUF_LEN(ehost));
757             buffer_append_string_len(b, CONST_STR_LEN("\""));
758             semicolon = 1;
759         } else if (!buffer_string_is_empty(r->http_host)) {
760             if (semicolon)
761                 buffer_append_string_len(b, CONST_STR_LEN(";"));
762             buffer_append_string_len(b, CONST_STR_LEN("host=\""));
763             buffer_append_string_backslash_escaped(
764               b, CONST_BUF_LEN(r->http_host));
765             buffer_append_string_len(b, CONST_STR_LEN("\""));
766             semicolon = 1;
767         }
768     }
769 
770     if (flags & PROXY_FORWARDED_REMOTE_USER) {
771         const buffer *remote_user =
772           http_header_env_get(r, CONST_STR_LEN("REMOTE_USER"));
773         if (NULL != remote_user) {
774             if (semicolon)
775                 buffer_append_string_len(b, CONST_STR_LEN(";"));
776             buffer_append_string_len(b, CONST_STR_LEN("remote_user=\""));
777             buffer_append_string_backslash_escaped(
778               b, CONST_BUF_LEN(remote_user));
779             buffer_append_string_len(b, CONST_STR_LEN("\""));
780             /*semicolon = 1;*/
781         }
782     }
783 
784     /* legacy X-* headers, including X-Forwarded-For */
785 
786     b = (NULL != efor) ? efor : con->dst_addr_buf;
787     http_header_request_set(r, HTTP_HEADER_X_FORWARDED_FOR,
788                             CONST_STR_LEN("X-Forwarded-For"),
789                             CONST_BUF_LEN(b));
790 
791     b = (NULL != ehost) ? ehost : r->http_host;
792     if (!buffer_string_is_empty(b)) {
793         http_header_request_set(r, HTTP_HEADER_OTHER,
794                                 CONST_STR_LEN("X-Host"),
795                                 CONST_BUF_LEN(b));
796         http_header_request_set(r, HTTP_HEADER_OTHER,
797                                 CONST_STR_LEN("X-Forwarded-Host"),
798                                 CONST_BUF_LEN(b));
799     }
800 
801     b = (NULL != eproto) ? eproto : &r->uri.scheme;
802     http_header_request_set(r, HTTP_HEADER_X_FORWARDED_PROTO,
803                             CONST_STR_LEN("X-Forwarded-Proto"),
804                             CONST_BUF_LEN(b));
805 }
806 
807 
808 static handler_t proxy_stdin_append(gw_handler_ctx *hctx) {
809     /*handler_ctx *hctx = (handler_ctx *)gwhctx;*/
810     chunkqueue * const req_cq = &hctx->r->reqbody_queue;
811     const off_t req_cqlen = chunkqueue_length(req_cq);
812     if (req_cqlen) {
813         /* XXX: future: use http_chunk_len_append() */
814         buffer * const tb = hctx->r->tmp_buf;
815         buffer_clear(tb);
816         buffer_append_uint_hex_lc(tb, (uintmax_t)req_cqlen);
817         buffer_append_string_len(tb, CONST_STR_LEN("\r\n"));
818 
819         const off_t len = (off_t)buffer_string_length(tb)
820                         + 2 /*(+2 end chunk "\r\n")*/
821                         + req_cqlen;
822         if (-1 != hctx->wb_reqlen)
823             hctx->wb_reqlen += (hctx->wb_reqlen >= 0) ? len : -len;
824 
825         (chunkqueue_is_empty(&hctx->wb) || hctx->wb.first->type == MEM_CHUNK)
826                                           /* else FILE_CHUNK for temp file */
827           ? chunkqueue_append_mem(&hctx->wb, CONST_BUF_LEN(tb))
828           : chunkqueue_append_mem_min(&hctx->wb, CONST_BUF_LEN(tb));
829         chunkqueue_steal(&hctx->wb, req_cq, req_cqlen);
830 
831         chunkqueue_append_mem_min(&hctx->wb, CONST_STR_LEN("\r\n"));
832     }
833 
834     if (hctx->wb.bytes_in == hctx->wb_reqlen) {/*hctx->r->reqbody_length >= 0*/
835         /* terminate STDIN */
836         chunkqueue_append_mem(&hctx->wb, CONST_STR_LEN("0\r\n\r\n"));
837         hctx->wb_reqlen += (int)sizeof("0\r\n\r\n");
838     }
839 
840     return HANDLER_GO_ON;
841 }
842 
843 
844 static handler_t proxy_create_env(gw_handler_ctx *gwhctx) {
845 	handler_ctx *hctx = (handler_ctx *)gwhctx;
846 	request_st * const r = hctx->gw.r;
847 	const int remap_headers = (NULL != hctx->conf.header.urlpaths
848 				   || NULL != hctx->conf.header.hosts_request);
849 	size_t rsz = (size_t)(r->read_queue.bytes_out - hctx->gw.wb.bytes_in);
850 	if (rsz >= 65536) rsz = r->rqst_header_len;
851 	buffer * const b = chunkqueue_prepend_buffer_open_sz(&hctx->gw.wb, rsz);
852 
853 	/* build header */
854 
855 	/* request line */
856 	http_method_append(b, r->http_method);
857 	buffer_append_str2(b, CONST_STR_LEN(" "), CONST_BUF_LEN(&r->target));
858 	if (remap_headers)
859 		http_header_remap_uri(b, buffer_string_length(b) - buffer_string_length(&r->target), &hctx->conf.header, 1);
860 
861 	if (!hctx->conf.header.force_http10)
862 		buffer_append_string_len(b, CONST_STR_LEN(" HTTP/1.1"));
863 	else
864 		buffer_append_string_len(b, CONST_STR_LEN(" HTTP/1.0"));
865 
866 	if (hctx->conf.replace_http_host && !buffer_string_is_empty(hctx->gw.host->id)) {
867 		if (hctx->gw.conf.debug > 1) {
868 			log_error(r->conf.errh, __FILE__, __LINE__,
869 			  "proxy - using \"%s\" as HTTP Host", hctx->gw.host->id->ptr);
870 		}
871 		buffer_append_str2(b, CONST_STR_LEN("\r\nHost: "),
872                                       CONST_BUF_LEN(hctx->gw.host->id));
873 	} else if (!buffer_string_is_empty(r->http_host)) {
874 		buffer_append_str2(b, CONST_STR_LEN("\r\nHost: "),
875                                       CONST_BUF_LEN(r->http_host));
876 		if (remap_headers) {
877 			size_t alen = buffer_string_length(r->http_host);
878 			http_header_remap_host(b, buffer_string_length(b) - alen, &hctx->conf.header, 1, alen);
879 		}
880 	}
881 
882 	/* "Forwarded" and legacy X- headers */
883 	proxy_set_Forwarded(r->con, r, hctx->conf.forwarded);
884 
885 	if (r->reqbody_length > 0
886 	    || (0 == r->reqbody_length
887 		&& !http_method_get_or_head(r->http_method))) {
888 		/* set Content-Length if client sent Transfer-Encoding: chunked
889 		 * and not streaming to backend (request body has been fully received) */
890 		const buffer *vb = http_header_request_get(r, HTTP_HEADER_CONTENT_LENGTH, CONST_STR_LEN("Content-Length"));
891 		if (NULL == vb) {
892 			buffer_append_int(
893 			  http_header_request_set_ptr(r, HTTP_HEADER_CONTENT_LENGTH,
894 			                              CONST_STR_LEN("Content-Length")),
895 			  r->reqbody_length);
896 		}
897 	}
898 	else if (!hctx->conf.header.force_http10
899 	         && -1 == r->reqbody_length
900 	         && (r->conf.stream_request_body
901 	             & (FDEVENT_STREAM_REQUEST | FDEVENT_STREAM_REQUEST_BUFMIN))) {
902 		hctx->gw.stdin_append = proxy_stdin_append; /* stream chunked body */
903 		buffer_append_string_len(b, CONST_STR_LEN("\r\nTransfer-Encoding: chunked"));
904 	}
905 
906 	/* request header */
907 	const buffer *connhdr = NULL;
908 	const buffer *te = NULL;
909 	const buffer *upgrade = NULL;
910 	for (size_t i = 0, used = r->rqst_headers.used; i < used; ++i) {
911 		const data_string * const ds = (data_string *)r->rqst_headers.data[i];
912 		switch (ds->ext) {
913 		default:
914 			break;
915 		case HTTP_HEADER_TE:
916 			if (hctx->conf.header.force_http10 || r->http_version == HTTP_VERSION_1_0) continue;
917 			/* ignore if not exactly "trailers" */
918 			if (!buffer_eq_icase_slen(&ds->value, CONST_STR_LEN("trailers"))) continue;
919 			te = &ds->value;
920 			break;
921 		case HTTP_HEADER_HOST:
922 			continue; /*(handled further above)*/
923 		case HTTP_HEADER_UPGRADE:
924 			if (hctx->conf.header.force_http10 || r->http_version == HTTP_VERSION_1_0) continue;
925 			if (!hctx->conf.header.upgrade) continue;
926 			upgrade = &ds->value;
927 			break;
928 		case HTTP_HEADER_CONNECTION:
929 			connhdr = &ds->value;
930 			continue;
931 		case HTTP_HEADER_SET_COOKIE:
932 			continue; /*(response header only; avoid accidental reflection)*/
933 		case HTTP_HEADER_OTHER:
934 			if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Proxy-Connection"))) continue;
935 			/* Do not emit HTTP_PROXY in environment.
936 			 * Some executables use HTTP_PROXY to configure
937 			 * outgoing proxy.  See also https://httpoxy.org/ */
938 			if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Proxy"))) continue;
939 			break;
940 		case HTTP_HEADER_EXPECT:
941 			/* Do not forward Expect: 100-continue
942 			 * since we do not handle "HTTP/1.1 100 Continue" response */
943 			continue;
944 		}
945 
946 		const uint32_t klen = buffer_string_length(&ds->key);
947 		const uint32_t vlen = buffer_string_length(&ds->value);
948 		if (0 == klen || 0 == vlen) continue;
949 		char * restrict s = buffer_extend(b, klen+vlen+4);
950 		s[0] = '\r';
951 		s[1] = '\n';
952 		memcpy(s+2, ds->key.ptr, klen);
953 		s += 2+klen;
954 		s[0] = ':';
955 		s[1] = ' ';
956 		memcpy(s+2, ds->value.ptr, vlen);
957 
958 		if (!remap_headers) continue;
959 
960 		/* check for hdrs for which to remap URIs in-place after append to b */
961 
962 		switch (klen) {
963 		default:
964 			continue;
965 	      #if 0 /* "URI" is HTTP response header (non-standard; historical in Apache) */
966 		case 3:
967 			if (ds->ext == HTTP_HEADER_OTHER && buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("URI"))) break;
968 			continue;
969 	      #endif
970 	      #if 0 /* "Location" is HTTP response header */
971 		case 8:
972 			if (ds->ext == HTTP_HEADER_LOCATION) break;
973 			continue;
974 	      #endif
975 		case 11: /* "Destination" is WebDAV request header */
976 			if (ds->ext == HTTP_HEADER_OTHER && buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Destination"))) break;
977 			continue;
978 		case 16: /* "Content-Location" may be HTTP request or response header */
979 			if (ds->ext == HTTP_HEADER_CONTENT_LOCATION) break;
980 			continue;
981 		}
982 
983 		http_header_remap_uri(b, buffer_string_length(b) - vlen, &hctx->conf.header, 1);
984 	}
985 
986 	if (connhdr && !hctx->conf.header.force_http10 && r->http_version >= HTTP_VERSION_1_1
987 	    && !buffer_eq_icase_slen(connhdr, CONST_STR_LEN("close"))) {
988 		/* mod_proxy always sends Connection: close to backend */
989 		buffer_append_string_len(b, CONST_STR_LEN("\r\nConnection: close"));
990 		/* (future: might be pedantic and also check Connection header for each
991 		 * token using http_header_str_contains_token() */
992 		if (!buffer_string_is_empty(te))
993 			buffer_append_string_len(b, CONST_STR_LEN(", te"));
994 		if (!buffer_string_is_empty(upgrade))
995 			buffer_append_string_len(b, CONST_STR_LEN(", upgrade"));
996 		buffer_append_string_len(b, CONST_STR_LEN("\r\n\r\n"));
997 	}
998 	else    /* mod_proxy always sends Connection: close to backend */
999 		buffer_append_string_len(b, CONST_STR_LEN("\r\nConnection: close\r\n\r\n"));
1000 
1001 	hctx->gw.wb_reqlen = buffer_string_length(b);
1002 	chunkqueue_prepend_buffer_commit(&hctx->gw.wb);
1003 
1004 	if (r->reqbody_length) {
1005 		if (r->reqbody_length > 0)
1006 			hctx->gw.wb_reqlen += r->reqbody_length; /* total req size */
1007 		else /* as-yet-unknown total request size (Transfer-Encoding: chunked)*/
1008 			hctx->gw.wb_reqlen = -hctx->gw.wb_reqlen;
1009 		if (hctx->gw.stdin_append == proxy_stdin_append)
1010 			proxy_stdin_append(&hctx->gw);
1011 		else
1012 			chunkqueue_append_chunkqueue(&hctx->gw.wb, &r->reqbody_queue);
1013 	}
1014 
1015 	status_counter_inc(CONST_STR_LEN("proxy.requests"));
1016 	return HANDLER_GO_ON;
1017 }
1018 
1019 
1020 static handler_t proxy_create_env_connect(gw_handler_ctx *gwhctx) {
1021 	handler_ctx *hctx = (handler_ctx *)gwhctx;
1022 	request_st * const r = hctx->gw.r;
1023 	r->http_status = 200; /* OK */
1024 	r->resp_body_started = 1;
1025 	gw_set_transparent(&hctx->gw);
1026 	http_response_upgrade_read_body_unknown(r);
1027 
1028 	status_counter_inc(CONST_STR_LEN("proxy.requests"));
1029 	return HANDLER_GO_ON;
1030 }
1031 
1032 
1033 static handler_t proxy_response_headers(request_st * const r, struct http_response_opts_t *opts) {
1034     /* response headers just completed */
1035     handler_ctx *hctx = (handler_ctx *)opts->pdata;
1036 
1037     if (light_btst(r->resp_htags, HTTP_HEADER_UPGRADE)) {
1038         if (hctx->conf.header.upgrade && r->http_status == 101) {
1039             /* 101 Switching Protocols; transition to transparent proxy */
1040             gw_set_transparent(&hctx->gw);
1041             http_response_upgrade_read_body_unknown(r);
1042         }
1043         else {
1044             light_bclr(r->resp_htags, HTTP_HEADER_UPGRADE);
1045           #if 0
1046             /* preserve prior questionable behavior; likely broken behavior
1047              * anyway if backend thinks connection is being upgraded but client
1048              * does not receive Connection: upgrade */
1049             http_header_response_unset(r, HTTP_HEADER_UPGRADE,
1050                                        CONST_STR_LEN("Upgrade"))
1051           #endif
1052         }
1053     }
1054 
1055     /* rewrite paths, if needed */
1056 
1057     if (NULL == hctx->conf.header.urlpaths
1058         && NULL == hctx->conf.header.hosts_response)
1059         return HANDLER_GO_ON;
1060 
1061     if (light_btst(r->resp_htags, HTTP_HEADER_LOCATION)) {
1062         buffer *vb = http_header_response_get(r, HTTP_HEADER_LOCATION, CONST_STR_LEN("Location"));
1063         if (vb) http_header_remap_uri(vb, 0, &hctx->conf.header, 0);
1064     }
1065     if (light_btst(r->resp_htags, HTTP_HEADER_CONTENT_LOCATION)) {
1066         buffer *vb = http_header_response_get(r, HTTP_HEADER_CONTENT_LOCATION, CONST_STR_LEN("Content-Location"));
1067         if (vb) http_header_remap_uri(vb, 0, &hctx->conf.header, 0);
1068     }
1069     if (light_btst(r->resp_htags, HTTP_HEADER_SET_COOKIE)) {
1070         buffer *vb = http_header_response_get(r, HTTP_HEADER_SET_COOKIE, CONST_STR_LEN("Set-Cookie"));
1071         if (vb) http_header_remap_setcookie(vb, 0, &hctx->conf.header);
1072     }
1073 
1074     return HANDLER_GO_ON;
1075 }
1076 
1077 static handler_t mod_proxy_check_extension(request_st * const r, void *p_d) {
1078 	plugin_data *p = p_d;
1079 	handler_t rc;
1080 
1081 	if (NULL != r->handler_module) return HANDLER_GO_ON;
1082 
1083 	mod_proxy_patch_config(r, p);
1084 	if (NULL == p->conf.gw.exts) return HANDLER_GO_ON;
1085 
1086 	rc = gw_check_extension(r, (gw_plugin_data *)p, 1, sizeof(handler_ctx));
1087 	if (HANDLER_GO_ON != rc) return rc;
1088 
1089 	if (r->handler_module == p->self) {
1090 		handler_ctx *hctx = r->plugin_ctx[p->id];
1091 		hctx->gw.create_env = proxy_create_env;
1092 		hctx->gw.response = chunk_buffer_acquire();
1093 		hctx->gw.opts.backend = BACKEND_PROXY;
1094 		hctx->gw.opts.pdata = hctx;
1095 		hctx->gw.opts.headers = proxy_response_headers;
1096 
1097 		hctx->conf = p->conf; /*(copies struct)*/
1098 		hctx->conf.header.http_host = r->http_host;
1099 		hctx->conf.header.upgrade  &= (r->http_version == HTTP_VERSION_1_1);
1100 		/* mod_proxy currently sends all backend requests as http.
1101 		 * https-remap is a flag since it might not be needed if backend
1102 		 * honors Forwarded or X-Forwarded-Proto headers, e.g. by using
1103 		 * lighttpd mod_extforward or similar functionality in backend*/
1104 		if (hctx->conf.header.https_remap) {
1105 			hctx->conf.header.https_remap =
1106 			  buffer_is_equal_string(&r->uri.scheme, CONST_STR_LEN("https"));
1107 		}
1108 
1109 		if (r->http_method == HTTP_METHOD_CONNECT) {
1110 			/*(note: not requiring HTTP/1.1 due to too many non-compliant
1111 			 * clients such as 'openssl s_client')*/
1112 			if (hctx->conf.header.connect_method) {
1113 				hctx->gw.create_env = proxy_create_env_connect;
1114 			}
1115 			else {
1116 				r->http_status = 405; /* Method Not Allowed */
1117 				r->handler_module = NULL;
1118 				return HANDLER_FINISHED;
1119 			}
1120 		}
1121 	}
1122 
1123 	return HANDLER_GO_ON;
1124 }
1125 
1126 
1127 int mod_proxy_plugin_init(plugin *p);
1128 int mod_proxy_plugin_init(plugin *p) {
1129 	p->version      = LIGHTTPD_VERSION_ID;
1130 	p->name         = "proxy";
1131 
1132 	p->init         = mod_proxy_init;
1133 	p->cleanup      = mod_proxy_free;
1134 	p->set_defaults = mod_proxy_set_defaults;
1135 	p->handle_request_reset    = gw_handle_request_reset;
1136 	p->handle_uri_clean        = mod_proxy_check_extension;
1137 	p->handle_subrequest       = gw_handle_subrequest;
1138 	p->handle_trigger          = gw_handle_trigger;
1139 	p->handle_waitpid          = gw_handle_waitpid_cb;
1140 
1141 	return 0;
1142 }
1143