httpd.c 27 KB
Newer Older
1
/*
2
 * Copyright (C) 2006-2008, 2010-2015  Internet Systems Consortium, Inc. ("ISC")
3
 *
Automatic Updater's avatar
Automatic Updater committed
4
 * Permission to use, copy, modify, and/or distribute this software for any
5
6
7
8
9
10
11
12
13
14
15
16
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

Mark Andrews's avatar
Mark Andrews committed
17
/* $Id$ */
18
19
20

/*! \file */

21
22
#include <config.h>

23
24
25
#include <isc/buffer.h>
#include <isc/httpd.h>
#include <isc/mem.h>
26
#include <isc/print.h>
27
28
29
#include <isc/socket.h>
#include <isc/string.h>
#include <isc/task.h>
Evan Hunt's avatar
Evan Hunt committed
30
#include <isc/time.h>
31
32
33
34
35
36
37
38
#include <isc/util.h>

#include <string.h>

/*%
 * TODO:
 *
 *  o  Put in better checks to make certain things are passed in correctly.
39
 *     This includes a magic number for externally-visible structures,
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
 *     checking for NULL-ness before dereferencing, etc.
 *  o  Make the URL processing external functions which will fill-in a buffer
 *     structure we provide, or return an error and we will render a generic
 *     page and close the client.
 */

#define MSHUTTINGDOWN(cm) ((cm->flags & ISC_HTTPDMGR_FLAGSHUTTINGDOWN) != 0)
#define MSETSHUTTINGDOWN(cm) (cm->flags |= ISC_HTTPDMGR_FLAGSHUTTINGDOWN)

#ifdef DEBUG_HTTPD
#define ENTER(x) do { fprintf(stderr, "ENTER %s\n", (x)); } while (0)
#define EXIT(x) do { fprintf(stderr, "EXIT %s\n", (x)); } while (0)
#define NOTICE(x) do { fprintf(stderr, "NOTICE %s\n", (x)); } while (0)
#else
#define ENTER(x) do { } while(0)
#define EXIT(x) do { } while(0)
#define NOTICE(x) do { } while(0)
#endif

#define HTTP_RECVLEN			1024
#define HTTP_SENDGROW			1024
#define HTTP_SEND_MAXLEN		10240

#define HTTPD_CLOSE		0x0001 /* Got a Connection: close header */
#define HTTPD_FOUNDHOST		0x0002 /* Got a Host: header */
65
#define HTTPD_KEEPALIVE		0x0004 /* Got a Connection: Keep-Alive */
66
67
68
69
70
71
72
73
74
75
76
77
78

/*% http client */
struct isc_httpd {
	isc_httpdmgr_t	       *mgr;		/*%< our parent */
	ISC_LINK(isc_httpd_t)	link;
	unsigned int		state;
	isc_socket_t		*sock;

	/*%
	 * Received data state.
	 */
	char			recvbuf[HTTP_RECVLEN]; /*%< receive buffer */
	isc_uint32_t		recvlen;	/*%< length recv'd */
Evan Hunt's avatar
Evan Hunt committed
79
	char		       *headers;	/*%< set in process_request() */
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
	unsigned int		method;
	char		       *url;
	char		       *querystring;
	char		       *protocol;

	/*
	 * Flags on the httpd client.
	 */
	int			flags;

	/*%
	 * Transmit data state.
	 *
	 * This is the data buffer we will transmit.
	 *
	 * This free function pointer is filled in by the rendering function
	 * we call.  The free function is called after the data is transmitted
	 * to the client.
	 *
	 * The bufflist is the list of buffers we are currently transmitting.
	 * The headerdata is where we render our headers to.  If we run out of
	 * space when rendering a header, we will change the size of our
	 * buffer.  We will not free it until we are finished, and will
	 * allocate an additional HTTP_SENDGROW bytes per header space grow.
	 *
	 * We currently use two buffers total, one for the headers (which
	 * we manage) and another for the client to fill in (which it manages,
	 * it provides the space for it, etc) -- we will pass that buffer
	 * structure back to the caller, who is responsible for managing the
	 * space it may have allocated as backing store for it.  This second
	 * buffer is bodybuffer, and we only allocate the buffer itself, not
	 * the backing store.
	 */
	isc_bufferlist_t	bufflist;
	char		       *headerdata; /*%< send header buf */
	unsigned int		headerlen;  /*%< current header buffer size */
	isc_buffer_t		headerbuffer;

	const char	       *mimetype;
	unsigned int		retcode;
	const char	       *retmsg;
	isc_buffer_t		bodybuffer;
	isc_httpdfree_t	       *freecb;
	void		       *freecb_arg;
};

/*% lightweight socket manager for httpd output */
struct isc_httpdmgr {
	isc_mem_t	       *mctx;
	isc_socket_t	       *sock;		/*%< listening socket */
	isc_task_t	       *task;		/*%< owning task */
	isc_timermgr_t	       *timermgr;

133
134
135
136
	isc_httpdclientok_t    *client_ok;	/*%< client validator */
	isc_httpdondestroy_t   *ondestroy;	/*%< cleanup callback */
	void		       *cb_arg;		/*%< argument for the above */

137
138
139
140
141
142
143
	unsigned int		flags;
	ISC_LIST(isc_httpd_t)	running;	/*%< running clients */

