summaryrefslogtreecommitdiff
path: root/src/httperr.c
blob: 461d6f587ae9cfd25ea1cdb59b613138125ff624 (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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
#include "fileserv.h"
#include <fcntl.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#include "wordsplit.h"

char *error_dir;

#define ERRFILETMPL "XXX.html.var"

void
lang_var_list_free(LANG_VAR_LIST *lst)
{
	LANG_VAR *p;
	while ((p = STAILQ_FIRST(lst))) {
		STAILQ_REMOVE_HEAD(lst, next);
		free(p);
	}
}

typedef struct errdoc_file {
	int fd;                      /* File descriptor */

	char *buf_base;              /* Buffer memory area */
	size_t buf_size;             /* Size of allocated memory */
	char *buf_ptr;               /* Current read position */ 
	char *buf_end;               /* End of filled area */
	
	char *file_name;             /* Name of the file */
	unsigned line_no;            /* Number of line being processed */
	LANG_VAR_LIST vlist;         /* List of language variants (being
					built) */
	unsigned body_start_line;    /* Number of line where the Body:
					header was lastly encountered */
	int error;                   /* Error status */
	int eof;                     /* End-of-file status */
} ERRDOC_FILE;

#define ERRDOC_BUFFER_SIZE 1024

static ERRDOC_FILE *
errdoc_open(char const *file_name)
{
	int fd;
	ERRDOC_FILE *ef;
	
	fd = open(file_name, O_RDONLY);
	if (fd == -1) {
		error("can't open file %s: %s", file_name, strerror(errno));
		return NULL;
	}

	ef = calloc(1, sizeof(*ef) + strlen(file_name) + 1);
	if (!ef) {
		alloc_warn();
		close(fd);
		return NULL;
	}
	ef->buf_base = malloc(ERRDOC_BUFFER_SIZE);
	if (!ef->buf_base) {
		alloc_warn();
		close(fd);
		free(ef);
		return NULL;
	}

	ef->fd = fd;
	ef->buf_size = ERRDOC_BUFFER_SIZE;
	ef->buf_ptr = ef->buf_base;
	ef->buf_end = ef->buf_base;

	ef->file_name = (char*)(ef + 1);
	strcpy(ef->file_name, file_name);
	ef->line_no = 0;
	ef->error = 0;
	ef->eof = 0;
	STAILQ_INIT(&ef->vlist);
	return ef;
}

static void
errdoc_close(ERRDOC_FILE *ef)
{
	if (!ef)
		return;
	close(ef->fd);
	free(ef->buf_base);
	lang_var_list_free(&ef->vlist);
	free(ef);
}

static inline int
errdoc_eof(ERRDOC_FILE *ef)
{
	return ef->eof;
}

static inline int
errdoc_error(ERRDOC_FILE *ef)
{
	return ef->error;
}


static inline int
errdoc_seterr(ERRDOC_FILE *ef, int code)
{
	return ef->error = code;
}

static inline size_t
errdoc_buf_pos(ERRDOC_FILE *ef)
{
	return ef->buf_ptr - ef->buf_base;
}

/* Returns number of unread characters in the buffer */
static inline size_t
errdoc_buf_unread(ERRDOC_FILE *ef)
{
	return ef->buf_end - ef->buf_ptr;
}

static inline size_t
errdoc_buf_nread(ERRDOC_FILE *ef)
{
	return ef->buf_end - ef->buf_base;
}

/* Returns number of bytes available for reading */
static inline size_t
errdoc_buf_avail(ERRDOC_FILE *ef)
{
	return ef->buf_size - errdoc_buf_unread(ef);
}

static int
errdoc_fill(ERRDOC_FILE *ef)
{
	ssize_t n_read;
	size_t n_unread;

	if (errdoc_eof(ef))
		return -1;
	
	n_unread = errdoc_buf_unread(ef);
	if (n_unread > 0 && ef->buf_ptr > ef->buf_base) {
		memmove(ef->buf_base, ef->buf_ptr, n_unread);
		ef->buf_ptr = ef->buf_base;
		ef->buf_end = ef->buf_base + n_unread;
	}
	if (n_unread == ef->buf_size) {
		char *new_base = n2realloc(ef->buf_base, &ef->buf_size, 1);
		if (!new_base) {
			alloc_warn();
			return errdoc_seterr(ef, ENOMEM);
		}
		ef->buf_ptr = new_base + (ef->buf_ptr - ef->buf_base);
		ef->buf_end = new_base + (ef->buf_end - ef->buf_base);
		ef->buf_base = new_base;
	}
	n_read = read(ef->fd, ef->buf_end, errdoc_buf_avail(ef));
	if (n_read == 0) {
		ef->eof = 1;
		return -1;
	} else if (n_read < 0) {
		errdoc_seterr(ef, errno);
		error("error reading from %s: %s",
		      ef->file_name, strerror(errno));
		return -1;
	}
	ef->buf_end += n_read;
	return 0;
}

static int
errdoc_gets(ERRDOC_FILE *ef, char const **ptr, size_t *psize)
{
	char *p;
	
	while ((p = memchr(ef->buf_ptr, '\n', errdoc_buf_unread(ef))) == NULL)
		if (errdoc_fill(ef))
			return -1;

	*ptr = ef->buf_ptr;
	*psize = p - ef->buf_ptr + 1;
	
	ef->buf_ptr = p + 1;
	ef->line_no++;
	return 0;
}

static inline off_t
errdoc_tell(ERRDOC_FILE *ef)
{
	off_t n;

	n = lseek(ef->fd, 0, SEEK_CUR);
	if (n == -1) {
		errdoc_seterr(ef, errno);
		error("lseek error in file %s: %s",
		      ef->file_name, strerror(errno));
		return -1;
	}
/*	return n - errdoc_buf_nread(ef) + errdoc_buf_pos(ef);*/
	return n + ef->buf_ptr - ef->buf_end;
}

static int
errdoc_seek(ERRDOC_FILE *ef, off_t off)
{
	off_t n;

	n = lseek(ef->fd, off, SEEK_SET);
	if (n == -1) {
		errdoc_seterr(ef, errno);
		error("lseek error in file %s: %s",
		      ef->file_name, strerror(errno));
		return -1;
	}
	ef->eof = 0;
	ef->buf_ptr = ef->buf_end = ef->buf_base;
	return 0;
}	

static int
ishdr(char const *h, char const *s, size_t n)
{
	while (*h && n--) {
		if (tolower(*h++) != tolower(*s++))
			return 0;
	}
	return (n && *s == ':');
}

static inline int
isws(int c)
{
	return c == ' ' || c == '\t';
}

static int
isempty(char const *s, size_t n)
{
	while (n--)
		if (!(isws(*s) || *s == '\n'))
			return 0;
	return 1;
}

static int
errdoc_getbody(ERRDOC_FILE *ef, LANG_VAR *lv, char *delim)
{
	char const *s;
	size_t n;
	
	while (errdoc_gets(ef, &s, &n) == 0) {
		if (memcmp(s, delim, n) == 0) {
			lv->body_size = errdoc_tell(ef) - n - lv->body_start;
			return 0;
		}
	}
	error("%s:%u: body not terminated", ef->file_name,
	      ef->body_start_line);
	return -1;
}

#define HDR_BODY "Body"

static int
errdoc_gethdr(ERRDOC_FILE *ef, LANG_VAR *lv)
{
	int res;
	char const *s;
	size_t n;
	char *delim;

	do {
		if (errdoc_gets(ef, &s, &n)) {
			error("%s:%u: expected \"Body:\"",
			      ef->file_name, ef->line_no);
			return -1;
		}
	} while (!ishdr(HDR_BODY, s, n));
	
	s += sizeof(HDR_BODY);
	n -= sizeof(HDR_BODY);
	delim = malloc(n + 1);
	if (!delim) {
		alloc_warn();
		return -1;
	}
	memcpy(delim, s, n);
	delim[n] = 0;
	ef->body_start_line = ef->line_no;
	lv->body_start = errdoc_tell(ef);
	res = errdoc_getbody(ef, lv, delim);
	free(delim);
	return res;
}

static int
errdoc_getlang(ERRDOC_FILE *ef)
{
	LANG_VAR *lv;
	char const *s;
	size_t n;
	off_t off;

	do {
		if (errdoc_gets(ef, &s, &n))
			return -1;
	} while (isempty(s, n));
	
	if (!ishdr(MHD_HTTP_HEADER_CONTENT_LANGUAGE, s, n)) {
		error("%s:%u: expected \""
		      MHD_HTTP_HEADER_CONTENT_LANGUAGE
		      "\"",
		      ef->file_name, ef->line_no);
		return errdoc_seterr(ef, EINVAL);
	}
	off = errdoc_tell(ef) - n;
	s += sizeof(MHD_HTTP_HEADER_CONTENT_LANGUAGE);
	n -= sizeof(MHD_HTTP_HEADER_CONTENT_LANGUAGE) + 1;
	while (n && isws(*s)) {
		s++;
		n--;
	}
	while (n && isws(s[n-1]))
		n--;
	if (n == 0) {
		error("%s:%u: syntax error",
		      ef->file_name, ef->line_no);
		return errdoc_seterr(ef, EINVAL);
	}
	lv = calloc(1, sizeof(*lv) + n + 1);
	lv->lang = (char*)(lv + 1);
	memcpy(lv->lang, s, n);
	lv->lang[n] = 0;
	lv->header_start = off;
	STAILQ_INSERT_TAIL(&ef->vlist, lv, next);
	return errdoc_gethdr(ef, lv);
}
	
static ERRDOC_FILE *
errdoc_parse(char const *file_name)
{
	ERRDOC_FILE *ef;

	ef = errdoc_open(file_name);
	if (ef) {
		while (errdoc_getlang(ef) == 0)
			;

		if (errdoc_error(ef)) {
			errdoc_close(ef);
			ef = NULL;
		}
	}
	return ef;
}

/* HTTP error definitions */
static struct http_error_def {
	int status;          /* Status code */
	char const *name;    /* Internal error identifier */
	char const *title;   /* Short error description, suitable for title */
	char const *doc;     /* Full error text */
} http_error_def[] = {
	{ MHD_HTTP_FORBIDDEN,
	  "HTTP_FORBIDDEN",
	  "Forbidden",
	  "You don't have permission to access \"$URL\"."
	  "It is either read-protected or not readable by the server."
	},
	{ MHD_HTTP_NOT_FOUND,
	  "HTTP_NOT_FOUND",
	  "Not Found",
	  "The requested URL $URL was not found on this server."
	},
	{ MHD_HTTP_METHOD_NOT_ALLOWED,
	  "HTTP_METHOD_NOT_ALLOWED",
	  "Method not allowed",
	  "The method $METHOD is not allowed for the requested URL \"$URL\"."
	},
	{ MHD_HTTP_INTERNAL_SERVER_ERROR,
	  "HTTP_INTERNAL_SERVER_ERROR",
	  "Internal server error",
	  "The server encountered an internal error and was unable"
	  " to complete your request."
	},
	{ MHD_HTTP_NOT_IMPLEMENTED,
	  "HTTP_NOT_IMPLEMENTED",
	  "Not implemented",
	  "The server does not support the action requested by the browser."
	},
	{ MHD_HTTP_SERVICE_UNAVAILABLE,
	  "HTTP_SERVICE_UNAVAILABLE",
	  "Service unavailable",
	  "The server is temporarily unable to service your"
	  " request due to maintenance downtime or capacity"
	  " problems. Please try again later."
	},
	{ 0 }
};

static struct http_error_def *
find_error_def(int status)
{
	struct http_error_def *dp;
	for (dp = http_error_def; dp->status; dp++)
		if (dp->status == status)
			return dp;
	return NULL;
}

static int
conn_getvar(char **ret, const char *var, size_t len, void *clos)
{
	struct MHD_Connection *conn = clos;
	char *copy;
	char const *value;
	
	copy = malloc(len + 1);
	if (!copy)
		return WRDSE_NOSPACE;
	memcpy(copy, var, len);
	copy[len] = 0;
	value = MHD_lookup_connection_value(conn, MHD_HEADER_KIND, copy);
	free(copy);
	if (!value)
		return WRDSE_UNDEF;
	*ret = strdup(value);
	return *ret ? WRDSE_OK : WRDSE_NOSPACE;
}

static char *
text_expand(char const *text, struct MHD_Connection *conn, char const **kvenv)
{
	struct wordsplit ws;
	char *retval;
	
	ws.ws_getvar = conn_getvar;
	ws.ws_closure = conn;
	ws.ws_env = kvenv;
	if (wordsplit(text, &ws,
		      WRDSF_NOCMD
		      | WRDSF_NOSPLIT
		      | WRDSF_GETVAR
		      | WRDSF_CLOSURE
		      | WRDSF_ENV
		      | WRDSF_ENV_KV)) {
		error("wordsplit: %s", wordsplit_strerror(&ws));
		return NULL;
	}
	retval = ws.ws_wordv[0];
	ws.ws_wordv[0] = NULL;
	wordsplit_free(&ws);
	return retval;
}

static char *
page_expand(char const *page,
	    struct MHD_Connection *conn,
	    char const *method,
	    char const *url,
	    struct http_error_def *def)
{
	enum {
		KV_URL = 0,
		VAL_URL,

		KV_STATUS,
		VAL_STATUS,

		KV_NAME,
		VAL_NAME,

		KV_METHOD,
		VAL_METHOD,

		last_expand_title = VAL_METHOD,
		
		KV_TITLE,
		VAL_TITLE,

		last_expand_doc = VAL_TITLE,
		
		KV_DOC,
		VAL_DOC,

		max_expand
	};

	char const *kvenv[max_expand+1];
	char statusstr[4];
	char *title;
	char *doc;
	char *retval;
	
	snprintf(statusstr, sizeof statusstr, "%3d", def->status);

	memset(kvenv, 0, sizeof kvenv);
	
	kvenv[KV_URL] = "URL";
	kvenv[VAL_URL] = url;
	kvenv[KV_STATUS] = "STATUS";
	kvenv[VAL_STATUS] = statusstr;
	kvenv[KV_NAME] = "NAME";
	kvenv[VAL_NAME] = def->name;
	kvenv[KV_METHOD] = "METHOD";
	kvenv[VAL_METHOD] = method;
	kvenv[last_expand_title+1] = NULL;

	title = text_expand(def->title, conn, kvenv);

	kvenv[KV_TITLE] = "TITLE";
	kvenv[VAL_TITLE] = title;
	kvenv[last_expand_doc+1] = NULL;

	doc = text_expand(def->doc, conn, kvenv);
	
	kvenv[KV_DOC] = "DOC";
	kvenv[VAL_DOC] = doc;
	kvenv[max_expand] = NULL;

	retval = text_expand(page, conn, kvenv);
	free(title);
	free(doc);

	return retval;
}

static char default_error_page[] = "\
<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\
<html><head>\
<title>$STATUS $TITLE</title>\
</head><body>\
<h1>$TITLE</h1>\
<p>$DOC</p>\
</body></html>\
";

static char double_error_page[] = "\
<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\
<html><head>\
<title>$STATUS $TITLE</title>\
</head><body>\
<h1>$TITLE</h1>\
<p>$DOC</p>\
<p>Additionally, an internal error occurred trying to display custom\
 error page.</p>\
</body></html>\
";

static struct MHD_Response *
http_default_error_response(struct MHD_Connection *conn,
			    char const *method,
			    char const *url,
			    struct http_error_def *def,
			    char const *template)
{
	char *page;
	struct MHD_Response *resp;
	
	page = page_expand(template, conn, method, url, def);
	if (page) {
		resp = MHD_create_response_from_buffer (strlen(page),
							page,
							MHD_RESPMEM_MUST_COPY);
		MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE,
					"text/html");
		free(page);
	} else {
		resp = MHD_create_response_from_buffer (0,
							NULL,
						MHD_RESPMEM_PERSISTENT);
	}
	return resp;
}

