summaryrefslogtreecommitdiff
path: root/src/mod_proxy_backend_fastcgi.c
blob: 2358fa3a7101dcabde93afdc0d72ac708d05a443 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
#include <stdlib.h>
#include <string.h>

#include "inet_ntop_cache.h"
#include "mod_proxy_core.h"
#include "buffer.h"
#include "log.h"
#include "fastcgi.h"

int proxy_fastcgi_get_env_fastcgi(server *srv, connection *con, plugin_data *p, proxy_session *sess) {
	buffer *b;

	char buf[32];
	const char *s;
	server_socket *srv_sock = con->srv_socket;
#ifdef HAVE_IPV6
	char b2[INET6_ADDRSTRLEN + 1];
#endif

	sock_addr our_addr;
	socklen_t our_addr_len;

	proxy_set_header(sess->env_headers, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_STR_LEN(PACKAGE_NAME"/"PACKAGE_VERSION));

	if (con->server_name->used) {
		proxy_set_header(sess->env_headers, CONST_STR_LEN("SERVER_NAME"), CONST_BUF_LEN(con->server_name));
	} else {
#ifdef HAVE_IPV6
		s = inet_ntop(srv_sock->addr.plain.sa_family,
			      srv_sock->addr.plain.sa_family == AF_INET6 ?
			      (const void *) &(srv_sock->addr.ipv6.sin6_addr) :
			      (const void *) &(srv_sock->addr.ipv4.sin_addr),
			      b2, sizeof(b2)-1);
#else
		s = inet_ntoa(srv_sock->addr.ipv4.sin_addr);
#endif
		proxy_set_header(sess->env_headers, CONST_STR_LEN("SERVER_NAME"), s, strlen(s));
	}

	proxy_set_header(sess->env_headers, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1"));

	ltostr(buf,
#ifdef HAVE_IPV6
	       ntohs(srv_sock->addr.plain.sa_family ? srv_sock->addr.ipv6.sin6_port : srv_sock->addr.ipv4.sin_port)
#else
	       ntohs(srv_sock->addr.ipv4.sin_port)
#endif
	       );

	proxy_set_header(sess->env_headers, CONST_STR_LEN("SERVER_PORT"), buf, strlen(buf));

	/* get the server-side of the connection to the client */
	our_addr_len = sizeof(our_addr);

	if (-1 == getsockname(con->sock->fd, &(our_addr.plain), &our_addr_len)) {
		s = inet_ntop_cache_get_ip(srv, &(srv_sock->addr));
	} else {
		s = inet_ntop_cache_get_ip(srv, &(our_addr));
	}
	proxy_set_header(sess->env_headers, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s));

	ltostr(buf,
#ifdef HAVE_IPV6
	       ntohs(con->dst_addr.plain.sa_family ? con->dst_addr.ipv6.sin6_port : con->dst_addr.ipv4.sin_port)
#else
	       ntohs(con->dst_addr.ipv4.sin_port)
#endif
	       );

	proxy_set_header(sess->env_headers, CONST_STR_LEN("REMOTE_PORT"), buf, strlen(buf));

	s = inet_ntop_cache_get_ip(srv, &(con->dst_addr));
	proxy_set_header(sess->env_headers, CONST_STR_LEN("REMOTE_ADDR"), s, strlen(s));

	if (!buffer_is_empty(con->authed_user)) {
		proxy_set_header(sess->env_headers, CONST_STR_LEN("REMOTE_USER"),
			     CONST_BUF_LEN(con->authed_user));
	}

	if (con->request.content_length > 0) {
		/* CGI-SPEC 6.1.2 and FastCGI spec 6.3 */

		/* request.content_length < SSIZE_MAX, see request.c */
		ltostr(buf, con->request.content_length);
		proxy_set_header(sess->env_headers, CONST_STR_LEN("CONTENT_LENGTH"), buf, strlen(buf));
	}

	
	/*
	 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
	 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
	 * (6.1.14, 6.1.6, 6.1.7)
	 * For AUTHORIZER mode these headers should be omitted.
	 */

	proxy_set_header(sess->env_headers, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path));

	if (!buffer_is_empty(con->request.pathinfo)) {
		proxy_set_header(sess->env_headers, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo));

		/* PATH_TRANSLATED is only defined if PATH_INFO is set */

		buffer_copy_string_buffer(p->tmp_buf, con->physical.doc_root);
		buffer_append_string_buffer(p->tmp_buf, con->request.pathinfo);
		proxy_set_header(sess->env_headers, CONST_STR_LEN("PATH_TRANSLATED"), CONST_BUF_LEN(p->tmp_buf));
	} else {
		proxy_set_header(sess->env_headers, CONST_STR_LEN("PATH_INFO"), CONST_STR_LEN(""));
	}

	/*
	 * SCRIPT_FILENAME and DOCUMENT_ROOT for php. The PHP manual
	 * http://www.php.net/manual/en/reserved.variables.php
	 * treatment of PATH_TRANSLATED is different from the one of CGI specs.
	 * TODO: this code should be checked against cgi.fix_pathinfo php
	 * parameter.
	 */

	if (1) {
		proxy_set_header(sess->env_headers, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(con->physical.path));
		proxy_set_header(sess->env_headers, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.doc_root));
	}

	proxy_set_header(sess->env_headers, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri));

	if (!buffer_is_equal(con->request.uri, con->request.orig_uri)) {
		proxy_set_header(sess->env_headers, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(con->request.uri));
	}
	if (!buffer_is_empty(con->uri.query)) {
		proxy_set_header(sess->env_headers, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con->uri.query));
	} else {
		proxy_set_header(sess->env_headers, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN(""));
	}

	s = get_http_method_name(con->request.http_method);
	proxy_set_header(sess->env_headers, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s));
	proxy_set_header(sess->env_headers, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200")); /* if php is compiled with --force-redirect */
	s = get_http_version_name(con->request.http_version);
	proxy_set_header(sess->env_headers, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s));

