xref: /lighttpd1.4/src/mod_proxy.c (revision f1e8a82f)
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_clen(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_clen(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_is_blank(&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_clen(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_clen(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_clen(&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_clen(&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_clen(&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_clen(&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_clen(&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_clen(&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_clen(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_clen(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 * const p = buffer_string_prepare_append(b, len*2 + 4);
606 
607     for (size_t i = 0; i < len; ++i) {
608         int c = s[i];
609         if (c == '"' || c == '\\' || c == 0x7F || (c < 0x20 && c != '\t'))
610             p[j++] = '\\';
611         p[j++] = c;
612     }
613 
614     buffer_commit(b, j);
615 }
616 
617 static void proxy_set_Forwarded(connection * const con, request_st * const r, const unsigned int flags) {
618     buffer *b = NULL, *efor = NULL, *eproto = NULL, *ehost = NULL;
619     int semicolon = 0;
620 
621     if (proxy_check_extforward) {
622         efor   =
623           http_header_env_get(r, CONST_STR_LEN("_L_EXTFORWARD_ACTUAL_FOR"));
624         eproto =
625           http_header_env_get(r, CONST_STR_LEN("_L_EXTFORWARD_ACTUAL_PROTO"));
626         ehost  =
627           http_header_env_get(r, CONST_STR_LEN("_L_EXTFORWARD_ACTUAL_HOST"));
628     }
629 
630     /* note: set "Forwarded" prior to updating X-Forwarded-For (below) */
631 
632     if (flags)
633         b = http_header_request_get(r, HTTP_HEADER_FORWARDED, CONST_STR_LEN("Forwarded"));
634 
635     if (flags && NULL == b) {
636         const buffer *xff =
637           http_header_request_get(r, HTTP_HEADER_X_FORWARDED_FOR, CONST_STR_LEN("X-Forwarded-For"));
638         b = http_header_request_set_ptr(r, HTTP_HEADER_FORWARDED,
639                                         CONST_STR_LEN("Forwarded"));
640         if (NULL != xff) {
641             /* use X-Forwarded-For contents to seed Forwarded */
642             char *s = xff->ptr;
643             size_t used = buffer_clen(xff);
644             for (size_t i=0, j, ipv6; i < used; ++i) {
645                 while (s[i] == ' ' || s[i] == '\t' || s[i] == ',') ++i;
646                 if (s[i] == '\0') break;
647                 j = i;
648                 do {
649                     ++i;
650                 } while (s[i]!=' ' && s[i]!='\t' && s[i]!=',' && s[i]!='\0');
651                 /* over-simplified test expecting only IPv4 or IPv6 addresses,
652                  * (not expecting :port, so treat existence of colon as IPv6,
653                  *  and not expecting unix paths, especially not containing ':')
654                  * quote all strings, backslash-escape since IPs not validated*/
655                 ipv6 = (NULL != memchr(s+j, ':', i-j)); /*(over-simplified) */
656                 ipv6
657                   ? buffer_append_string_len(b, CONST_STR_LEN("for=\"["))
658                   : buffer_append_string_len(b, CONST_STR_LEN("for=\""));
659                 buffer_append_string_backslash_escaped(b, s+j, i-j);
660                 ipv6
661                   ? buffer_append_string_len(b, CONST_STR_LEN("]\", "))
662                   : buffer_append_string_len(b, CONST_STR_LEN("\", "));
663             }
664         }
665     } else if (flags) { /*(NULL != b)*/
666         buffer_append_string_len(b, CONST_STR_LEN(", "));
667     }
668 
669     if (flags & PROXY_FORWARDED_FOR) {
670         int family = sock_addr_get_family(&con->dst_addr);
671         buffer_append_string_len(b, CONST_STR_LEN("for="));
672         if (NULL != efor) {
673             /* over-simplified test expecting only IPv4 or IPv6 addresses,
674              * (not expecting :port, so treat existence of colon as IPv6,
675              *  and not expecting unix paths, especially not containing ':')
676              * quote all strings and backslash-escape since IPs not validated
677              * (should be IP from original con->dst_addr_buf,
678              *  so trustable and without :port) */
679             int ipv6 = (NULL != strchr(efor->ptr, ':'));
680             ipv6
681               ? buffer_append_string_len(b, CONST_STR_LEN("\"["))
682               : buffer_append_string_len(b, CONST_STR_LEN("\""));
683             buffer_append_string_backslash_escaped(b, BUF_PTR_LEN(efor));
684             ipv6
685               ? buffer_append_string_len(b, CONST_STR_LEN("]\""))
686               : buffer_append_string_len(b, CONST_STR_LEN("\""));
687         } else if (family == AF_INET) {
688             /*(Note: if :port is added, then must be quoted-string:
689              * e.g. for="...:port")*/
690             buffer_append_string_buffer(b, &con->dst_addr_buf);
691         } else if (family == AF_INET6) {
692             buffer_append_str3(b, CONST_STR_LEN("\"["),
693                                   BUF_PTR_LEN(&con->dst_addr_buf),
694                                   CONST_STR_LEN("]\""));
695         } else {
696             buffer_append_string_len(b, CONST_STR_LEN("\""));
697             buffer_append_string_backslash_escaped(
698               b, BUF_PTR_LEN(&con->dst_addr_buf));
699             buffer_append_string_len(b, CONST_STR_LEN("\""));
700         }
701         semicolon = 1;
702     }
703 
704     if (flags & PROXY_FORWARDED_BY) {
705         int family = sock_addr_get_family(&con->srv_socket->addr);
706         /* Note: getsockname() and inet_ntop() are expensive operations.
707          * (recommendation: do not to enable by=... unless required)
708          * future: might use con->srv_socket->srv_token if addr is not
709          *   INADDR_ANY or in6addr_any, but must omit optional :port
710          *   from con->srv_socket->srv_token for consistency */
711 
712         if (semicolon) buffer_append_string_len(b, CONST_STR_LEN(";"));
713         buffer_append_string_len(b, CONST_STR_LEN("by=\""));
714       #ifdef HAVE_SYS_UN_H
715         /* special-case: might need to encode unix domain socket path */
716         if (family == AF_UNIX) {
717             buffer_append_string_backslash_escaped(
718               b, BUF_PTR_LEN(con->srv_socket->srv_token));
719         }
720         else
721       #endif
722         {
723             sock_addr addr;
724             socklen_t addrlen = sizeof(addr);
725             if (0 == getsockname(con->fd,(struct sockaddr *)&addr, &addrlen)) {
726                 sock_addr_stringify_append_buffer(b, &addr);
727             }
728         }
729         buffer_append_string_len(b, CONST_STR_LEN("\""));
730         semicolon = 1;
731     }
732 
733     if (flags & PROXY_FORWARDED_PROTO) {
734         /* expecting "http" or "https"
735          * (not checking if quoted-string and encoding needed) */
736         if (semicolon) buffer_append_string_len(b, CONST_STR_LEN(";"));
737         if (NULL != eproto) {
738             buffer_append_str2(b, CONST_STR_LEN("proto="), BUF_PTR_LEN(eproto));
739         } else if (con->srv_socket->is_ssl) {
740             buffer_append_string_len(b, CONST_STR_LEN("proto=https"));
741         } else {
742             buffer_append_string_len(b, CONST_STR_LEN("proto=http"));
743         }
744         semicolon = 1;
745     }
746 
747     if (flags & PROXY_FORWARDED_HOST) {
748         if (NULL != ehost) {
749             if (semicolon)
750                 buffer_append_string_len(b, CONST_STR_LEN(";"));
751             buffer_append_string_len(b, CONST_STR_LEN("host=\""));
752             buffer_append_string_backslash_escaped(
753               b, BUF_PTR_LEN(ehost));
754             buffer_append_string_len(b, CONST_STR_LEN("\""));
755             semicolon = 1;
756         } else if (r->http_host && !buffer_is_blank(r->http_host)) {
757             if (semicolon)
758                 buffer_append_string_len(b, CONST_STR_LEN(";"));
759             buffer_append_string_len(b, CONST_STR_LEN("host=\""));
760             buffer_append_string_backslash_escaped(
761               b, BUF_PTR_LEN(r->http_host));
762             buffer_append_string_len(b, CONST_STR_LEN("\""));
763             semicolon = 1;
764         }
765     }
766 
767     if (flags & PROXY_FORWARDED_REMOTE_USER) {
768         const buffer *remote_user =
769           http_header_env_get(r, CONST_STR_LEN("REMOTE_USER"));
770         if (NULL != remote_user) {
771             if (semicolon)
772                 buffer_append_string_len(b, CONST_STR_LEN(";"));
773             buffer_append_string_len(b, CONST_STR_LEN("remote_user=\""));
774             buffer_append_string_backslash_escaped(
775               b, BUF_PTR_LEN(remote_user));
776             buffer_append_string_len(b, CONST_STR_LEN("\""));
777             /*semicolon = 1;*/
778         }
779     }
780 
781     /* legacy X-* headers, including X-Forwarded-For */
782 
783     b = (NULL != efor) ? efor : &con->dst_addr_buf;
784     http_header_request_set(r, HTTP_HEADER_X_FORWARDED_FOR,
785                             CONST_STR_LEN("X-Forwarded-For"),
786                             BUF_PTR_LEN(b));
787 
788     b = (NULL != ehost) ? ehost : r->http_host;
789     if (b && !buffer_is_blank(b)) {
790         http_header_request_set(r, HTTP_HEADER_OTHER,
791                                 CONST_STR_LEN("X-Host"),
792                                 BUF_PTR_LEN(b));
793         http_header_request_set(r, HTTP_HEADER_OTHER,
794                                 CONST_STR_LEN("X-Forwarded-Host"),
795                                 BUF_PTR_LEN(b));
796     }
797 
798     b = (NULL != eproto) ? eproto : &r->uri.scheme;
799     http_header_request_set(r, HTTP_HEADER_X_FORWARDED_PROTO,
800                             CONST_STR_LEN("X-Forwarded-Proto"),
801                             BUF_PTR_LEN(b));
802 }
803 
804 
805 static handler_t proxy_stdin_append(gw_handler_ctx *hctx) {
806     /*handler_ctx *hctx = (handler_ctx *)gwhctx;*/
807     chunkqueue * const req_cq = &hctx->r->reqbody_queue;
808     const off_t req_cqlen = chunkqueue_length(req_cq);
809     if (req_cqlen) {
810         /* XXX: future: use http_chunk_len_append() */
811         buffer * const tb = hctx->r->tmp_buf;
812         buffer_clear(tb);
813         buffer_append_uint_hex_lc(tb, (uintmax_t)req_cqlen);
814         buffer_append_string_len(tb, CONST_STR_LEN("\r\n"));
815 
816         const off_t len = (off_t)buffer_clen(tb)
817                         + 2 /*(+2 end chunk "\r\n")*/
818                         + req_cqlen;
819         if (-1 != hctx->wb_reqlen)
820             hctx->wb_reqlen += (hctx->wb_reqlen >= 0) ? len : -len;
821 
822         (chunkqueue_is_empty(&hctx->wb) || hctx->wb.first->type == MEM_CHUNK)
823                                           /* else FILE_CHUNK for temp file */
824           ? chunkqueue_append_mem(&hctx->wb, BUF_PTR_LEN(tb))
825           : chunkqueue_append_mem_min(&hctx->wb, BUF_PTR_LEN(tb));
826         chunkqueue_steal(&hctx->wb, req_cq, req_cqlen);
827 
828         chunkqueue_append_mem_min(&hctx->wb, CONST_STR_LEN("\r\n"));
829     }
830 
831     if (hctx->wb.bytes_in == hctx->wb_reqlen) {/*hctx->r->reqbody_length >= 0*/
832         /* terminate STDIN */
833         chunkqueue_append_mem(&hctx->wb, CONST_STR_LEN("0\r\n\r\n"));
834         hctx->wb_reqlen += (int)sizeof("0\r\n\r\n");
835     }
836 
837     return HANDLER_GO_ON;
838 }
839 
840 
841 static handler_t proxy_create_env(gw_handler_ctx *gwhctx) {
842 	handler_ctx *hctx = (handler_ctx *)gwhctx;
843 	request_st * const r = hctx->gw.r;
844 	const int remap_headers = (NULL != hctx->conf.header.urlpaths
845 				   || NULL != hctx->conf.header.hosts_request);
846 	size_t rsz = (size_t)(r->read_queue.bytes_out - hctx->gw.wb.bytes_in);
847 	if (rsz >= 65536) rsz = r->rqst_header_len;
848 	buffer * const b = chunkqueue_prepend_buffer_open_sz(&hctx->gw.wb, rsz);
849 
850 	/* build header */
851 
852 	/* request line */
853 	http_method_append(b, r->http_method);
854 	buffer_append_str2(b, CONST_STR_LEN(" "), BUF_PTR_LEN(&r->target));
855 	if (remap_headers)
856 		http_header_remap_uri(b, buffer_clen(b) - buffer_clen(&r->target),
857 		                      &hctx->conf.header, 1);
858 
859 	buffer_append_string_len(b, !hctx->conf.header.force_http10
860 	                            ? " HTTP/1.1" : " HTTP/1.0",
861 	                            sizeof(" HTTP/1.1")-1);
862 
863 	if (hctx->conf.replace_http_host && !buffer_is_blank(hctx->gw.host->id)) {
864 		if (hctx->gw.conf.debug > 1) {
865 			log_error(r->conf.errh, __FILE__, __LINE__,
866 			  "proxy - using \"%s\" as HTTP Host", hctx->gw.host->id->ptr);
867 		}
868 		buffer_append_str2(b, CONST_STR_LEN("\r\nHost: "),
869 		                      BUF_PTR_LEN(hctx->gw.host->id));
870 	} else if (r->http_host && !buffer_is_unset(r->http_host)) {
871 		buffer_append_str2(b, CONST_STR_LEN("\r\nHost: "),
872 		                      BUF_PTR_LEN(r->http_host));
873 		if (remap_headers) {
874 			size_t alen = buffer_clen(r->http_host);
875 			http_header_remap_host(b, buffer_clen(b) - alen, &hctx->conf.header, 1, alen);
876 		}
877 	} else {
878 		/* no Host header available; must send HTTP/1.0 request */
879 		b->ptr[b->used-2] = '0'; /*(overwrite end of request line)*/
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 			/*if (!buffer_is_blank(&ds->value)) te = &ds->value;*/
920 			te = &ds->value; /*("trailers")*/
921 			break;
922 		case HTTP_HEADER_HOST:
923 			continue; /*(handled further above)*/
924 		case HTTP_HEADER_UPGRADE:
925 			if (hctx->conf.header.force_http10 || r->http_version == HTTP_VERSION_1_0) continue;
926 			if (!hctx->conf.header.upgrade) continue;
927 			if (!buffer_is_blank(&ds->value)) upgrade = &ds->value;
928 			break;
929 		case HTTP_HEADER_CONNECTION:
930 			connhdr = &ds->value;
931 			continue;
932 		case HTTP_HEADER_SET_COOKIE:
933 			continue; /*(response header only; avoid accidental reflection)*/
934 		case HTTP_HEADER_OTHER:
935 			if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Proxy-Connection"))) continue;
936 			/* Do not emit HTTP_PROXY in environment.
937 			 * Some executables use HTTP_PROXY to configure
938 			 * outgoing proxy.  See also https://httpoxy.org/ */
939 			if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Proxy"))) continue;
940 			break;
941 		case HTTP_HEADER_EXPECT:
942 			/* Do not forward Expect: 100-continue
943 			 * since we do not handle "HTTP/1.1 100 Continue" response */
944 			continue;
945 		}
946 
947 		const uint32_t klen = buffer_clen(&ds->key);
948 		const uint32_t vlen = buffer_clen(&ds->value);
949 		if (0 == klen || 0 == vlen) continue;
950 		char * restrict s = buffer_extend(b, klen+vlen+4);
951 		s[0] = '\r';
952 		s[1] = '\n';
953 		memcpy(s+2, ds->key.ptr, klen);
954 		s += 2+klen;
955 		s[0] = ':';
956 		s[1] = ' ';
957 		memcpy(s+2, ds->value.ptr, vlen);
958 
959 		if (!remap_headers) continue;
960 
961 		/* check for hdrs for which to remap URIs in-place after append to b */
962 
963 		switch (klen) {
964 		default:
965 			continue;
966 	      #if 0 /* "URI" is HTTP response header (non-standard; historical in Apache) */
967 		case 3:
968 			if (ds->ext == HTTP_HEADER_OTHER && buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("URI"))) break;
969 			continue;
970 	      #endif
971 	      #if 0 /* "Location" is HTTP response header */
972 		case 8:
973 			if (ds->ext == HTTP_HEADER_LOCATION) break;
974 			continue;
975 	      #endif
976 		case 11: /* "Destination" is WebDAV request header */
977 			if (ds->ext == HTTP_HEADER_OTHER && buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Destination"))) break;
978 			continue;
979 		case 16: /* "Content-Location" may be HTTP request or response header */
980 			if (ds->ext == HTTP_HEADER_CONTENT_LOCATION) break;
981 			continue;
982 		}
983 
984 		http_header_remap_uri(b, buffer_clen(b) - vlen, &hctx->conf.header, 1);
985 	}
986 
987 	if (connhdr && !hctx->conf.header.force_http10 && r->http_version >= HTTP_VERSION_1_1
988 	    && !buffer_eq_icase_slen(connhdr, CONST_STR_LEN("close"))) {
989 		/* mod_proxy always sends Connection: close to backend */
990 		buffer_append_string_len(b, CONST_STR_LEN("\r\nConnection: close"));
991 		/* (future: might be pedantic and also check Connection header for each
992 		 * token using http_header_str_contains_token() */
993 		if (te)
994 			buffer_append_string_len(b, CONST_STR_LEN(", te"));
995 		if (upgrade)
996 			buffer_append_string_len(b, CONST_STR_LEN(", upgrade"));
997 		buffer_append_string_len(b, CONST_STR_LEN("\r\n\r\n"));
998 	}
999 	else    /* mod_proxy always sends Connection: close to backend */
1000 		buffer_append_string_len(b, CONST_STR_LEN("\r\nConnection: close\r\n\r\n"));
1001 
1002 	hctx->gw.wb_reqlen = buffer_clen(b);
1003 	chunkqueue_prepend_buffer_commit(&hctx->gw.wb);
1004 
1005 	if (r->reqbody_length) {
1006 		if (r->reqbody_length > 0)
1007 			hctx->gw.wb_reqlen += r->reqbody_length; /* total req size */
1008 		else /* as-yet-unknown total request size (Transfer-Encoding: chunked)*/
1009 			hctx->gw.wb_reqlen = -hctx->gw.wb_reqlen;
1010 		if (hctx->gw.stdin_append == proxy_stdin_append)
1011 			proxy_stdin_append(&hctx->gw);
1012 		else
1013 			chunkqueue_append_chunkqueue(&hctx->gw.wb, &r->reqbody_queue);
1014 	}
1015 
1016 	status_counter_inc(CONST_STR_LEN("proxy.requests"));
1017 	return HANDLER_GO_ON;
1018 }
1019 
1020 
1021 static handler_t proxy_create_env_connect(gw_handler_ctx *gwhctx) {
1022 	handler_ctx *hctx = (handler_ctx *)gwhctx;
1023 	request_st * const r = hctx->gw.r;
1024 	r->http_status = 200; /* OK */
1025 	r->resp_body_started = 1;
1026 	gw_set_transparent(&hctx->gw);
1027 	http_response_upgrade_read_body_unknown(r);
1028 
1029 	status_counter_inc(CONST_STR_LEN("proxy.requests"));
1030 	return HANDLER_GO_ON;
1031 }
1032 
1033 
1034 static handler_t proxy_response_headers(request_st * const r, struct http_response_opts_t *opts) {
1035     /* response headers just completed */
1036     handler_ctx *hctx = (handler_ctx *)opts->pdata;
1037 
1038     if (light_btst(r->resp_htags, HTTP_HEADER_UPGRADE)) {
1039         if (hctx->conf.header.upgrade && r->http_status == 101) {
1040             /* 101 Switching Protocols; transition to transparent proxy */
1041             gw_set_transparent(&hctx->gw);
1042             http_response_upgrade_read_body_unknown(r);
1043         }
1044         else {
1045             light_bclr(r->resp_htags, HTTP_HEADER_UPGRADE);
1046           #if 0
1047             /* preserve prior questionable behavior; likely broken behavior
1048              * anyway if backend thinks connection is being upgraded but client
1049              * does not receive Connection: upgrade */
1050             http_header_response_unset(r, HTTP_HEADER_UPGRADE,
1051                                        CONST_STR_LEN("Upgrade"))
1052           #endif
1053         }
1054     }
1055 
1056     /* rewrite paths, if needed */
1057 
1058     if (NULL == hctx->conf.header.urlpaths
1059         && NULL == hctx->conf.header.hosts_response)
1060         return HANDLER_GO_ON;
1061 
1062     if (light_btst(r->resp_htags, HTTP_HEADER_LOCATION)) {
1063         buffer *vb = http_header_response_get(r, HTTP_HEADER_LOCATION, CONST_STR_LEN("Location"));
1064         if (vb) http_header_remap_uri(vb, 0, &hctx->conf.header, 0);
1065     }
1066     if (light_btst(r->resp_htags, HTTP_HEADER_CONTENT_LOCATION)) {
1067         buffer *vb = http_header_response_get(r, HTTP_HEADER_CONTENT_LOCATION, CONST_STR_LEN("Content-Location"));
1068         if (vb) http_header_remap_uri(vb, 0, &hctx->conf.header, 0);
1069     }
1070     if (light_btst(r->resp_htags, HTTP_HEADER_SET_COOKIE)) {
1071         buffer *vb = http_header_response_get(r, HTTP_HEADER_SET_COOKIE, CONST_STR_LEN("Set-Cookie"));
1072         if (vb) http_header_remap_setcookie(vb, 0, &hctx->conf.header);
1073     }
1074 
1075     return HANDLER_GO_ON;
1076 }
1077 
1078 static handler_t mod_proxy_check_extension(request_st * const r, void *p_d) {
1079 	plugin_data *p = p_d;
1080 	handler_t rc;
1081 
1082 	if (NULL != r->handler_module) return HANDLER_GO_ON;
1083 
1084 	mod_proxy_patch_config(r, p);
1085 	if (NULL == p->conf.gw.exts) return HANDLER_GO_ON;
1086 
1087 	rc = gw_check_extension(r, (gw_plugin_data *)p, 1, sizeof(handler_ctx));
1088 	if (HANDLER_GO_ON != rc) return rc;
1089 
1090 	if (r->handler_module == p->self) {
1091 		handler_ctx *hctx = r->plugin_ctx[p->id];
1092 		hctx->gw.create_env = proxy_create_env;
1093 		hctx->gw.response = chunk_buffer_acquire();
1094 		hctx->gw.opts.backend = BACKEND_PROXY;
1095 		hctx->gw.opts.pdata = hctx;
1096 		hctx->gw.opts.headers = proxy_response_headers;
1097 
1098 		hctx->conf = p->conf; /*(copies struct)*/
1099 		hctx->conf.header.http_host = r->http_host;
1100 		hctx->conf.header.upgrade  &= (r->http_version == HTTP_VERSION_1_1);
1101 		/* mod_proxy currently sends all backend requests as http.
1102 		 * https-remap is a flag since it might not be needed if backend
1103 		 * honors Forwarded or X-Forwarded-Proto headers, e.g. by using
1104 		 * lighttpd mod_extforward or similar functionality in backend*/
1105 		if (hctx->conf.header.https_remap) {
1106 			hctx->conf.header.https_remap =
1107 			  buffer_is_equal_string(&r->uri.scheme, CONST_STR_LEN("https"));
1108 		}
1109 
1110 		if (r->http_method == HTTP_METHOD_CONNECT) {
1111 			/*(note: not requiring HTTP/1.1 due to too many non-compliant
1112 			 * clients such as 'openssl s_client')*/
1113 			if (hctx->conf.header.connect_method) {
1114 				hctx->gw.create_env = proxy_create_env_connect;
1115 			}
1116 			else {
1117 				r->http_status = 405; /* Method Not Allowed */
1118 				r->handler_module = NULL;
1119 				return HANDLER_FINISHED;
1120 			}
1121 		}
1122 	}
1123 
1124 	return HANDLER_GO_ON;
1125 }
1126 
1127 
1128 int mod_proxy_plugin_init(plugin *p);
1129 int mod_proxy_plugin_init(plugin *p) {
1130 	p->version      = LIGHTTPD_VERSION_ID;
1131 	p->name         = "proxy";
1132 
1133 	p->init         = mod_proxy_init;
1134 	p->cleanup      = mod_proxy_free;
1135 	p->set_defaults = mod_proxy_set_defaults;
1136 	p->handle_request_reset    = gw_handle_request_reset;
1137 	p->handle_uri_clean        = mod_proxy_check_extension;
1138 	p->handle_subrequest       = gw_handle_subrequest;
1139 	p->handle_trigger          = gw_handle_trigger;
1140 	p->handle_waitpid          = gw_handle_waitpid_cb;
1141 
1142 	return 0;
1143 }
1144