static struct MHD_Response *
err_from_var(struct MHD_Connection *conn, int status, char const *file)
{
	char const *acc;
	ERRDOC_FILE *ef;
	struct MHD_Response *res;
	LANG_VAR *lv;
	char const *s;
	size_t n;
	
	ef = errdoc_parse(file);

	if (!ef) 
		return NULL;

	acc = MHD_lookup_connection_value(conn,
					  MHD_HEADER_KIND,
					  MHD_HTTP_HEADER_ACCEPT_LANGUAGE);

	lv = select_language(&ef->vlist, acc);
	if (lv) {
		res = MHD_create_response_from_fd_at_offset64(lv->body_size,
							      ef->fd,
							      lv->body_start);
		errdoc_seek(ef, lv->header_start);
		while (errdoc_gets(ef, &s, &n) == 0
		       && errdoc_tell(ef) < lv->body_start) {
			char *p, *buf = malloc(n);
			if (!buf)
				break;
			n--;
			memcpy(buf, s, n);
			buf[n] = 0;
			p = strchr(buf, ':');
			if (!p)
				break;
			*p++ = 0;
			while (p < s + n && isws(*p))
				p++;

			MHD_add_response_header(res, buf, p);
			free(buf);
		}
	
		ef->fd = -1;
	} else
		res = NULL;
	
	errdoc_close(ef);
	
	return res;
}