	isc_mutex_t		lock;

	ISC_LIST(isc_httpdurl_t) urls;		/*%< urls we manage */
	isc_httpdaction_t      *render_404;
144
	isc_httpdaction_t      *render_500;
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
};

/*%
 * HTTP methods.
 */
#define ISC_HTTPD_METHODUNKNOWN	0
#define ISC_HTTPD_METHODGET	1
#define ISC_HTTPD_METHODPOST	2

/*%
 * Client states.
 *
 * _IDLE	The client is not doing anything at all.  This state should
 *		only occur just after creation, and just before being
 *		destroyed.
 *
 * _RECV	The client is waiting for data after issuing a socket recv().
 *
 * _RECVDONE	Data has been received, and is being processed.
 *
 * _SEND	All data for a response has completed, and a reply was
 *		sent via a socket send() call.
 *
 * _SENDDONE	Send is completed.
 *
 * Badly formatted state table:
 *
 *	IDLE -> RECV when client has a recv() queued.
 *
 *	RECV -> RECVDONE when recvdone event received.
 *
 *	RECVDONE -> SEND if the data for a reply is at hand.
 *
 *	SEND -> RECV when a senddone event was received.
 *
 *	At any time -> RECV on error.  If RECV fails, the client will
 *	self-destroy, closing the socket and freeing memory.
 */
#define ISC_HTTPD_STATEIDLE	0
#define ISC_HTTPD_STATERECV	1
#define ISC_HTTPD_STATERECVDONE	2
#define ISC_HTTPD_STATESEND	3
#define ISC_HTTPD_STATESENDDONE	4

#define ISC_HTTPD_ISRECV(c)	((c)->state == ISC_HTTPD_STATERECV)
#define ISC_HTTPD_ISRECVDONE(c)	((c)->state == ISC_HTTPD_STATERECVDONE)
#define ISC_HTTPD_ISSEND(c)	((c)->state == ISC_HTTPD_STATESEND)
#define ISC_HTTPD_ISSENDDONE(c)	((c)->state == ISC_HTTPD_STATESENDDONE)

/*%
 * Overall magic test that means we're not idle.
 */
#define ISC_HTTPD_SETRECV(c)	((c)->state = ISC_HTTPD_STATERECV)
#define ISC_HTTPD_SETRECVDONE(c)	((c)->state = ISC_HTTPD_STATERECVDONE)
#define ISC_HTTPD_SETSEND(c)	((c)->state = ISC_HTTPD_STATESEND)
#define ISC_HTTPD_SETSENDDONE(c)	((c)->state = ISC_HTTPD_STATESENDDONE)

static void isc_httpd_accept(isc_task_t *, isc_event_t *);
static void isc_httpd_recvdone(isc_task_t *, isc_event_t *);
static void isc_httpd_senddone(isc_task_t *, isc_event_t *);
static void destroy_client(isc_httpd_t **);
static isc_result_t process_request(isc_httpd_t *, int);
static void httpdmgr_destroy(isc_httpdmgr_t *);
static isc_result_t grow_headerspace(isc_httpd_t *);
static void reset_client(isc_httpd_t *httpd);
Evan Hunt's avatar
Evan Hunt committed
210
211
212

static isc_httpdaction_t render_404;
static isc_httpdaction_t render_500;
213
214

static void
Evan Hunt's avatar
Evan Hunt committed
215
destroy_client(isc_httpd_t **httpdp) {
216
217
218
	isc_httpd_t *httpd = *httpdp;
	isc_httpdmgr_t *httpdmgr = httpd->mgr;

Mark Andrews's avatar
Mark Andrews committed
219
220
	*httpdp = NULL;

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
	LOCK(&httpdmgr->lock);

	isc_socket_detach(&httpd->sock);
	ISC_LIST_UNLINK(httpdmgr->running, httpd, link);

	if (httpd->headerlen > 0)
		isc_mem_put(httpdmgr->mctx, httpd->headerdata,
			    httpd->headerlen);

	isc_mem_put(httpdmgr->mctx, httpd, sizeof(isc_httpd_t));

	UNLOCK(&httpdmgr->lock);

	httpdmgr_destroy(httpdmgr);
}

isc_result_t
isc_httpdmgr_create(isc_mem_t *mctx, isc_socket_t *sock, isc_task_t *task,
239
240
		    isc_httpdclientok_t *client_ok,
		    isc_httpdondestroy_t *ondestroy, void *cb_arg,
241
		    isc_timermgr_t *tmgr, isc_httpdmgr_t **httpdmgrp)
