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