1 #include "first.h" 2 3 #include <sys/types.h> 4 #include <stdlib.h> 5 #include <string.h> 6 7 #include "gw_backend.h" 8 typedef gw_plugin_config plugin_config; 9 typedef gw_plugin_data plugin_data; 10 typedef gw_handler_ctx handler_ctx; 11 12 #include "base.h" 13 #include "buffer.h" 14 #include "fdevent.h" 15 #include "http_chunk.h" 16 #include "log.h" 17 #include "status_counter.h" 18 19 #ifdef HAVE_FASTCGI_FASTCGI_H 20 # include <fastcgi/fastcgi.h> 21 #else 22 # ifdef HAVE_FASTCGI_H 23 # include <fastcgi.h> 24 # else 25 # include "fastcgi.h" 26 # endif 27 #endif /* HAVE_FASTCGI_FASTCGI_H */ 28 29 #if GW_RESPONDER != FCGI_RESPONDER 30 #error "mismatched defines: (GW_RESPONDER != FCGI_RESPONDER)" 31 #endif 32 #if GW_AUTHORIZER != FCGI_AUTHORIZER 33 #error "mismatched defines: (GW_AUTHORIZER != FCGI_AUTHORIZER)" 34 #endif 35 #if GW_FILTER != FCGI_FILTER 36 #error "mismatched defines: (GW_FILTER != FCGI_FILTER)" 37 #endif 38 39 static void mod_fastcgi_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) { 40 switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */ 41 case 0: /* fastcgi.server */ 42 if (cpv->vtype == T_CONFIG_LOCAL) { 43 gw_plugin_config * const gw = cpv->v.v; 44 pconf->exts = gw->exts; 45 pconf->exts_auth = gw->exts_auth; 46 pconf->exts_resp = gw->exts_resp; 47 } 48 break; 49 case 1: /* fastcgi.balance */ 50 /*if (cpv->vtype == T_CONFIG_LOCAL)*//*always true here for this param*/ 51 pconf->balance = (int)cpv->v.u; 52 break; 53 case 2: /* fastcgi.debug */ 54 pconf->debug = (int)cpv->v.u; 55 break; 56 case 3: /* fastcgi.map-extensions */ 57 pconf->ext_mapping = cpv->v.a; 58 break; 59 default:/* should not happen */ 60 return; 61 } 62 } 63 64 static void mod_fastcgi_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) { 65 do { 66 mod_fastcgi_merge_config_cpv(pconf, cpv); 67 } while ((++cpv)->k_id != -1); 68 } 69 70 static void mod_fastcgi_patch_config(request_st * const r, plugin_data * const p) { 71 memcpy(&p->conf, &p->defaults, sizeof(plugin_config)); 72 for (int i = 1, used = p->nconfig; i < used; ++i) { 73 if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id)) 74 mod_fastcgi_merge_config(&p->conf,p->cvlist + p->cvlist[i].v.u2[0]); 75 } 76 } 77 78 SETDEFAULTS_FUNC(mod_fastcgi_set_defaults) { 79 static const config_plugin_keys_t cpk[] = { 80 { CONST_STR_LEN("fastcgi.server"), 81 T_CONFIG_ARRAY_KVARRAY, 82 T_CONFIG_SCOPE_CONNECTION } 83 ,{ CONST_STR_LEN("fastcgi.balance"), 84 T_CONFIG_STRING, 85 T_CONFIG_SCOPE_CONNECTION } 86 ,{ CONST_STR_LEN("fastcgi.debug"), 87 T_CONFIG_INT, 88 T_CONFIG_SCOPE_CONNECTION } 89 ,{ CONST_STR_LEN("fastcgi.map-extensions"), 90 T_CONFIG_ARRAY_KVSTRING, 91 T_CONFIG_SCOPE_CONNECTION } 92 ,{ NULL, 0, 93 T_CONFIG_UNSET, 94 T_CONFIG_SCOPE_UNSET } 95 }; 96 97 plugin_data * const p = p_d; 98 if (!config_plugin_values_init(srv, p, cpk, "mod_fastcgi")) 99 return HANDLER_ERROR; 100 101 /* process and validate config directives 102 * (init i to 0 if global context; to 1 to skip empty global context) */ 103 for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) { 104 config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0]; 105 for (; -1 != cpv->k_id; ++cpv) { 106 switch (cpv->k_id) { 107 case 0:{/* fastcgi.server */ 108 gw_plugin_config *gw = calloc(1, sizeof(gw_plugin_config)); 109 force_assert(gw); 110 if (!gw_set_defaults_backend(srv, p, cpv->v.a, gw, 0, 111 cpk[cpv->k_id].k)) { 112 gw_plugin_config_free(gw); 113 return HANDLER_ERROR; 114 } 115 cpv->v.v = gw; 116 cpv->vtype = T_CONFIG_LOCAL; 117 break; 118 } 119 case 1: /* fastcgi.balance */ 120 cpv->v.u = (unsigned int)gw_get_defaults_balance(srv, cpv->v.b); 121 break; 122 case 2: /* fastcgi.debug */ 123 case 3: /* fastcgi.map-extensions */ 124 break; 125 default:/* should not happen */ 126 break; 127 } 128 } 129 } 130 131 /* default is 0 */ 132 /*p->defaults.balance = (unsigned int)gw_get_defaults_balance(srv, NULL);*/ 133 134 /* initialize p->defaults from global config context */ 135 if (p->nconfig > 0 && p->cvlist->v.u2[1]) { 136 const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0]; 137 if (-1 != cpv->k_id) 138 mod_fastcgi_merge_config(&p->defaults, cpv); 139 } 140 141 return HANDLER_GO_ON; 142 } 143 144 145 static int fcgi_env_add(void *venv, const char *key, size_t key_len, const char *val, size_t val_len) { 146 buffer *env = venv; 147 size_t len; 148 char len_enc[8]; 149 size_t len_enc_len = 0; 150 char *dst; 151 152 if (!key || !val) return -1; 153 154 len = key_len + val_len; 155 156 len += key_len > 127 ? 4 : 1; 157 len += val_len > 127 ? 4 : 1; 158 159 if (buffer_string_length(env) + len >= FCGI_MAX_LENGTH + sizeof(FCGI_BeginRequestRecord) + sizeof(FCGI_Header)) { 160 /** 161 * we can't append more headers, ignore it 162 */ 163 return -1; 164 } 165 166 /** 167 * field length can be 31bit max 168 * 169 * HINT: this can't happen as FCGI_MAX_LENGTH is only 16bit 170 */ 171 force_assert(key_len < 0x7fffffffu); 172 force_assert(val_len < 0x7fffffffu); 173 174 if (buffer_string_space(env) < len) { 175 size_t extend = env->size * 2 - buffer_string_length(env); 176 extend = extend > len ? extend : len + 4095; 177 buffer_string_prepare_append(env, extend); 178 } 179 180 if (key_len > 127) { 181 len_enc[len_enc_len++] = ((key_len >> 24) & 0xff) | 0x80; 182 len_enc[len_enc_len++] = (key_len >> 16) & 0xff; 183 len_enc[len_enc_len++] = (key_len >> 8) & 0xff; 184 len_enc[len_enc_len++] = (key_len >> 0) & 0xff; 185 } else { 186 len_enc[len_enc_len++] = (key_len >> 0) & 0xff; 187 } 188 189 if (val_len > 127) { 190 len_enc[len_enc_len++] = ((val_len >> 24) & 0xff) | 0x80; 191 len_enc[len_enc_len++] = (val_len >> 16) & 0xff; 192 len_enc[len_enc_len++] = (val_len >> 8) & 0xff; 193 len_enc[len_enc_len++] = (val_len >> 0) & 0xff; 194 } else { 195 len_enc[len_enc_len++] = (val_len >> 0) & 0xff; 196 } 197 198 dst = buffer_string_prepare_append(env, len); 199 memcpy(dst, len_enc, len_enc_len); 200 memcpy(dst + len_enc_len, key, key_len); 201 memcpy(dst + len_enc_len + key_len, val, val_len); 202 buffer_commit(env, len); 203 204 return 0; 205 } 206 207 static void fcgi_header(FCGI_Header * header, unsigned char type, int request_id, int contentLength, unsigned char paddingLength) { 208 force_assert(contentLength <= FCGI_MAX_LENGTH); 209 210 header->version = FCGI_VERSION_1; 211 header->type = type; 212 header->requestIdB0 = request_id & 0xff; 213 header->requestIdB1 = (request_id >> 8) & 0xff; 214 header->contentLengthB0 = contentLength & 0xff; 215 header->contentLengthB1 = (contentLength >> 8) & 0xff; 216 header->paddingLength = paddingLength; 217 header->reserved = 0; 218 } 219 220 static handler_t fcgi_stdin_append(handler_ctx *hctx) { 221 FCGI_Header header; 222 chunkqueue * const req_cq = &hctx->r->reqbody_queue; 223 off_t offset, weWant; 224 const off_t req_cqlen = chunkqueue_length(req_cq); 225 int request_id = hctx->request_id; 226 227 /* something to send ? */ 228 for (offset = 0; offset != req_cqlen; offset += weWant) { 229 weWant = req_cqlen - offset > FCGI_MAX_LENGTH ? FCGI_MAX_LENGTH : req_cqlen - offset; 230 231 if (-1 != hctx->wb_reqlen) { 232 if (hctx->wb_reqlen >= 0) { 233 hctx->wb_reqlen += sizeof(header); 234 } else { 235 hctx->wb_reqlen -= sizeof(header); 236 } 237 } 238 239 fcgi_header(&(header), FCGI_STDIN, request_id, weWant, 0); 240 (chunkqueue_is_empty(&hctx->wb) || hctx->wb.first->type == MEM_CHUNK) /* else FILE_CHUNK for temp file */ 241 ? chunkqueue_append_mem(&hctx->wb, (const char *)&header, sizeof(header)) 242 : chunkqueue_append_mem_min(&hctx->wb, (const char *)&header, sizeof(header)); 243 chunkqueue_steal(&hctx->wb, req_cq, weWant); 244 /*(hctx->wb_reqlen already includes reqbody_length)*/ 245 } 246 247 if (hctx->wb.bytes_in == hctx->wb_reqlen) { 248 /* terminate STDIN */ 249 /* (future: must defer ending FCGI_STDIN 250 * if might later upgrade protocols 251 * and then have more data to send) */ 252 fcgi_header(&(header), FCGI_STDIN, request_id, 0, 0); 253 chunkqueue_append_mem(&hctx->wb, (const char *)&header, sizeof(header)); 254 hctx->wb_reqlen += (int)sizeof(header); 255 } 256 257 return HANDLER_GO_ON; 258 } 259 260 static handler_t fcgi_create_env(handler_ctx *hctx) { 261 FCGI_BeginRequestRecord beginRecord; 262 FCGI_Header header; 263 int request_id; 264 265 gw_host *host = hctx->host; 266 request_st * const r = hctx->r; 267 268 http_cgi_opts opts = { 269 (hctx->gw_mode == FCGI_AUTHORIZER), 270 host->break_scriptfilename_for_php, 271 host->docroot, 272 host->strip_request_uri 273 }; 274 275 size_t rsz = (size_t)(r->read_queue.bytes_out - hctx->wb.bytes_in); 276 if (rsz >= 65536) rsz = r->rqst_header_len; 277 buffer * const b = chunkqueue_prepend_buffer_open_sz(&hctx->wb, rsz); 278 279 /* send FCGI_BEGIN_REQUEST */ 280 281 if (hctx->request_id == 0) { 282 hctx->request_id = 1; /* always use id 1 as we don't use multiplexing */ 283 } else { 284 log_error(r->conf.errh, __FILE__, __LINE__, 285 "fcgi-request is already in use: %d", hctx->request_id); 286 } 287 request_id = hctx->request_id; 288 289 fcgi_header(&(beginRecord.header), FCGI_BEGIN_REQUEST, request_id, sizeof(beginRecord.body), 0); 290 beginRecord.body.roleB0 = hctx->gw_mode; 291 beginRecord.body.roleB1 = 0; 292 beginRecord.body.flags = 0; 293 memset(beginRecord.body.reserved, 0, sizeof(beginRecord.body.reserved)); 294 295 buffer_copy_string_len(b, (const char *)&beginRecord, sizeof(beginRecord)); 296 fcgi_header(&header, FCGI_PARAMS, request_id, 0, 0); /*(set aside space to fill in later)*/ 297 buffer_append_string_len(b, (const char *)&header, sizeof(header)); 298 299 /* send FCGI_PARAMS */ 300 301 if (0 != http_cgi_headers(r, &opts, fcgi_env_add, b)) { 302 r->http_status = 400; 303 r->handler_module = NULL; 304 buffer_clear(b); 305 chunkqueue_remove_finished_chunks(&hctx->wb); 306 return HANDLER_FINISHED; 307 } else { 308 fcgi_header(&(header), FCGI_PARAMS, request_id, 309 buffer_string_length(b) - sizeof(FCGI_BeginRequestRecord) - sizeof(FCGI_Header), 0); 310 memcpy(b->ptr+sizeof(FCGI_BeginRequestRecord), (const char *)&header, sizeof(header)); 311 312 fcgi_header(&(header), FCGI_PARAMS, request_id, 0, 0); 313 buffer_append_string_len(b, (const char *)&header, sizeof(header)); 314 315 hctx->wb_reqlen = buffer_string_length(b); 316 chunkqueue_prepend_buffer_commit(&hctx->wb); 317 } 318 319 if (r->reqbody_length) { 320 /*chunkqueue_append_chunkqueue(&hctx->wb, &r->reqbody_queue);*/ 321 if (r->reqbody_length > 0) 322 hctx->wb_reqlen += r->reqbody_length;/* (eventual) (minimal) total request size, not necessarily including all fcgi_headers around content length yet */ 323 else /* as-yet-unknown total request size (Transfer-Encoding: chunked)*/ 324 hctx->wb_reqlen = -hctx->wb_reqlen; 325 } 326 fcgi_stdin_append(hctx); 327 328 status_counter_inc(CONST_STR_LEN("fastcgi.requests")); 329 return HANDLER_GO_ON; 330 } 331 332 typedef struct { 333 unsigned int len; 334 int type; 335 int padding; 336 int request_id; 337 } fastcgi_response_packet; 338 339 static int fastcgi_get_packet(handler_ctx *hctx, fastcgi_response_packet *packet) { 340 FCGI_Header header; 341 off_t rblen = chunkqueue_length(hctx->rb); 342 if (rblen < (off_t)sizeof(FCGI_Header)) { 343 /* no header */ 344 if (hctx->conf.debug && 0 != rblen) { 345 log_error(hctx->r->conf.errh, __FILE__, __LINE__, 346 "FastCGI: header too small: %lld bytes < %zu bytes, " 347 "waiting for more data", (long long)rblen, sizeof(FCGI_Header)); 348 } 349 return -1; 350 } 351 char *ptr = (char *)&header; 352 uint32_t rd = sizeof(FCGI_Header); 353 if (chunkqueue_peek_data(hctx->rb, &ptr, &rd, hctx->r->conf.errh) < 0) 354 return -1; 355 if (rd != sizeof(FCGI_Header)) 356 return -1; 357 if (ptr != (char *)&header) /* copy into aligned struct */ 358 memcpy(&header, ptr, sizeof(FCGI_Header)); 359 360 /* we have at least a header, now check how much we have to fetch */ 361 packet->len = (header.contentLengthB0 | (header.contentLengthB1 << 8)) + header.paddingLength; 362 packet->request_id = (header.requestIdB0 | (header.requestIdB1 << 8)); 363 packet->type = header.type; 364 packet->padding = header.paddingLength; 365 366 if (packet->len > (unsigned int)rblen-sizeof(FCGI_Header)) { 367 return -1; /* we didn't get the full packet */ 368 } 369 370 chunkqueue_mark_written(hctx->rb, sizeof(FCGI_Header)); 371 return 0; 372 } 373 374 static void fastcgi_get_packet_body(buffer * const b, handler_ctx * const hctx, const fastcgi_response_packet * const packet) { 375 /* copy content; hctx->rb must contain at least packet->len content */ 376 /* (read entire packet and then truncate padding, if present) */ 377 const uint32_t blen = buffer_string_length(b); 378 if (chunkqueue_read_data(hctx->rb, 379 buffer_string_prepare_append(b, packet->len), 380 packet->len, hctx->r->conf.errh) < 0) 381 return; /*(should not happen; should all be in memory)*/ 382 buffer_string_set_length(b, blen + packet->len - packet->padding); 383 } 384 385 static int 386 mod_fastcgi_chunk_decode_transfer_cqlen (request_st * const r, chunkqueue * const src, const unsigned int len) 387 { 388 if (!r->resp_decode_chunked) 389 return http_chunk_transfer_cqlen(r, src, len); 390 391 if (0 == len) return 0; 392 393 /* specialized for mod_fastcgi to decode chunked encoding; 394 * FastCGI packet data is all type MEM_CHUNK 395 * entire src cq is processed, minus packet.padding at end 396 * (This extra work can be avoided if FastCGI backend does not send 397 * Transfer-Encoding: chunked, which FastCGI is not supposed to do) */ 398 uint32_t remain = len, wr; 399 for (const chunk *c = src->first; c && remain; c = c->next, remain -= wr) { 400 /*assert(c->type == MEM_CHUNK);*/ 401 wr = buffer_string_length(c->mem) - c->offset; 402 if (wr > remain) wr = remain; 403 if (0 != http_chunk_decode_append_mem(r, c->mem->ptr+c->offset, wr)) 404 return -1; 405 } 406 chunkqueue_mark_written(src, len); 407 return 0; 408 } 409 410 static handler_t fcgi_recv_parse(request_st * const r, struct http_response_opts_t *opts, buffer *b, size_t n) { 411 handler_ctx *hctx = (handler_ctx *)opts->pdata; 412 int fin = 0; 413 414 if (0 == n) { 415 if (-1 == hctx->request_id) return HANDLER_FINISHED; /*(flag request ended)*/ 416 if (!(fdevent_fdnode_interest(hctx->fdn) & FDEVENT_IN) 417 && !(r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_POLLRDHUP)) 418 return HANDLER_GO_ON; 419 log_error(r->conf.errh, __FILE__, __LINE__, 420 "unexpected end-of-file (perhaps the fastcgi process died):" 421 "pid: %d socket: %s", 422 hctx->proc->pid, hctx->proc->connection_name->ptr); 423 424 return HANDLER_ERROR; 425 } 426 427 chunkqueue_append_buffer(hctx->rb, b); 428 429 /* 430 * parse the fastcgi packets and forward the content to the write-queue 431 * 432 */ 433 while (fin == 0) { 434 fastcgi_response_packet packet; 435 436 /* check if we have at least one packet */ 437 if (0 != fastcgi_get_packet(hctx, &packet)) { 438 /* no full packet */ 439 break; 440 } 441 442 switch(packet.type) { 443 case FCGI_STDOUT: 444 if (packet.len == 0) break; 445 446 /* is the header already finished */ 447 if (0 == r->resp_body_started) { 448 /* split header from body */ 449 buffer *hdrs = hctx->response; 450 if (NULL == hdrs) { 451 hdrs = r->tmp_buf; 452 buffer_clear(hdrs); 453 } 454 fastcgi_get_packet_body(hdrs, hctx, &packet); 455 if (HANDLER_GO_ON != http_response_parse_headers(r, &hctx->opts, hdrs)) { 456 hctx->send_content_body = 0; 457 fin = 1; 458 break; 459 } 460 if (0 == r->resp_body_started) { 461 if (!hctx->response) { 462 hctx->response = chunk_buffer_acquire(); 463 buffer_copy_buffer(hctx->response, hdrs); 464 } 465 } 466 else if (hctx->gw_mode == GW_AUTHORIZER && 467 (r->http_status == 0 || r->http_status == 200)) { 468 /* authorizer approved request; ignore the content here */ 469 hctx->send_content_body = 0; 470 } 471 } else if (hctx->send_content_body) { 472 if (0 != mod_fastcgi_chunk_decode_transfer_cqlen(r, hctx->rb, packet.len - packet.padding)) { 473 /* error writing to tempfile; 474 * truncate response or send 500 if nothing sent yet */ 475 fin = 1; 476 } 477 if (packet.padding) chunkqueue_mark_written(hctx->rb, packet.padding); 478 } else { 479 chunkqueue_mark_written(hctx->rb, packet.len); 480 } 481 break; 482 case FCGI_STDERR: 483 if (packet.len) { 484 buffer * const tb = r->tmp_buf; 485 buffer_clear(tb); 486 fastcgi_get_packet_body(tb, hctx, &packet); 487 log_error_multiline_buffer(r->conf.errh, __FILE__, __LINE__, tb, 488 "FastCGI-stderr:"); 489 } 490 break; 491 case FCGI_END_REQUEST: 492 hctx->request_id = -1; /*(flag request ended)*/ 493 fin = 1; 494 break; 495 default: 496 log_error(r->conf.errh, __FILE__, __LINE__, 497 "FastCGI: header.type not handled: %d", packet.type); 498 chunkqueue_mark_written(hctx->rb, packet.len); 499 break; 500 } 501 } 502 503 return 0 == fin ? HANDLER_GO_ON : HANDLER_FINISHED; 504 } 505 506 static handler_t fcgi_check_extension(request_st * const r, void *p_d, int uri_path_handler) { 507 plugin_data *p = p_d; 508 handler_t rc; 509 510 if (NULL != r->handler_module) return HANDLER_GO_ON; 511 512 mod_fastcgi_patch_config(r, p); 513 if (NULL == p->conf.exts) return HANDLER_GO_ON; 514 515 rc = gw_check_extension(r, p, uri_path_handler, 0); 516 if (HANDLER_GO_ON != rc) return rc; 517 518 if (r->handler_module == p->self) { 519 handler_ctx *hctx = r->plugin_ctx[p->id]; 520 hctx->opts.backend = BACKEND_FASTCGI; 521 hctx->opts.parse = fcgi_recv_parse; 522 hctx->opts.pdata = hctx; 523 hctx->stdin_append = fcgi_stdin_append; 524 hctx->create_env = fcgi_create_env; 525 if (!hctx->rb) { 526 hctx->rb = chunkqueue_init(NULL); 527 } 528 else { 529 chunkqueue_reset(hctx->rb); 530 } 531 } 532 533 return HANDLER_GO_ON; 534 } 535 536 /* uri-path handler */ 537 static handler_t fcgi_check_extension_1(request_st * const r, void *p_d) { 538 return fcgi_check_extension(r, p_d, 1); 539 } 540 541 /* start request handler */ 542 static handler_t fcgi_check_extension_2(request_st * const r, void *p_d) { 543 return fcgi_check_extension(r, p_d, 0); 544 } 545 546 547 int mod_fastcgi_plugin_init(plugin *p); 548 int mod_fastcgi_plugin_init(plugin *p) { 549 p->version = LIGHTTPD_VERSION_ID; 550 p->name = "fastcgi"; 551 552 p->init = gw_init; 553 p->cleanup = gw_free; 554 p->set_defaults = mod_fastcgi_set_defaults; 555 p->handle_request_reset = gw_handle_request_reset; 556 p->handle_uri_clean = fcgi_check_extension_1; 557 p->handle_subrequest_start = fcgi_check_extension_2; 558 p->handle_subrequest = gw_handle_subrequest; 559 p->handle_trigger = gw_handle_trigger; 560 p->handle_waitpid = gw_handle_waitpid_cb; 561 562 return 0; 563 } 564