242
243
{
	isc_result_t result;
244
	isc_httpdmgr_t *httpdmgr;
245
246
247
248
249

	REQUIRE(mctx != NULL);
	REQUIRE(sock != NULL);
	REQUIRE(task != NULL);
	REQUIRE(tmgr != NULL);
250
	REQUIRE(httpdmgrp != NULL && *httpdmgrp == NULL);
251

252
253
	httpdmgr = isc_mem_get(mctx, sizeof(isc_httpdmgr_t));
	if (httpdmgr == NULL)
254
255
		return (ISC_R_NOMEMORY);

256
	result = isc_mutex_init(&httpdmgr->lock);
257
	if (result != ISC_R_SUCCESS) {
258
		isc_mem_put(mctx, httpdmgr, sizeof(isc_httpdmgr_t));
259
260
		return (result);
	}
261
262
263
264
265
266
267
268
269
270
271
272
273
274
	httpdmgr->mctx = NULL;
	isc_mem_attach(mctx, &httpdmgr->mctx);
	httpdmgr->sock = NULL;
	isc_socket_attach(sock, &httpdmgr->sock);
	httpdmgr->task = NULL;
	isc_task_attach(task, &httpdmgr->task);
	httpdmgr->timermgr = tmgr; /* XXXMLG no attach function? */
	httpdmgr->client_ok = client_ok;
	httpdmgr->ondestroy = ondestroy;
	httpdmgr->cb_arg = cb_arg;
	httpdmgr->flags = 0;

	ISC_LIST_INIT(httpdmgr->running);
	ISC_LIST_INIT(httpdmgr->urls);
275

Mark Andrews's avatar
cleanup    
Mark Andrews committed
276
	/* XXXMLG ignore errors on isc_socket_listen() */
277
	result = isc_socket_listen(sock, SOMAXCONN);
278
	if (result != ISC_R_SUCCESS) {
279
280
281
282
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				 "isc_socket_listen() failed: %s",
				 isc_result_totext(result));
		goto cleanup;
283
284
	}

285
286
	(void)isc_socket_filter(sock, "httpready");

287
	result = isc_socket_accept(sock, task, isc_httpd_accept, httpdmgr);
288
289
290
	if (result != ISC_R_SUCCESS)
		goto cleanup;

291
292
	httpdmgr->render_404 = render_404;
	httpdmgr->render_500 = render_500;
293

294
	*httpdmgrp = httpdmgr;
295
	return (ISC_R_SUCCESS);
296
297

  cleanup:
298
299
300
301
302
	isc_task_detach(&httpdmgr->task);
	isc_socket_detach(&httpdmgr->sock);
	isc_mem_detach(&httpdmgr->mctx);
	(void)isc_mutex_destroy(&httpdmgr->lock);
	isc_mem_put(mctx, httpdmgr, sizeof(isc_httpdmgr_t));
303
	return (result);
304
305
306
}

static void
Evan Hunt's avatar
Evan Hunt committed
307
httpdmgr_destroy(isc_httpdmgr_t *httpdmgr) {
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
	isc_mem_t *mctx;
	isc_httpdurl_t *url;

	ENTER("httpdmgr_destroy");

	LOCK(&httpdmgr->lock);

	if (!MSHUTTINGDOWN(httpdmgr)) {
		NOTICE("httpdmgr_destroy not shutting down yet");
		UNLOCK(&httpdmgr->lock);
		return;
	}

	/*
	 * If all clients are not shut down, don't do anything yet.
	 */
	if (!ISC_LIST_EMPTY(httpdmgr->running)) {
		NOTICE("httpdmgr_destroy clients still active");
		UNLOCK(&httpdmgr->lock);
		return;
	}

	NOTICE("httpdmgr_destroy detaching socket, task, and timermgr");

	isc_socket_detach(&httpdmgr->sock);
	isc_task_detach(&httpdmgr->task);
	httpdmgr->timermgr = NULL;

	/*
	 * Clear out the list of all actions we know about.  Just free the
	 * memory.
	 */
	url = ISC_LIST_HEAD(httpdmgr->urls);
	while (url != NULL) {
		isc_mem_free(httpdmgr->mctx, url->url);
		ISC_LIST_UNLINK(httpdmgr->urls, url, link);
		isc_mem_put(httpdmgr->mctx, url, sizeof(isc_httpdurl_t));
		url = ISC_LIST_HEAD(httpdmgr->urls);
	}

	UNLOCK(&httpdmgr->lock);
349
	(void)isc_mutex_destroy(&httpdmgr->lock);
350

351
352
353
	if (httpdmgr->ondestroy != NULL)
		(httpdmgr->ondestroy)(httpdmgr->cb_arg);

354
	mctx = httpdmgr->mctx;
Mark Andrews's avatar
cleanup    
Mark Andrews committed
355
	isc_mem_putanddetach(&mctx, httpdmgr, sizeof(isc_httpdmgr_t));
356
357
358
359
360
361
362
363

	EXIT("httpdmgr_destroy");
}

#define LENGTHOK(s) (httpd->recvbuf - (s) < (int)httpd->recvlen)
#define BUFLENOK(s) (httpd->recvbuf - (s) < HTTP_RECVLEN)