static struct MHD_Response *
err_from_html(struct MHD_Connection *conn, int status, char const *file_name)
{
	int fd;
	struct stat st;
	struct MHD_Response *resp;
	
	fd = open(file_name, O_RDONLY);
	if (fd == -1) {
		error("can't open file %s: %s", file_name, strerror(errno));
		return NULL;
	}
	if (fstat(fd, &st)) {
		error("can't stat file %s: %s", file_name, strerror(errno));
		close(fd);
		return NULL;
	}
	resp = MHD_create_response_from_fd64(st.st_size, fd);
	MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE,
				"text/html");
	return resp;
}

typedef	struct MHD_Response *(*SUFFIX_HANDLER_FUNCTION)
	(struct MHD_Connection *, int, char const *);

static struct suffix_handler {
	char const *suffix;
	SUFFIX_HANDLER_FUNCTION handler;
} suffix_handler[] = {
	{ ".html", err_from_html },
	{ ".html.var", err_from_var },
	{ NULL }
};	

static struct MHD_Response *
handle_errdoc(struct MHD_Connection *conn, struct http_error_def *def)
{
	char const *basenames[3];
	char statstr[4];
	int i;
	struct suffix_handler const *sh;

	snprintf(statstr, sizeof(statstr), "%3d", def->status);

	basenames[0] = statstr;
	basenames[1] = def->name;
	basenames[2] = NULL;
	
	for (i = 0; basenames[i]; i++) {
		for (sh = suffix_handler; sh->suffix; sh++) {
			struct MHD_Response *resp = NULL;
			char *name = catfile_suf(error_dir,
						 basenames[i],
						 sh->suffix);
			if (access(name, R_OK) == 0)
				resp = sh->handler(conn, def->status, name);
			free(name);
			if (resp)
				return resp;
		}
	}
	return NULL;
}