#ifdef USE_OPENSSL
	if (srv_sock->is_ssl) {
		proxy_set_header(sess->env_headers, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
	}
#endif

	return 0;
}

/**
 * transform the HTTP-Request headers into CGI notation
 */
int proxy_fastcgi_get_env_request(server *srv, connection *con, plugin_data *p, proxy_session *sess) {
	size_t i;
	/* the request header got already copied into the sess->request_headers for us
	 * no extra filter is needed
	 *
	 * prepend a HTTP_ and uppercase the keys
	 */
	for (i = 0; i < sess->request_headers->used; i++) {
		data_string *ds;
		size_t j;

		ds = (data_string *)sess->request_headers->data[i];

		buffer_reset(p->tmp_buf);

		if (0 != strcasecmp(ds->key->ptr, "CONTENT-TYPE")) {
			BUFFER_COPY_STRING_CONST(p->tmp_buf, "HTTP_");
			p->tmp_buf->used--;
		}

		buffer_prepare_append(p->tmp_buf, ds->key->used + 2);
		for (j = 0; j < ds->key->used - 1; j++) {
			char c = '_';
			if (light_isalpha(ds->key->ptr[j])) {
				/* upper-case */
				c = ds->key->ptr[j] & ~32;
			} else if (light_isdigit(ds->key->ptr[j])) {
				/* copy */
				c = ds->key->ptr[j];
			}
			p->tmp_buf->ptr[p->tmp_buf->used++] = c;
		}
		p->tmp_buf->ptr[p->tmp_buf->used++] = '\0';

		proxy_set_header(sess->env_headers, CONST_BUF_LEN(p->tmp_buf), CONST_BUF_LEN(ds->value));
	}

	return 0;
}


/**
 * add a key-value pair to the fastcgi-buffer
 */