static isc_result_t
Evan Hunt's avatar
Evan Hunt committed
364
process_request(isc_httpd_t *httpd, int length) {
365
366
367
368
369
370
371
372
373
	char *s;
	char *p;
	int delim;

	ENTER("request");

	httpd->recvlen += length;

	httpd->recvbuf[httpd->recvlen] = 0;
Evan Hunt's avatar
Evan Hunt committed
374
	httpd->headers = NULL;
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

	/*
	 * If we don't find a blank line in our buffer, return that we need
	 * more data.
	 */
	s = strstr(httpd->recvbuf, "\r\n\r\n");
	delim = 1;
	if (s == NULL) {
		s = strstr(httpd->recvbuf, "\n\n");
		delim = 2;
	}
	if (s == NULL)
		return (ISC_R_NOTFOUND);

	/*
	 * Determine if this is a POST or GET method.  Any other values will
	 * cause an error to be returned.
	 */
	if (strncmp(httpd->recvbuf, "GET ", 4) == 0) {
		httpd->method = ISC_HTTPD_METHODGET;
		p = httpd->recvbuf + 4;
	} else if (strncmp(httpd->recvbuf, "POST ", 5) == 0) {
		httpd->method = ISC_HTTPD_METHODPOST;
		p = httpd->recvbuf + 5;
	} else {
		return (ISC_R_RANGE);
	}

	/*
	 * From now on, p is the start of our buffer.
	 */

	/*
	 * Extract the URL.
	 */
	s = p;
	while (LENGTHOK(s) && BUFLENOK(s) &&
	       (*s != '\n' && *s != '\r' && *s != '\0' && *s != ' '))
		s++;
	if (!LENGTHOK(s))
		return (ISC_R_NOTFOUND);
	if (!BUFLENOK(s))
		return (ISC_R_NOMEMORY);
	*s = 0;

	/*
	 * Make the URL relative.
	 */
	if ((strncmp(p, "http:/", 6) == 0)
	    || (strncmp(p, "https:/", 7) == 0)) {
		/* Skip first / */
		while (*p != '/' && *p != 0)
			p++;
		if (*p == 0)
			return (ISC_R_RANGE);
		p++;
		/* Skip second / */
		while (*p != '/' && *p != 0)
			p++;
		if (*p == 0)
			return (ISC_R_RANGE);
		p++;
		/* Find third / */
		while (*p != '/' && *p != 0)
			p++;
		if (*p == 0) {
			p--;
			*p = '/';
		}
	}

	httpd->url = p;
	p = s + delim;
	s = p;

	/*
	 * Now, see if there is a ? mark in the URL.  If so, this is
	 * part of the query string, and we will split it from the URL.
	 */
	httpd->querystring = strchr(httpd->url, '?');
	if (httpd->querystring != NULL) {
		*(httpd->querystring) = 0;
		httpd->querystring++;
	}

	/*
	 * Extract the HTTP/1.X protocol.  We will bounce on anything but
	 * HTTP/1.1 for now.
	 */
	while (LENGTHOK(s) && BUFLENOK(s) &&
	       (*s != '\n' && *s != '\r' && *s != '\0'))
		s++;
	if (!LENGTHOK(s))
		return (ISC_R_NOTFOUND);
	if (!BUFLENOK(s))
		return (ISC_R_NOMEMORY);
	*s = 0;
	if ((strncmp(p, "HTTP/1.0", 8) != 0)
	    && (strncmp(p, "HTTP/1.1", 8) != 0))
		return (ISC_R_RANGE);
	httpd->protocol = p;
	p = s + 1;
	s = p;

Evan Hunt's avatar
Evan Hunt committed
479
480
	httpd->headers = s;

481
482
483
484
485
486
	if (strstr(s, "Connection: close") != NULL)
		httpd->flags |= HTTPD_CLOSE;

	if (strstr(s, "Host: ") != NULL)
		httpd->flags |= HTTPD_FOUNDHOST;

487
488
489
490
491
492
493
	if (strncmp(httpd->protocol, "HTTP/1.0", 8) == 0) {
		if (strcasestr(s, "Connection: Keep-Alive") != NULL)
			httpd->flags |= HTTPD_KEEPALIVE;
		else
			httpd->flags |= HTTPD_CLOSE;
	}

494
495
496
497
498
499
500
501
502
503
504
505
506
	/*
	 * Standards compliance hooks here.
	 */
	if (strcmp(httpd->protocol, "HTTP/1.1") == 0
	    && ((httpd->flags & HTTPD_FOUNDHOST) == 0))
		return (ISC_R_RANGE);

	EXIT("request");

	return (ISC_R_SUCCESS);
}

