summaryrefslogtreecommitdiffhomepage
path: root/contrib/package/uhttpd/src/uhttpd-cgi.c
blob: 4342d279ebe1833bf6745bf15ffc7af9d8327b20 (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
/*
 * uhttpd - Tiny non-forking httpd - CGI handler
 *
 *   Copyright (C) 2010 Jo-Philipp Wich <xm@subsignal.org>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include "uhttpd.h"
#include "uhttpd-utils.h"
#include "uhttpd-cgi.h"

static struct http_response * uh_cgi_header_parse(char *buf, int len, int *off)
{
	char *bufptr = NULL;
	char *hdrname = NULL;
	int hdrcount = 0;
	int pos = 0;

	static struct http_response res;


	if( ((bufptr = strfind(buf, len, "\r\n\r\n", 4)) != NULL) ||
	    ((bufptr = strfind(buf, len, "\n\n", 2)) != NULL)
	) {
		*off = (int)(bufptr - buf) + ((bufptr[0] == '\r') ? 4 : 2);

		memset(&res, 0, sizeof(res));

		res.statuscode = 200;
		res.statusmsg  = "OK";

		bufptr = &buf[0];

		for( pos = 0; pos < len; pos++ )
		{
			if( !hdrname && (buf[pos] == ':') )
			{
				buf[pos++] = 0;

				if( (pos < len) && (buf[pos] == ' ') )
					pos++;

				if( pos < len )
				{
					hdrname = bufptr;
					bufptr = &buf[pos];
				}
			}

			else if( (buf[pos] == '\r') || (buf[pos] == '\n') )
			{
				buf[pos++] = 0;

				if( ! hdrname )
					break;

				if( (pos < len) && (buf[pos] == '\n') )
					pos++;

				if( pos < len )
				{
					if( (hdrcount + 1) < array_size(res.headers) )
					{
						if( ! strcasecmp(hdrname, "Status") )
						{
							res.statuscode = atoi(bufptr);

							if( res.statuscode < 100 )
								res.statuscode = 200;

							if( ((bufptr = strchr(bufptr, ' ')) != NULL) && (&bufptr[1] != 0) )
								res.statusmsg = &bufptr[1];
						}
						else
						{
							res.headers[hdrcount++] = hdrname;
							res.headers[hdrcount++] = bufptr;
						}

						bufptr = &buf[pos];
						hdrname = NULL;
					}
					else
					{
						return NULL;
					}
				}
			}
		}

		return &res;
	}

	return NULL;
}

static char * uh_cgi_header_lookup(struct http_response *res, const char *hdrname)
{
	int i;

	foreach_header(i, res->headers)
	{
		if( ! strcasecmp(res->headers[i], hdrname) )
			return res->headers[i+1];
	}

	return NULL;
}

static void uh_cgi_error_500(struct client *cl, struct http_request *req, const char *message)
{
	uh_http_sendf(cl, NULL,
		"HTTP/%.1f 500 Internal Server Error\r\n"
		"Content-Type: text/plain\r\n%s\r\n",
			req->version, 
			(req->version > 1.0)
				? "Transfer-Encoding: chunked\r\n" : ""
	);

	uh_http_send(cl, req, message, -1);
}


void uh_cgi_request(struct client *cl, struct http_request *req, struct path_info *pi)
{
	int i, hdroff, bufoff;
	int hdrlen = 0;
	int buflen = 0;
	int fd_max = 0;
	int content_length = 0;
	int header_sent = 0;

	int rfd[2] = { 0, 0 };
	int wfd[2] = { 0, 0 };

	char buf[UH_LIMIT_MSGHEAD];
	char hdr[UH_LIMIT_MSGHEAD];

	fd_set reader;
	fd_set writer;

	struct timeval timeout;
	struct http_response *res;


	/* spawn pipes for me->child, child->me */
	if( (pipe(rfd) < 0) || (pipe(wfd) < 0) )
	{
		uh_http_sendhf(cl, 500, "Internal Server Error",
			"Failed to create pipe: %s", strerror(errno));

		if( rfd[0] > 0 ) close(rfd[0]);
		if( rfd[1] > 0 ) close(rfd[1]);
		if( wfd[0] > 0 ) close(wfd[0]);
		if( wfd[1] > 0 ) close(wfd[1]);

		return;
	}

	/* fork off child process */
	switch( fork() )
	{
		/* oops */
		case -1:
			uh_http_sendhf(cl, 500, "Internal Server Error",
				"Failed to fork child: %s", strerror(errno));
			return;

		/* exec child */
		case 0:
			/* child */
			close(rfd[0]);
			close(wfd[1]);

			/* patch stdout and stdin to pipes */
			dup2(rfd[1], 1);
			dup2(wfd[0], 0);

			/* check for regular, world-executable file */
			if( (pi->stat.st_mode & S_IFREG) &&
			    (pi->stat.st_mode & S_IXOTH)
			) {
				/* build environment */
				clearenv();

				/* common information */
				setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
				setenv("SERVER_SOFTWARE", "uHTTPd", 1);
				setenv("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);

#ifdef HAVE_TLS
				/* https? */
				if( cl->tls )
					setenv("HTTPS", "on", 1);
#endif

				/* addresses */
				setenv("SERVER_NAME", sa_straddr(&cl->servaddr), 1);
				setenv("SERVER_ADDR", sa_straddr(&cl->servaddr), 1);
				setenv("SERVER_PORT", sa_strport(&cl->servaddr), 1);
				setenv("REMOTE_HOST", sa_straddr(&cl->peeraddr), 1);
				setenv("REMOTE_ADDR", sa_straddr(&cl->peeraddr), 1);
				setenv("REMOTE_PORT", sa_strport(&cl->peeraddr), 1);

				/* path information */
				setenv("SCRIPT_NAME", pi->name, 1);
				setenv("SCRIPT_FILENAME", pi->phys, 1);
				setenv("DOCUMENT_ROOT", pi->root, 1);
				setenv("QUERY_STRING", pi->query ? pi->query : "", 1);

				if( pi->info )
					setenv("PATH_INFO", pi->info, 1);


				/* http version */
				if( req->version > 1.0 )
					setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
				else
					setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);

				/* request method */
				switch( req->method )
				{
					case UH_HTTP_MSG_GET:
						setenv("REQUEST_METHOD", "GET", 1);
						break;

					case UH_HTTP_MSG_HEAD:
						setenv("REQUEST_METHOD", "HEAD", 1);
						break;

					case UH_HTTP_MSG_POST:
						setenv("REQUEST_METHOD", "POST", 1);
						break;
				}

				/* request url */
				setenv("REQUEST_URI", req->url, 1);

				/* remote user */
				if( req->realm )
					setenv("REMOTE_USER", req->realm->user, 1);

				/* request message headers */
				foreach_header(i, req->headers)
				{
					if( ! strcasecmp(req->headers[i], "Accept") )
						setenv("HTTP_ACCEPT", req->headers[i+1], 1);

					else if( ! strcasecmp(req->headers[i], "Accept-Charset") )
						setenv("HTTP_ACCEPT_CHARSET", req->headers[i+1], 1);

					else if( ! strcasecmp(req->headers[i], "Accept-Encoding") )
						setenv("HTTP_ACCEPT_ENCODING", req->headers[i+1], 1);

					else if( ! strcasecmp(req->headers[i], "Accept-Language") )
						setenv("HTTP_ACCEPT_LANGUAGE", req->headers[i+1], 1);

					else if( ! strcasecmp(req->headers[i], "Authorization") )
						setenv("HTTP_AUTHORIZATION", req->headers[i+1], 1);

					else if( ! strcasecmp(req->headers[i], "Connection") )
						setenv("HTTP_CONNECTION", req->headers[i+1], 1);

					else if( ! strcasecmp(req->headers[i], "Cookie") )
						setenv("HTTP_COOKIE", req->headers[i+1], 1);

					else if( ! strcasecmp(req->headers[i], "Host") )
						setenv("HTTP_HOST", req->headers[i+1], 1);

					else if( ! strcasecmp(req->headers[i], "Referer") )
						setenv("HTTP_REFERER", req->headers[i+1], 1);

					else if( ! strcasecmp(req->headers[i], "User-Agent") )
						setenv("HTTP_USER_AGENT", req->headers[i+1], 1);

					else if( ! strcasecmp(req->headers[i], "Content-Type") )
						setenv("CONTENT_TYPE", req->headers[i+1], 1);

					else if( ! strcasecmp(req->headers[i], "Content-Length") )
						setenv("CONTENT_LENGTH", req->headers[i+1], 1);
				}


				/* execute child code ... */
				if( chdir(pi->root) )
					perror("chdir()");

				execl(pi->phys, pi->phys, NULL);

				/* in case it fails ... */
				printf(
					"Status: 500 Internal Server Error\r\n\r\n"
					"Unable to launch the requested CGI program:\n"
					"  %s: %s\n",
						pi->phys, strerror(errno)
				);
			}

			/* 403 */
			else
			{
				printf(
					"Status: 403 Forbidden\r\n\r\n"
					"Access to this resource is forbidden\n"
				);
			}

			close(wfd[0]);
			close(rfd[1]);
			exit(0);

			break;

		/* parent; handle I/O relaying */
		default:
			/* close unneeded pipe ends */
			close(rfd[1]);
			close(wfd[0]);

			/* max watch fd */
			fd_max = max(rfd[0], wfd[1]) + 1;

			/* find content length */
			if( req->method == UH_HTTP_MSG_POST )
			{
				foreach_header(i, req->headers)
				{
					if( ! strcasecmp(req->headers[i], "Content-Length") )
					{
						content_length = atoi(req->headers[i+1]);
						break;
					}
				}
			}


			memset(hdr, 0, sizeof(hdr));

			/* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
			while( 1 )
			{
				FD_ZERO(&reader);
				FD_ZERO(&writer);

				FD_SET(rfd[0], &reader);
				FD_SET(wfd[1], &writer);

				timeout.tv_sec = 15;
				timeout.tv_usec = 0;

				/* wait until we can read or write or both */
				if( select(fd_max, &reader, (content_length > -1) ? &writer : NULL, NULL, &timeout) > 0 )
				{
					/* ready to write to cgi program */
					if( FD_ISSET(wfd[1], &writer) )
					{
						/* there is unread post data waiting */
						if( content_length > 0 )
						{
							/* read it from socket ... */
							if( (buflen = uh_tcp_recv(cl, buf, min(content_length, sizeof(buf)))) > 0 )
							{
								/* ... and write it to child's stdin */
								if( write(wfd[1], buf, buflen) < 0 )
									perror("write()");

								content_length -= buflen;
							}

							/* unexpected eof! */
							else
							{
								if( write(wfd[1], "", 0) < 0 )
									perror("write()");

								content_length = 0;
							}
						}

						/* there is no more post data, close pipe to child's stdin */
						else
						{
							close(wfd[1]);
							content_length = -1;
						}
					}

					/* ready to read from cgi program */
					if( FD_ISSET(rfd[0], &reader) )
					{
						/* read data from child ... */
						if( (buflen = read(rfd[0], buf, sizeof(buf))) > 0 )
						{
							/* we have not pushed out headers yet, parse input */
							if( ! header_sent )
							{
								/* head buffer not full and no end yet */
								if( hdrlen < sizeof(hdr) )
								{
									bufoff = min(buflen, sizeof(hdr) - hdrlen);
									memcpy(&hdr[hdrlen], buf, bufoff);
									hdrlen += bufoff;
								}
								else
								{
									bufoff = 0;
								}


								/* try to parse header ... */
								if( (res = uh_cgi_header_parse(hdr, hdrlen, &hdroff)) != NULL )
								{
									/* write status */
									uh_http_sendf(cl, NULL, "HTTP/%.1f %03d %s\r\n",
										req->version, res->statuscode, res->statusmsg);

									/* add Content-Type if no Location or Content-Type */
									if( !uh_cgi_header_lookup(res, "Location") &&
									    !uh_cgi_header_lookup(res, "Content-Type")
									) {
										uh_http_send(cl, NULL,
											"Content-Type: text/plain\r\n", -1);
									}

									/* if request was HTTP 1.1 we'll respond chunked */
									if( (req->version > 1.0) &&
									    !uh_cgi_header_lookup(res, "Transfer-Encoding")
									) {
										uh_http_send(cl, NULL,
											"Transfer-Encoding: chunked\r\n", -1);
									}

									/* write headers from CGI program */
									foreach_header(i, res->headers)
									{
										uh_http_sendf(cl, NULL, "%s: %s\r\n",
											res->headers[i], res->headers[i+1]);
									}

									/* terminate header */
									uh_http_send(cl, NULL, "\r\n", -1);

									/* push out remaining head buffer */
									if( hdroff < hdrlen )
										uh_http_send(cl, req, &hdr[hdroff], hdrlen - hdroff);
								}

								/* ... failed and head buffer exceeded */
								else if( hdrlen >= sizeof(hdr) )
								{
									uh_cgi_error_500(cl, req,
										"The CGI program generated an invalid response:\n\n");

									uh_http_send(cl, req, hdr, hdrlen);
								}

								/* ... failed but free buffer space, try again */
								else
								{
									continue;
								}

								/* push out remaining read buffer */
								if( bufoff < buflen )
									uh_http_send(cl, req, &buf[bufoff], buflen - bufoff);

								header_sent = 1;
								continue;
							}


							/* headers complete, pass through buffer to socket */
							uh_http_send(cl, req, buf, buflen);
						}

						/* looks like eof from child */
						else
						{
							/* cgi script did not output useful stuff at all */
							if( ! header_sent )
							{
								/* I would do this ...
								 *
								 *    uh_cgi_error_500(cl, req,
								 *        "The CGI program generated an "
								 *        "invalid response:\n\n");
								 *
								 * ... but in order to stay as compatible as possible,
								 * treat whatever we got as text/plain response and
								 * build the required headers here.
								 */

								uh_http_sendf(cl, NULL,
									"HTTP/%.1f 200 OK\r\n"
									"Content-Type: text/plain\r\n"
									"%s\r\n",
										req->version, (req->version > 1.0)
											? "Transfer-Encoding: chunked\r\n" : ""
								);

								uh_http_send(cl, req, hdr, hdrlen);
							}

							/* send final chunk if we're in chunked transfer mode */
							uh_http_send(cl, req, "", 0);
							break;
						}
					}
				}

				/* no activity for 15 seconds... looks dead */
				else
				{
					uh_http_sendhf(cl, 504, "Gateway Timeout",
						"The CGI script took too long to produce a response");

					break;
				}
			}

			close(rfd[0]);
			close(wfd[1]);

			break;
	}
}