static int fcgi_env_add(buffer *env, const char *key, size_t key_len, const char *val, size_t val_len) {
	size_t len;

	if (!key || !val) return -1;

	len = key_len + val_len;

	len += key_len > 127 ? 4 : 1;
	len += val_len > 127 ? 4 : 1;

	buffer_prepare_append(env, len);

	if (key_len > 127) {
		env->ptr[env->used++] = ((key_len >> 24) & 0xff) | 0x80;
		env->ptr[env->used++] = (key_len >> 16) & 0xff;
		env->ptr[env->used++] = (key_len >> 8) & 0xff;
		env->ptr[env->used++] = (key_len >> 0) & 0xff;
	} else {
		env->ptr[env->used++] = (key_len >> 0) & 0xff;
	}

	if (val_len > 127) {
		env->ptr[env->used++] = ((val_len >> 24) & 0xff) | 0x80;
		env->ptr[env->used++] = (val_len >> 16) & 0xff;
		env->ptr[env->used++] = (val_len >> 8) & 0xff;
		env->ptr[env->used++] = (val_len >> 0) & 0xff;
	} else {
		env->ptr[env->used++] = (val_len >> 0) & 0xff;
	}

	memcpy(env->ptr + env->used, key, key_len);
	env->used += key_len;
	memcpy(env->ptr + env->used, val, val_len);
	env->used += val_len;

	return 0;
}

/**
 * init the FCGI_header 
 */
static int fcgi_header(FCGI_Header * header, unsigned char type, size_t request_id, int contentLength, unsigned char paddingLength) {
	header->version = FCGI_VERSION_1;
	header->type = type;
	header->requestIdB0 = request_id & 0xff;
	header->requestIdB1 = (request_id >> 8) & 0xff;
	header->contentLengthB0 = contentLength & 0xff;
	header->contentLengthB1 = (contentLength >> 8) & 0xff;
	header->paddingLength = paddingLength;
	header->reserved = 0;

	return 0;
}


int proxy_fastcgi_get_request_chunk(server *srv, connection *con, plugin_data *p, proxy_session *sess, chunkqueue *cq) {
	buffer *b, *packet;
	size_t i;
	FCGI_BeginRequestRecord beginRecord;
	FCGI_Header header;
	int request_id = 1;

	b = chunkqueue_get_append_buffer(cq);
	/* send FCGI_BEGIN_REQUEST */

	fcgi_header(&(beginRecord.header), FCGI_BEGIN_REQUEST, request_id, sizeof(beginRecord.body), 0);
	beginRecord.body.roleB0 = FCGI_RESPONDER;
	beginRecord.body.roleB1 = 0;
	beginRecord.body.flags = 0;
	memset(beginRecord.body.reserved, 0, sizeof(beginRecord.body.reserved));

	buffer_copy_string_len(b, (const char *)&beginRecord, sizeof(beginRecord));

	/* send FCGI_PARAMS */
	b = chunkqueue_get_append_buffer(cq);
	buffer_prepare_copy(b, 1024);

	/* fill the sess->env_headers */
	array_reset(sess->env_headers);
	proxy_fastcgi_get_env_request(srv, con, p, sess);
	proxy_fastcgi_get_env_fastcgi(srv, con, p, sess);

	packet = buffer_init();

	for (i = 0; i < sess->env_headers->used; i++) {
		data_string *ds;

		ds = (data_string *)sess->env_headers->data[i];
		fcgi_env_add(packet, CONST_BUF_LEN(ds->key), CONST_BUF_LEN(ds->value));
	}

	fcgi_header(&(header), FCGI_PARAMS, request_id, packet->used, 0);
	buffer_append_memory(b, (const char *)&header, sizeof(header));
	buffer_append_memory(b, (const char *)packet->ptr, packet->used);

	buffer_free(packet);

	fcgi_header(&(header), FCGI_PARAMS, request_id, 0, 0);
	buffer_append_memory(b, (const char *)&header, sizeof(header));

	b = chunkqueue_get_append_buffer(cq);
	/* terminate STDIN */
	fcgi_header(&(header), FCGI_STDIN, request_id, 0, 0);
	buffer_copy_memory(b, (const char *)&header, sizeof(header));
	b->used++; /* add virtual \0 */

	return 0;
}