static void
Evan Hunt's avatar
Evan Hunt committed
507
isc_httpd_accept(isc_task_t *task, isc_event_t *ev) {
508
509
510
511
512
	isc_result_t result;
	isc_httpdmgr_t *httpdmgr = ev->ev_arg;
	isc_httpd_t *httpd;
	isc_region_t r;
	isc_socket_newconnev_t *nev = (isc_socket_newconnev_t *)ev;
513
	isc_sockaddr_t peeraddr;
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528

	ENTER("accept");

	LOCK(&httpdmgr->lock);
	if (MSHUTTINGDOWN(httpdmgr)) {
		NOTICE("accept shutting down, goto out");
		goto out;
	}

	if (nev->result == ISC_R_CANCELED) {
		NOTICE("accept canceled, goto out");
		goto out;
	}

	if (nev->result != ISC_R_SUCCESS) {
Mark Andrews's avatar
cleanup    
Mark Andrews committed
529
		/* XXXMLG log failure */
530
531
532
533
		NOTICE("accept returned failure, goto requeue");
		goto requeue;
	}

534
535
536
537
538
539
540
	(void)isc_socket_getpeername(nev->newsocket, &peeraddr);
	if (httpdmgr->client_ok != NULL &&
	    !(httpdmgr->client_ok)(&peeraddr, httpdmgr->cb_arg)) {
		isc_socket_detach(&nev->newsocket);
		goto requeue;
	}

541
542
	httpd = isc_mem_get(httpdmgr->mctx, sizeof(isc_httpd_t));
	if (httpd == NULL) {
Mark Andrews's avatar
cleanup    
Mark Andrews committed
543
		/* XXXMLG log failure */
544
		NOTICE("accept failed to allocate memory, goto requeue");
545
		isc_socket_detach(&nev->newsocket);
546
547
548
549
550
551
552
553
		goto requeue;
	}

	httpd->mgr = httpdmgr;
	ISC_LINK_INIT(httpd, link);
	ISC_LIST_APPEND(httpdmgr->running, httpd, link);
	ISC_HTTPD_SETRECV(httpd);
	httpd->sock = nev->newsocket;
554
	isc_socket_setname(httpd->sock, "httpd", NULL);
555
556
557
558
559
560
561
562
	httpd->flags = 0;

	/*
	 * Initialize the buffer for our headers.
	 */
	httpd->headerdata = isc_mem_get(httpdmgr->mctx, HTTP_SENDGROW);
	if (httpd->headerdata == NULL) {
		isc_mem_put(httpdmgr->mctx, httpd, sizeof(isc_httpd_t));
563
		isc_socket_detach(&nev->newsocket);
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
		goto requeue;
	}
	httpd->headerlen = HTTP_SENDGROW;
	isc_buffer_init(&httpd->headerbuffer, httpd->headerdata,
			httpd->headerlen);

	ISC_LIST_INIT(httpd->bufflist);

	isc_buffer_initnull(&httpd->bodybuffer);
	reset_client(httpd);

	r.base = (unsigned char *)httpd->recvbuf;
	r.length = HTTP_RECVLEN - 1;
	result = isc_socket_recv(httpd->sock, &r, 1, task, isc_httpd_recvdone,
				 httpd);
579
580
	/* FIXME!!! */
	POST(result);
581
582
583
584
585
586
	NOTICE("accept queued recv on socket");

 requeue:
	result = isc_socket_accept(httpdmgr->sock, task, isc_httpd_accept,
				   httpdmgr);
	if (result != ISC_R_SUCCESS) {
Mark Andrews's avatar
cleanup    
Mark Andrews committed
587
		/* XXXMLG what to do?  Log failure... */
588
589
590
591
592
593
594
595
596
597
598
599
600
601
		NOTICE("accept could not reaccept due to failure");
	}

 out:
	UNLOCK(&httpdmgr->lock);

	httpdmgr_destroy(httpdmgr);

	isc_event_free(&ev);

	EXIT("accept");
}

static isc_result_t
Evan Hunt's avatar
Evan Hunt committed
602
603
render_404(const char *url, isc_httpdurl_t *urlinfo,
	   const char *querystring, const char *headers, void *arg,
604
605
606
607
	   unsigned int *retcode, const char **retmsg,
	   const char **mimetype, isc_buffer_t *b,
	   isc_httpdfree_t **freecb, void **freecb_args)
{
608
	static char msg[] = "No such URL.\r\n";
609
610

	UNUSED(url);
Evan Hunt's avatar
Evan Hunt committed
611
	UNUSED(urlinfo);
612
	UNUSED(querystring);
Evan Hunt's avatar
Evan Hunt committed
613
	UNUSED(headers);
614
615
616
617
618
619
620
621
622
623
624
625
626
	UNUSED(arg);

	*retcode = 404;
	*retmsg = "No such URL";
	*mimetype = "text/plain";
	isc_buffer_reinit(b, msg, strlen(msg));
	isc_buffer_add(b, strlen(msg));
	*freecb = NULL;
	*freecb_args = NULL;

	return (ISC_R_SUCCESS);
}

627
static isc_result_t
Evan Hunt's avatar
Evan Hunt committed
628
629
render_500(const char *url, isc_httpdurl_t *urlinfo,
	   const char *querystring, const char *headers, void *arg,
630
631
632
633
	   unsigned int *retcode, const char **retmsg,
	   const char **mimetype, isc_buffer_t *b,
	   isc_httpdfree_t **freecb, void **freecb_args)
{
634
	static char msg[] = "Internal server failure.\r\n";
635
636

	UNUSED(url);
Evan Hunt's avatar
Evan Hunt committed
637
	UNUSED(urlinfo);
638
	UNUSED(querystring);
Evan Hunt's avatar
Evan Hunt committed
639
	UNUSED(headers);
640
641
642
643
644
645
646
647
648
649
650
651
652
	UNUSED(arg);

	*retcode = 500;
	*retmsg = "Internal server failure";
	*mimetype = "text/plain";
	isc_buffer_reinit(b, msg, strlen(msg));
	isc_buffer_add(b, strlen(msg));
	*freecb = NULL;
	*freecb_args = NULL;

	return (ISC_R_SUCCESS);
}