int
http_error(struct MHD_Connection *conn,
	   char const *method, char const *url, int status)
{
	int ret;
	struct MHD_Response *resp = NULL;
	struct http_error_def *def;
	
	http_log(conn, method, url, status, NULL);
	def = find_error_def(status);
	if (def && error_dir) {
		resp = handle_errdoc(conn, def);
		if (!resp)
			resp = http_default_error_response(conn,
							   method,
							   url,
							   def,
							   double_error_page);
	} else
		resp = http_default_error_response(conn, method, url, def,
						   default_error_page);

	ret = MHD_queue_response(conn, status, resp);
	MHD_destroy_response(resp);
	return ret;
}

#ifdef TEST
#include <assert.h>
void
errdoc_test(char const *file, char const *acc)
{
	ERRDOC_FILE *ef;
	LANG_VAR *lv;
	FILE *fp;
	char *buf;

	ef = errdoc_parse(file);

	if (ef == NULL)
		exit(1);
	fp = fdopen(ef->fd, "r");
	assert(fp != NULL);
	ef->fd = -1;
	
	lv = select_language(&ef->vlist, acc);
	assert(fseek(fp, lv->body_start, SEEK_SET) == 0);
	buf = xmalloc(lv->body_size);
	assert(fread(buf, lv->body_size, 1, fp) == 1);
	fwrite(buf, lv->body_size, 1, stdout);

	free(buf);
	errdoc_close(ef);
	fclose(fp);
	
	exit(0);
}
#endif

Return to:

Send suggestions and report system problems to the System administrator.