typedef struct {
	buffer  *b;
	size_t   len;
	int      type;
	int      padding;
	size_t   request_id;
} fastcgi_response_packet;

int proxy_fastcgi_stream_decoder(server *srv, proxy_session *sess, chunkqueue *raw, chunkqueue *decoded) {
	chunk *	c;
	size_t offset = 0;
	size_t toread = 0;
	FCGI_Header *header;
	fastcgi_response_packet packet;
	buffer *b;

	if (!raw->first) return 0;

	packet.b = buffer_init();
	packet.len = 0;
	packet.type = 0;
	packet.padding = 0;
	packet.request_id = 0;

	/* get at least the FastCGI header */
	for (c = raw->first; c; c = c->next) {
		if (packet.b->used == 0) {
			buffer_copy_string_len(packet.b, c->mem->ptr + c->offset, c->mem->used - c->offset - 1);
		} else {
			buffer_append_string_len(packet.b, c->mem->ptr + c->offset, c->mem->used - c->offset - 1);
		}

		if (packet.b->used >= sizeof(*header) + 1) break;
	}

	if ((packet.b->used == 0) ||
	    (packet.b->used - 1 < sizeof(FCGI_Header))) {
		/* no header */
		buffer_free(packet.b);

		ERROR("%s", "FastCGI: header too small");
		return -1;
	}

	/* we have at least a header, now check how much me have to fetch */
	header = (FCGI_Header *)(packet.b->ptr);

	packet.len = (header->contentLengthB0 | (header->contentLengthB1 << 8)) + header->paddingLength;
	packet.request_id = (header->requestIdB0 | (header->requestIdB1 << 8));
	packet.type = header->type;
	packet.padding = header->paddingLength;

	/* the first bytes in packet->b are the header */
	offset = sizeof(*header);

	buffer_copy_string(packet.b, "");

	if (packet.len) {
		/* copy the content */
		for (; c && (packet.b->used < packet.len + 1); c = c->next) {
			size_t weWant = packet.len - (packet.b->used - 1);
			size_t weHave = c->mem->used - c->offset - offset - 1;

			if (weHave > weWant) weHave = weWant;

			buffer_append_string_len(packet.b, c->mem->ptr + c->offset + offset, weHave);

			/* we only skipped the first 8 bytes as they are the fcgi header */
			offset = 0;
		}

		if (packet.b->used < packet.len + 1) {
			/* we didn't got the full packet */

			buffer_free(packet.b);

			TRACE("%s", "need more");

			return 0;
		}

		packet.b->used -= packet.padding;
		packet.b->ptr[packet.b->used - 1] = '\0';
	}

	/* tag the chunks as read */
	toread = packet.len + sizeof(FCGI_Header);
	for (c = raw->first; c && toread; c = c->next) {
		if (c->mem->used - c->offset - 1 <= toread) {
			/* we read this whole buffer, move it to unused */
			toread -= c->mem->used - c->offset - 1;
			c->offset = c->mem->used - 1; /* everthing has been written */
		} else {
			c->offset += toread;
			toread = 0;
		}
	}

	chunkqueue_remove_finished_chunks(raw);

	/* we are still here ? */

	switch (packet.type) {
	case FCGI_STDOUT:
		b = chunkqueue_get_append_buffer(decoded);
		buffer_copy_string_buffer(b, packet.b);
		buffer_free(packet.b);
		return 0;
	case FCGI_STDERR:
		TRACE("(fastcgi-stderr) %s", BUF_STR(packet.b));
		buffer_free(packet.b);
		return 0;
	case FCGI_END_REQUEST:
		buffer_free(packet.b);
		return 1;
	default:
		buffer_free(packet.b);

		TRACE("unknown packet.type: %d", packet.type);
		return -1;
	}
}