653
static void
Evan Hunt's avatar
Evan Hunt committed
654
isc_httpd_recvdone(isc_task_t *task, isc_event_t *ev) {
655
656
657
658
659
660
	isc_region_t r;
	isc_result_t result;
	isc_httpd_t *httpd = ev->ev_arg;
	isc_socketevent_t *sev = (isc_socketevent_t *)ev;
	isc_httpdurl_t *url;
	isc_time_t now;
Evan Hunt's avatar
Evan Hunt committed
661
	char datebuf[ISC_FORMATHTTPTIMESTAMP_SIZE];
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680

	ENTER("recv");

	INSIST(ISC_HTTPD_ISRECV(httpd));

	if (sev->result != ISC_R_SUCCESS) {
		NOTICE("recv destroying client");
		destroy_client(&httpd);
		goto out;
	}

	result = process_request(httpd, sev->n);
	if (result == ISC_R_NOTFOUND) {
		if (httpd->recvlen >= HTTP_RECVLEN - 1) {
			destroy_client(&httpd);
			goto out;
		}
		r.base = (unsigned char *)httpd->recvbuf + httpd->recvlen;
		r.length = HTTP_RECVLEN - httpd->recvlen - 1;
681
682
683
		/* check return code? */
		(void)isc_socket_recv(httpd->sock, &r, 1, task,
				      isc_httpd_recvdone, httpd);
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
		goto out;
	} else if (result != ISC_R_SUCCESS) {
		destroy_client(&httpd);
		goto out;
	}

	ISC_HTTPD_SETSEND(httpd);

	/*
	 * XXXMLG Call function here.  Provide an add-header function
	 * which will append the common headers to a response we generate.
	 */
	isc_buffer_initnull(&httpd->bodybuffer);
	isc_time_now(&now);
	isc_time_formathttptimestamp(&now, datebuf, sizeof(datebuf));
	url = ISC_LIST_HEAD(httpd->mgr->urls);
	while (url != NULL) {
		if (strcmp(httpd->url, url->url) == 0)
			break;
		url = ISC_LIST_NEXT(url, link);
	}
	if (url == NULL)
Evan Hunt's avatar
Evan Hunt committed
706
707
708
		result = httpd->mgr->render_404(httpd->url, NULL,
						httpd->querystring,
						NULL, NULL,
709
710
711
712
713
714
715
						&httpd->retcode,
						&httpd->retmsg,
						&httpd->mimetype,
						&httpd->bodybuffer,
						&httpd->freecb,
						&httpd->freecb_arg);
	else
Evan Hunt's avatar
Evan Hunt committed
716
717
718
		result = url->action(httpd->url, url,
				     httpd->querystring,
				     httpd->headers,
719
720
721
722
723
				     url->action_arg,
				     &httpd->retcode, &httpd->retmsg,
				     &httpd->mimetype, &httpd->bodybuffer,
				     &httpd->freecb, &httpd->freecb_arg);
	if (result != ISC_R_SUCCESS) {
Evan Hunt's avatar
Evan Hunt committed
724
725
726
727
		result = httpd->mgr->render_500(httpd->url, url,
						httpd->querystring,
						NULL, NULL,
						&httpd->retcode,
728
729
730
731
732
733
						&httpd->retmsg,
						&httpd->mimetype,
						&httpd->bodybuffer,
						&httpd->freecb,
						&httpd->freecb_arg);
		RUNTIME_CHECK(result == ISC_R_SUCCESS);
734
	}
Automatic Updater's avatar
Automatic Updater committed
735

736
	isc_httpd_response(httpd);
737
738
	if ((httpd->flags & HTTPD_KEEPALIVE) != 0)
		isc_httpd_addheader(httpd, "Connection", "Keep-Alive");
739
740
741
	isc_httpd_addheader(httpd, "Content-Type", httpd->mimetype);
	isc_httpd_addheader(httpd, "Date", datebuf);
	isc_httpd_addheader(httpd, "Expires", datebuf);
Evan Hunt's avatar
Evan Hunt committed
742
743

	if (url != NULL && url->isstatic) {
Evan Hunt's avatar
Evan Hunt committed
744
		char loadbuf[ISC_FORMATHTTPTIMESTAMP_SIZE];
Evan Hunt's avatar
Evan Hunt committed
745
746
747
748
749
750
751
752
753
754
		isc_time_formathttptimestamp(&url->loadtime,
					     loadbuf, sizeof(loadbuf));
		isc_httpd_addheader(httpd, "Last-Modified", loadbuf);
		isc_httpd_addheader(httpd, "Cache-Control: public", NULL);
	} else {
		isc_httpd_addheader(httpd, "Last-Modified", datebuf);
		isc_httpd_addheader(httpd, "Pragma: no-cache", NULL);
		isc_httpd_addheader(httpd, "Cache-Control: no-cache", NULL);
	}

755
756
757
758
759
760
761
762
763
764
765
766
767
768
	isc_httpd_addheader(httpd, "Server: libisc", NULL);
	isc_httpd_addheaderuint(httpd, "Content-Length",
				isc_buffer_usedlength(&httpd->bodybuffer));
	isc_httpd_endheaders(httpd);  /* done */

	ISC_LIST_APPEND(httpd->bufflist, &httpd->headerbuffer, link);
	/*
	 * Link the data buffer into our send queue, should we have any data
	 * rendered into it.  If no data is present, we won't do anything
	 * with the buffer.
	 */
	if (isc_buffer_length(&httpd->bodybuffer) > 0)
		ISC_LIST_APPEND(httpd->bufflist, &httpd->bodybuffer, link);

769
770
771
	/* check return code? */
	(void)isc_socket_sendv(httpd->sock, &httpd->bufflist, task,
			       isc_httpd_senddone, httpd);
772
773
774
775
776
777
778

 out:
	isc_event_free(&ev);
	EXIT("recv");
}