/**
 * parse the response header
 *
 * NOTE: this can be used by all backends as they all send a HTTP-Response a clean block
 * - fastcgi needs some decoding for the protocol
 */
parse_status_t proxy_fastcgi_parse_response_header(server *srv, connection *con, plugin_data *p, proxy_session *sess, chunkqueue *cq) {
	int have_content_length = 0;
	size_t i;
	off_t old_len = chunkqueue_length(cq);

	http_response_reset(p->resp);

	/* decode the whole packet stream */
	do {
		
		old_len = chunkqueue_length(cq);
		/* decode the packet */
		switch (proxy_fastcgi_stream_decoder(srv, sess, cq, sess->recv)) {
		case 0:
			break;
		case 1:
			/* the FIN packet was catched, why ever */
			return PARSE_ERROR;
		case -1:
			return PARSE_ERROR;
		}
	} while (chunkqueue_length(cq) != old_len);
	
	switch (http_response_parse_cq(sess->recv, p->resp)) {
	case PARSE_ERROR:
		/* parsing failed */

		return PARSE_ERROR;
	case PARSE_NEED_MORE:
		return PARSE_NEED_MORE;
	case PARSE_SUCCESS:
		con->http_status = p->resp->status;

		chunkqueue_remove_finished_chunks(cq);

		sess->content_length = -1;

		/* copy the http-headers */
		for (i = 0; i < p->resp->headers->used; i++) {
			const char *ign[] = { "Status", "Connection", NULL };
			size_t j, k;
			data_string *ds;

			data_string *header = (data_string *)p->resp->headers->data[i];

			/* some headers are ignored by default */
			for (j = 0; ign[j]; j++) {
				if (0 == strcasecmp(ign[j], header->key->ptr)) break;
			}
			if (ign[j]) continue;

			if (0 == buffer_caseless_compare(CONST_BUF_LEN(header->key), CONST_STR_LEN("Location"))) {
				/* CGI/1.1 rev 03 - 7.2.1.2 */
				if (con->http_status == 0) con->http_status = 302;
			} else if (0 == buffer_caseless_compare(CONST_BUF_LEN(header->key), CONST_STR_LEN("Content-Length"))) {
				have_content_length = 1;

				sess->content_length = strtol(header->value->ptr, NULL, 10);

				if (sess->content_length < 0) {
					return PARSE_ERROR;
				}
			} else if (0 == buffer_caseless_compare(CONST_BUF_LEN(header->key), CONST_STR_LEN("Transfer-Encoding"))) {
				if (strstr(header->value->ptr, "chunked")) {
					sess->is_chunked = 1;
				}
				/* ignore the header */
				continue;
			}
			
			if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
				ds = data_response_init();
			}


			buffer_copy_string_buffer(ds->key, header->key);

			for (k = 0; k < p->conf.response_rewrites->used; k++) {
				proxy_rewrite *rw = p->conf.response_rewrites->ptr[k];

				if (buffer_is_equal(rw->header, header->key)) {
					int ret;
	
					if ((ret = pcre_replace(rw->regex, rw->replace, header->value, p->replace_buf)) < 0) {
						switch (ret) {
						case PCRE_ERROR_NOMATCH:
							/* hmm, ok. no problem */
							buffer_append_string_buffer(ds->value, header->value);
							break;
						default:
							TRACE("oops, pcre_replace failed with: %d", ret);
							break;
						}
					} else {
						buffer_append_string_buffer(ds->value, p->replace_buf);
					}

					break;
				}
			}

			if (k == p->conf.response_rewrites->used) {
				buffer_copy_string_buffer(ds->value, header->value);
			}

			array_insert_unique(con->response.headers, (data_unset *)ds);
		}

		/* does the client allow us to send chunked encoding ? */
		if (con->request.http_version == HTTP_VERSION_1_1 &&
		    !have_content_length) {
			con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
   		}

		break;
	}

	return PARSE_SUCCESS; /* we have a full header */
}