void
Evan Hunt's avatar
Evan Hunt committed
779
isc_httpdmgr_shutdown(isc_httpdmgr_t **httpdmgrp) {
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
	isc_httpdmgr_t *httpdmgr;
	isc_httpd_t *httpd;
	httpdmgr = *httpdmgrp;
	*httpdmgrp = NULL;

	ENTER("isc_httpdmgr_shutdown");

	LOCK(&httpdmgr->lock);

	MSETSHUTTINGDOWN(httpdmgr);

	isc_socket_cancel(httpdmgr->sock, httpdmgr->task, ISC_SOCKCANCEL_ALL);

	httpd = ISC_LIST_HEAD(httpdmgr->running);
	while (httpd != NULL) {
		isc_socket_cancel(httpd->sock, httpdmgr->task,
				  ISC_SOCKCANCEL_ALL);
		httpd = ISC_LIST_NEXT(httpd, link);
	}

	UNLOCK(&httpdmgr->lock);

	EXIT("isc_httpdmgr_shutdown");
}

static isc_result_t
Evan Hunt's avatar
Evan Hunt committed
806
grow_headerspace(isc_httpd_t *httpd) {
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
	char *newspace;
	unsigned int newlen;
	isc_region_t r;

	newlen = httpd->headerlen + HTTP_SENDGROW;
	if (newlen > HTTP_SEND_MAXLEN)
		return (ISC_R_NOSPACE);

	newspace = isc_mem_get(httpd->mgr->mctx, newlen);
	if (newspace == NULL)
		return (ISC_R_NOMEMORY);
	isc_buffer_region(&httpd->headerbuffer, &r);
	isc_buffer_reinit(&httpd->headerbuffer, newspace, newlen);

	isc_mem_put(httpd->mgr->mctx, r.base, r.length);

	return (ISC_R_SUCCESS);
}

isc_result_t
Evan Hunt's avatar
Evan Hunt committed
827
isc_httpd_response(isc_httpd_t *httpd) {
828
829
830
831
832
833
834
	isc_result_t result;
	unsigned int needlen;

	needlen = strlen(httpd->protocol) + 1; /* protocol + space */
	needlen += 3 + 1;  /* room for response code, always 3 bytes */
	needlen += strlen(httpd->retmsg) + 2;  /* return msg + CRLF */

835
	while (isc_buffer_availablelength(&httpd->headerbuffer) < needlen) {
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
		result = grow_headerspace(httpd);
		if (result != ISC_R_SUCCESS)
			return (result);
	}

	sprintf(isc_buffer_used(&httpd->headerbuffer), "%s %03d %s\r\n",
		httpd->protocol, httpd->retcode, httpd->retmsg);
	isc_buffer_add(&httpd->headerbuffer, needlen);

	return (ISC_R_SUCCESS);
}

isc_result_t
isc_httpd_addheader(isc_httpd_t *httpd, const char *name,
		    const char *val)
{
	isc_result_t result;
	unsigned int needlen;

	needlen = strlen(name); /* name itself */
	if (val != NULL)
		needlen += 2 + strlen(val); /* :<space> and val */
	needlen += 2; /* CRLF */

860
	while (isc_buffer_availablelength(&httpd->headerbuffer) < needlen) {
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
		result = grow_headerspace(httpd);
		if (result != ISC_R_SUCCESS)
			return (result);
	}

	if (val != NULL)
		sprintf(isc_buffer_used(&httpd->headerbuffer),
			"%s: %s\r\n", name, val);
	else
		sprintf(isc_buffer_used(&httpd->headerbuffer),
			"%s\r\n", name);

	isc_buffer_add(&httpd->headerbuffer, needlen);

	return (ISC_R_SUCCESS);
}

isc_result_t
Evan Hunt's avatar
Evan Hunt committed
879
isc_httpd_endheaders(isc_httpd_t *httpd) {
880
881
	isc_result_t result;

882
	while (isc_buffer_availablelength(&httpd->headerbuffer) < 2) {
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
		result = grow_headerspace(httpd);
		if (result != ISC_R_SUCCESS)
			return (result);
	}

	sprintf(isc_buffer_used(&httpd->headerbuffer), "\r\n");
	isc_buffer_add(&httpd->headerbuffer, 2);

	return (ISC_R_SUCCESS);
}

isc_result_t
isc_httpd_addheaderuint(isc_httpd_t *httpd, const char *name, int val) {
	isc_result_t result;
	unsigned int needlen;
	char buf[sizeof "18446744073709551616"];

	sprintf(buf, "%d", val);

	needlen = strlen(name); /* name itself */
	needlen += 2 + strlen(buf); /* :<space> and val */
	needlen += 2; /* CRLF */

906
	while (isc_buffer_availablelength(&httpd->headerbuffer) < needlen) {
907
908
909
910
911
912
913
914
915
916
917
918
919
920
		result = grow_headerspace(httpd);
		if (result != ISC_R_SUCCESS)
			return (result);
	}

	sprintf(isc_buffer_used(&httpd->headerbuffer),
		"%s: %s\r\n", name, buf);

	isc_buffer_add(&httpd->headerbuffer, needlen);

	return (ISC_R_SUCCESS);
}

static void
Evan Hunt's avatar
Evan Hunt committed
921
isc_httpd_senddone(isc_task_t *task, isc_event_t *ev) {
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
	isc_httpd_t *httpd = ev->ev_arg;
	isc_region_t r;
	isc_socketevent_t *sev = (isc_socketevent_t *)ev;

	ENTER("senddone");
	INSIST(ISC_HTTPD_ISSEND(httpd));

	/*
	 * First, unlink our header buffer from the socket's bufflist.  This
	 * is sort of an evil hack, since we know our buffer will be there,
	 * and we know it's address, so we can just remove it directly.
	 */
	NOTICE("senddone unlinked header");
	ISC_LIST_UNLINK(sev->bufferlist, &httpd->headerbuffer, link);

	/*
	 * We will always want to clean up our receive buffer, even if we
	 * got an error on send or we are shutting down.
	 *
	 * We will pass in the buffer only if there is data in it.  If
	 * there is no data, we will pass in a NULL.
	 */
	if (httpd->freecb != NULL) {
		isc_buffer_t *b = NULL;
946
		if (isc_buffer_length(&httpd->bodybuffer) > 0) {
947
			b = &httpd->bodybuffer;
948
949
			httpd->freecb(b, httpd->freecb_arg);
		}
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
		NOTICE("senddone free callback performed");
	}
	if (ISC_LINK_LINKED(&httpd->bodybuffer, link)) {
		ISC_LIST_UNLINK(sev->bufferlist, &httpd->bodybuffer, link);
		NOTICE("senddone body buffer unlinked");
	}

	if (sev->result != ISC_R_SUCCESS) {
		destroy_client(&httpd);
		goto out;
	}

	if ((httpd->flags & HTTPD_CLOSE) != 0) {
		destroy_client(&httpd);
		goto out;
	}

	ISC_HTTPD_SETRECV(httpd);

	NOTICE("senddone restarting recv on socket");

	reset_client(httpd);

	r.base = (unsigned char *)httpd->recvbuf;
	r.length = HTTP_RECVLEN - 1;
975
976
977
	/* check return code? */
	(void)isc_socket_recv(httpd->sock, &r, 1, task,
			      isc_httpd_recvdone, httpd);
978
979
980
981
982
983
984

out:
	isc_event_free(&ev);
	EXIT("senddone");
}

static void
Evan Hunt's avatar
Evan Hunt committed
985
reset_client(isc_httpd_t *httpd) {
986
987
988
989
990
991
992
993
994
995
	/*
	 * Catch errors here.  We MUST be in RECV mode, and we MUST NOT have
	 * any outstanding buffers.  If we have buffers, we have a leak.
	 */
	INSIST(ISC_HTTPD_ISRECV(httpd));
	INSIST(!ISC_LINK_LINKED(&httpd->headerbuffer, link));
	INSIST(!ISC_LINK_LINKED(&httpd->bodybuffer, link));

	httpd->recvbuf[0] = 0;
	httpd->recvlen = 0;
Evan Hunt's avatar
Evan Hunt committed
996
	httpd->headers = NULL;
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
	httpd->method = ISC_HTTPD_METHODUNKNOWN;
	httpd->url = NULL;
	httpd->querystring = NULL;
	httpd->protocol = NULL;
	httpd->flags = 0;

	isc_buffer_clear(&httpd->headerbuffer);
	isc_buffer_invalidate(&httpd->bodybuffer);
}

isc_result_t
isc_httpdmgr_addurl(isc_httpdmgr_t *httpdmgr, const char *url,
		    isc_httpdaction_t *func, void *arg)
Evan Hunt's avatar
Evan Hunt committed
1010
1011
1012
1013
1014
1015
1016
1017
{
	return (isc_httpdmgr_addurl2(httpdmgr, url, ISC_FALSE, func, arg));
}

isc_result_t
isc_httpdmgr_addurl2(isc_httpdmgr_t *httpdmgr, const char *url,
		     isc_boolean_t isstatic,
		     isc_httpdaction_t *func, void *arg)
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
{
	isc_httpdurl_t *item;

	if (url == NULL) {
		httpdmgr->render_404 = func;
		return (ISC_R_SUCCESS);
	}

	item = isc_mem_get(httpdmgr->mctx, sizeof(isc_httpdurl_t));
	if (item == NULL)
		return (ISC_R_NOMEMORY);

	item->url = isc_mem_strdup(httpdmgr->mctx, url);
	if (item->url == NULL) {
		isc_mem_put(httpdmgr->mctx, item, sizeof(isc_httpdurl_t));
		return (ISC_R_NOMEMORY);
	}

	item->action = func;
	item->action_arg = arg;
Evan Hunt's avatar
Evan Hunt committed
1038
1039
1040
	item->isstatic = isstatic;
	isc_time_now(&item->loadtime);

1041
1042
1043
1044
1045
	ISC_LINK_INIT(item, link);
	ISC_LIST_APPEND(httpdmgr->urls, item, link);

	return (ISC_R_SUCCESS);
}