[core] consolidate duplicated read-to-close code
[lighttpd.git] / src / mod_dirlisting.c
blobc881e94acef519c39a1e669173ec10c30866538b
1 #include "first.h"
3 #include "base.h"
4 #include "log.h"
5 #include "buffer.h"
7 #include "plugin.h"
9 #include "response.h"
10 #include "stat_cache.h"
12 #include <ctype.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <dirent.h>
16 #include <assert.h>
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <stdio.h>
20 #include <unistd.h>
21 #include <time.h>
23 /**
24 * this is a dirlisting for a lighttpd plugin
27 #ifdef HAVE_ATTR_ATTRIBUTES_H
28 #include <attr/attributes.h>
29 #endif
31 #ifdef HAVE_SYS_EXTATTR_H
32 #include <sys/extattr.h>
33 #endif
35 /* plugin config for all request/connections */
37 typedef struct {
38 #ifdef HAVE_PCRE_H
39 pcre *regex;
40 #endif
41 buffer *string;
42 } excludes;
44 typedef struct {
45 excludes **ptr;
47 size_t used;
48 size_t size;
49 } excludes_buffer;
51 typedef struct {
52 unsigned short dir_listing;
53 unsigned short hide_dot_files;
54 unsigned short hide_readme_file;
55 unsigned short encode_readme;
56 unsigned short hide_header_file;
57 unsigned short encode_header;
58 unsigned short auto_layout;
60 excludes_buffer *excludes;
62 buffer *show_readme;
63 buffer *show_header;
64 buffer *external_css;
65 buffer *external_js;
66 buffer *encoding;
67 buffer *set_footer;
68 } plugin_config;
70 typedef struct {
71 PLUGIN_DATA;
73 buffer *tmp_buf;
74 buffer *content_charset;
76 plugin_config **config_storage;
78 plugin_config conf;
79 } plugin_data;
81 static excludes_buffer *excludes_buffer_init(void) {
82 excludes_buffer *exb;
84 exb = calloc(1, sizeof(*exb));
86 return exb;
89 static int excludes_buffer_append(excludes_buffer *exb, buffer *string) {
90 #ifdef HAVE_PCRE_H
91 size_t i;
92 const char *errptr;
93 int erroff;
95 if (!string) return -1;
97 if (exb->size == 0) {
98 exb->size = 4;
99 exb->used = 0;
101 exb->ptr = malloc(exb->size * sizeof(*exb->ptr));
103 for(i = 0; i < exb->size ; i++) {
104 exb->ptr[i] = calloc(1, sizeof(**exb->ptr));
106 } else if (exb->used == exb->size) {
107 exb->size += 4;
109 exb->ptr = realloc(exb->ptr, exb->size * sizeof(*exb->ptr));
111 for(i = exb->used; i < exb->size; i++) {
112 exb->ptr[i] = calloc(1, sizeof(**exb->ptr));
117 if (NULL == (exb->ptr[exb->used]->regex = pcre_compile(string->ptr, 0,
118 &errptr, &erroff, NULL))) {
119 return -1;
122 exb->ptr[exb->used]->string = buffer_init();
123 buffer_copy_buffer(exb->ptr[exb->used]->string, string);
125 exb->used++;
127 return 0;
128 #else
129 UNUSED(exb);
130 UNUSED(string);
132 return -1;
133 #endif
136 static void excludes_buffer_free(excludes_buffer *exb) {
137 #ifdef HAVE_PCRE_H
138 size_t i;
140 for (i = 0; i < exb->size; i++) {
141 if (exb->ptr[i]->regex) pcre_free(exb->ptr[i]->regex);
142 if (exb->ptr[i]->string) buffer_free(exb->ptr[i]->string);
143 free(exb->ptr[i]);
146 if (exb->ptr) free(exb->ptr);
147 #endif
149 free(exb);
152 /* init the plugin data */
153 INIT_FUNC(mod_dirlisting_init) {
154 plugin_data *p;
156 p = calloc(1, sizeof(*p));
158 p->tmp_buf = buffer_init();
159 p->content_charset = buffer_init();
161 return p;
164 /* detroy the plugin data */
165 FREE_FUNC(mod_dirlisting_free) {
166 plugin_data *p = p_d;
168 UNUSED(srv);
170 if (!p) return HANDLER_GO_ON;
172 if (p->config_storage) {
173 size_t i;
174 for (i = 0; i < srv->config_context->used; i++) {
175 plugin_config *s = p->config_storage[i];
177 if (!s) continue;
179 excludes_buffer_free(s->excludes);
180 buffer_free(s->show_readme);
181 buffer_free(s->show_header);
182 buffer_free(s->external_css);
183 buffer_free(s->external_js);
184 buffer_free(s->encoding);
185 buffer_free(s->set_footer);
187 free(s);
189 free(p->config_storage);
192 buffer_free(p->tmp_buf);
193 buffer_free(p->content_charset);
195 free(p);
197 return HANDLER_GO_ON;
200 /* handle plugin config and check values */
202 #define CONFIG_EXCLUDE "dir-listing.exclude"
203 #define CONFIG_ACTIVATE "dir-listing.activate"
204 #define CONFIG_HIDE_DOTFILES "dir-listing.hide-dotfiles"
205 #define CONFIG_EXTERNAL_CSS "dir-listing.external-css"
206 #define CONFIG_EXTERNAL_JS "dir-listing.external-js"
207 #define CONFIG_ENCODING "dir-listing.encoding"
208 #define CONFIG_SHOW_README "dir-listing.show-readme"
209 #define CONFIG_HIDE_README_FILE "dir-listing.hide-readme-file"
210 #define CONFIG_SHOW_HEADER "dir-listing.show-header"
211 #define CONFIG_HIDE_HEADER_FILE "dir-listing.hide-header-file"
212 #define CONFIG_DIR_LISTING "server.dir-listing"
213 #define CONFIG_SET_FOOTER "dir-listing.set-footer"
214 #define CONFIG_ENCODE_README "dir-listing.encode-readme"
215 #define CONFIG_ENCODE_HEADER "dir-listing.encode-header"
216 #define CONFIG_AUTO_LAYOUT "dir-listing.auto-layout"
219 SETDEFAULTS_FUNC(mod_dirlisting_set_defaults) {
220 plugin_data *p = p_d;
221 size_t i = 0;
223 config_values_t cv[] = {
224 { CONFIG_EXCLUDE, NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
225 { CONFIG_ACTIVATE, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
226 { CONFIG_HIDE_DOTFILES, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
227 { CONFIG_EXTERNAL_CSS, NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 3 */
228 { CONFIG_ENCODING, NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 4 */
229 { CONFIG_SHOW_README, NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 5 */
230 { CONFIG_HIDE_README_FILE, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 6 */
231 { CONFIG_SHOW_HEADER, NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 7 */
232 { CONFIG_HIDE_HEADER_FILE, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 8 */
233 { CONFIG_DIR_LISTING, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 9 */
234 { CONFIG_SET_FOOTER, NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 10 */
235 { CONFIG_ENCODE_README, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 11 */
236 { CONFIG_ENCODE_HEADER, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 12 */
237 { CONFIG_AUTO_LAYOUT, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 13 */
238 { CONFIG_EXTERNAL_JS, NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 14 */
240 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
243 if (!p) return HANDLER_ERROR;
245 p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
247 for (i = 0; i < srv->config_context->used; i++) {
248 data_config const* config = (data_config const*)srv->config_context->data[i];
249 plugin_config *s;
250 data_unset *du_excludes;
252 s = calloc(1, sizeof(plugin_config));
253 s->excludes = excludes_buffer_init();
254 s->dir_listing = 0;
255 s->show_readme = buffer_init();
256 s->show_header = buffer_init();
257 s->external_css = buffer_init();
258 s->external_js = buffer_init();
259 s->hide_dot_files = 1;
260 s->hide_readme_file = 0;
261 s->hide_header_file = 0;
262 s->encode_readme = 1;
263 s->encode_header = 1;
264 s->auto_layout = 1;
266 s->encoding = buffer_init();
267 s->set_footer = buffer_init();
269 cv[0].destination = s->excludes;
270 cv[1].destination = &(s->dir_listing);
271 cv[2].destination = &(s->hide_dot_files);
272 cv[3].destination = s->external_css;
273 cv[4].destination = s->encoding;
274 cv[5].destination = s->show_readme;
275 cv[6].destination = &(s->hide_readme_file);
276 cv[7].destination = s->show_header;
277 cv[8].destination = &(s->hide_header_file);
278 cv[9].destination = &(s->dir_listing); /* old name */
279 cv[10].destination = s->set_footer;
280 cv[11].destination = &(s->encode_readme);
281 cv[12].destination = &(s->encode_header);
282 cv[13].destination = &(s->auto_layout);
283 cv[14].destination = s->external_js;
285 p->config_storage[i] = s;
287 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
288 return HANDLER_ERROR;
291 if (NULL != (du_excludes = array_get_element(config->value, CONFIG_EXCLUDE))) {
292 array *excludes_list;
293 size_t j;
295 if (du_excludes->type != TYPE_ARRAY) {
296 log_error_write(srv, __FILE__, __LINE__, "sss",
297 "unexpected type for key: ", CONFIG_EXCLUDE, "array of strings");
298 return HANDLER_ERROR;
301 excludes_list = ((data_array*)du_excludes)->value;
303 #ifndef HAVE_PCRE_H
304 if (excludes_list->used > 0) {
305 log_error_write(srv, __FILE__, __LINE__, "sss",
306 "pcre support is missing for: ", CONFIG_EXCLUDE, ", please install libpcre and the headers");
307 return HANDLER_ERROR;
309 #else
310 for (j = 0; j < excludes_list->used; j++) {
311 data_unset *du_exclude = excludes_list->data[j];
313 if (du_exclude->type != TYPE_STRING) {
314 log_error_write(srv, __FILE__, __LINE__, "sssbs",
315 "unexpected type for key: ", CONFIG_EXCLUDE, "[",
316 du_exclude->key, "](string)");
317 return HANDLER_ERROR;
320 if (0 != excludes_buffer_append(s->excludes, ((data_string*)(du_exclude))->value)) {
321 log_error_write(srv, __FILE__, __LINE__, "sb",
322 "pcre-compile failed for", ((data_string*)(du_exclude))->value);
323 return HANDLER_ERROR;
326 #endif
329 if (!buffer_string_is_empty(s->show_readme)) {
330 if (buffer_is_equal_string(s->show_readme, CONST_STR_LEN("enable"))) {
331 buffer_copy_string_len(s->show_readme, CONST_STR_LEN("README.txt"));
333 else if (buffer_is_equal_string(s->show_readme, CONST_STR_LEN("disable"))) {
334 buffer_string_set_length(s->show_readme, 0);
338 if (!buffer_string_is_empty(s->show_header)) {
339 if (buffer_is_equal_string(s->show_header, CONST_STR_LEN("enable"))) {
340 buffer_copy_string_len(s->show_header, CONST_STR_LEN("HEADER.txt"));
342 else if (buffer_is_equal_string(s->show_header, CONST_STR_LEN("disable"))) {
343 buffer_string_set_length(s->show_header, 0);
348 return HANDLER_GO_ON;
351 #define PATCH(x) \
352 p->conf.x = s->x;
353 static int mod_dirlisting_patch_connection(server *srv, connection *con, plugin_data *p) {
354 size_t i, j;
355 plugin_config *s = p->config_storage[0];
357 PATCH(dir_listing);
358 PATCH(external_css);
359 PATCH(external_js);
360 PATCH(hide_dot_files);
361 PATCH(encoding);
362 PATCH(show_readme);
363 PATCH(hide_readme_file);
364 PATCH(show_header);
365 PATCH(hide_header_file);
366 PATCH(excludes);
367 PATCH(set_footer);
368 PATCH(encode_readme);
369 PATCH(encode_header);
370 PATCH(auto_layout);
372 /* skip the first, the global context */
373 for (i = 1; i < srv->config_context->used; i++) {
374 data_config *dc = (data_config *)srv->config_context->data[i];
375 s = p->config_storage[i];
377 /* condition didn't match */
378 if (!config_check_cond(srv, con, dc)) continue;
380 /* merge config */
381 for (j = 0; j < dc->value->used; j++) {
382 data_unset *du = dc->value->data[j];
384 if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_ACTIVATE)) ||
385 buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_DIR_LISTING))) {
386 PATCH(dir_listing);
387 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_HIDE_DOTFILES))) {
388 PATCH(hide_dot_files);
389 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_EXTERNAL_CSS))) {
390 PATCH(external_css);
391 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_EXTERNAL_JS))) {
392 PATCH(external_js);
393 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_ENCODING))) {
394 PATCH(encoding);
395 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_SHOW_README))) {
396 PATCH(show_readme);
397 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_HIDE_README_FILE))) {
398 PATCH(hide_readme_file);
399 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_SHOW_HEADER))) {
400 PATCH(show_header);
401 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_HIDE_HEADER_FILE))) {
402 PATCH(hide_header_file);
403 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_SET_FOOTER))) {
404 PATCH(set_footer);
405 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_EXCLUDE))) {
406 PATCH(excludes);
407 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_ENCODE_README))) {
408 PATCH(encode_readme);
409 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_ENCODE_HEADER))) {
410 PATCH(encode_header);
411 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_AUTO_LAYOUT))) {
412 PATCH(auto_layout);
417 return 0;
419 #undef PATCH
421 typedef struct {
422 size_t namelen;
423 time_t mtime;
424 off_t size;
425 } dirls_entry_t;
427 typedef struct {
428 dirls_entry_t **ent;
429 size_t used;
430 size_t size;
431 } dirls_list_t;
433 #define DIRLIST_ENT_NAME(ent) ((char*)(ent) + sizeof(dirls_entry_t))
434 #define DIRLIST_BLOB_SIZE 16
436 /* simple combsort algorithm */
437 static void http_dirls_sort(dirls_entry_t **ent, int num) {
438 int gap = num;
439 int i, j;
440 int swapped;
441 dirls_entry_t *tmp;
443 do {
444 gap = (gap * 10) / 13;
445 if (gap == 9 || gap == 10)
446 gap = 11;
447 if (gap < 1)
448 gap = 1;
449 swapped = 0;
451 for (i = 0; i < num - gap; i++) {
452 j = i + gap;
453 if (strcmp(DIRLIST_ENT_NAME(ent[i]), DIRLIST_ENT_NAME(ent[j])) > 0) {
454 tmp = ent[i];
455 ent[i] = ent[j];
456 ent[j] = tmp;
457 swapped = 1;
461 } while (gap > 1 || swapped);
464 /* buffer must be able to hold "999.9K"
465 * conversion is simple but not perfect
467 static int http_list_directory_sizefmt(char *buf, size_t bufsz, off_t size) {
468 const char unit[] = " KMGTPE"; /* Kilo, Mega, Giga, Tera, Peta, Exa */
469 const char *u = unit; /* u will always increment at least once */
470 int remain;
471 size_t buflen;
473 if (size < 100)
474 size += 99;
475 if (size < 100)
476 size = 0;
478 while (1) {
479 remain = (int) size & 1023;
480 size >>= 10;
481 u++;
482 if ((size & (~0 ^ 1023)) == 0)
483 break;
486 remain /= 100;
487 if (remain > 9)
488 remain = 9;
489 if (size > 999) {
490 size = 0;
491 remain = 9;
492 u++;
495 li_itostrn(buf, bufsz, size);
496 buflen = strlen(buf);
497 if (buflen + 3 >= bufsz) return buflen;
498 buf[buflen+0] = '.';
499 buf[buflen+1] = remain + '0';
500 buf[buflen+2] = *u;
501 buf[buflen+3] = '\0';
503 return buflen + 3;
506 /* don't want to block when open()ing a fifo */
507 #if defined(O_NONBLOCK)
508 # define FIFO_NONBLOCK O_NONBLOCK
509 #else
510 # define FIFO_NONBLOCK 0
511 #endif
513 static void http_list_directory_include_file(buffer *out, buffer *path, const char *classname, int encode) {
514 int fd = open(path->ptr, O_RDONLY | FIFO_NONBLOCK);
515 ssize_t rd;
516 char buf[8192];
518 if (-1 == fd) return;
520 if (encode) {
521 buffer_append_string_len(out, CONST_STR_LEN("<pre class=\""));
522 buffer_append_string(out, classname);
523 buffer_append_string_len(out, CONST_STR_LEN("\">"));
526 while ((rd = read(fd, buf, sizeof(buf))) > 0) {
527 if (encode) {
528 buffer_append_string_encoded(out, buf, (size_t)rd, ENCODING_MINIMAL_XML);
529 } else {
530 buffer_append_string_len(out, buf, (size_t)rd);
533 close(fd);
535 if (encode) {
536 buffer_append_string_len(out, CONST_STR_LEN("</pre>"));
540 /* portions copied from mod_status
541 * modified and specialized for stable dirlist sorting by name */
542 static const char js_simple_table_resort[] = \
543 "var click_column;\n" \
544 "var name_column = 0;\n" \
545 "var date_column = 1;\n" \
546 "var size_column = 2;\n" \
547 "var type_column = 3;\n" \
548 "var prev_span = null;\n" \
549 "\n" \
550 "if (typeof(String.prototype.localeCompare) === 'undefined') {\n" \
551 " String.prototype.localeCompare = function(str, locale, options) {\n" \
552 " return ((this == str) ? 0 : ((this > str) ? 1 : -1));\n" \
553 " };\n" \
554 "}\n" \
555 "\n" \
556 "if (typeof(String.prototype.toLocaleUpperCase) === 'undefined') {\n" \
557 " String.prototype.toLocaleUpperCase = function() {\n" \
558 " return this.toUpperCase();\n" \
559 " };\n" \
560 "}\n" \
561 "\n" \
562 "function get_inner_text(el) {\n" \
563 " if((typeof el == 'string')||(typeof el == 'undefined'))\n" \
564 " return el;\n" \
565 " if(el.innerText)\n" \
566 " return el.innerText;\n" \
567 " else {\n" \
568 " var str = \"\";\n" \
569 " var cs = el.childNodes;\n" \
570 " var l = cs.length;\n" \
571 " for (i=0;i<l;i++) {\n" \
572 " if (cs[i].nodeType==1) str += get_inner_text(cs[i]);\n" \
573 " else if (cs[i].nodeType==3) str += cs[i].nodeValue;\n" \
574 " }\n" \
575 " }\n" \
576 " return str;\n" \
577 "}\n" \
578 "\n" \
579 "function isdigit(c) {\n" \
580 " return (c >= '0' && c <= '9');\n" \
581 "}\n" \
582 "\n" \
583 "function unit_multiplier(unit) {\n" \
584 " return (unit=='K') ? 1000\n" \
585 " : (unit=='M') ? 1000000\n" \
586 " : (unit=='G') ? 1000000000\n" \
587 " : (unit=='T') ? 1000000000000\n" \
588 " : (unit=='P') ? 1000000000000000\n" \
589 " : (unit=='E') ? 1000000000000000000 : 1;\n" \
590 "}\n" \
591 "\n" \
592 "function sortfn_then_by_name(a,b,sort_column) {\n" \
593 " if (sort_column == name_column || sort_column == type_column) {\n" \
594 " var ad = (a.cells[type_column].innerHTML === 'Directory');\n" \
595 " var bd = (b.cells[type_column].innerHTML === 'Directory');\n" \
596 " if (ad != bd) return (ad ? -1 : 1);\n" \
597 " }\n" \
598 " var at = get_inner_text(a.cells[sort_column]);\n" \
599 " var bt = get_inner_text(b.cells[sort_column]);\n" \
600 " var cmp;\n" \
601 " if (a.cells[sort_column].className == 'int') {\n" \
602 " cmp = parseInt(at)-parseInt(bt);\n" \
603 " } else if (sort_column == date_column) {\n" \
604 " cmp = Date.parse(at.replace(/-/g, '/'))\n" \
605 " - Date.parse(bt.replace(/-/g, '/'));\n" \
606 " var ad = isdigit(at.substr(0,1));\n" \
607 " var bd = isdigit(bt.substr(0,1));\n" \
608 " if (ad != bd) return (!ad ? -1 : 1);\n" \
609 " } else if (sort_column == size_column) {\n" \
610 " var ai = parseInt(at, 10) * unit_multiplier(at.substr(-1,1));\n" \
611 " var bi = parseInt(bt, 10) * unit_multiplier(bt.substr(-1,1));\n" \
612 " if (at.substr(0,1) == '-') ai = -1;\n" \
613 " if (bt.substr(0,1) == '-') bi = -1;\n" \
614 " cmp = ai - bi;\n" \
615 " } else {\n" \
616 " cmp = at.toLocaleUpperCase().localeCompare(bt.toLocaleUpperCase());\n" \
617 " if (0 != cmp) return cmp;\n" \
618 " cmp = at.localeCompare(bt);\n" \
619 " }\n" \
620 " if (0 != cmp || sort_column == name_column) return cmp;\n" \
621 " return sortfn_then_by_name(a,b,name_column);\n" \
622 "}\n" \
623 "\n" \
624 "function sortfn(a,b) {\n" \
625 " return sortfn_then_by_name(a,b,click_column);\n" \
626 "}\n" \
627 "\n" \
628 "function resort(lnk) {\n" \
629 " var span = lnk.childNodes[1];\n" \
630 " var table = lnk.parentNode.parentNode.parentNode.parentNode;\n" \
631 " var rows = new Array();\n" \
632 " for (j=1;j<table.rows.length;j++)\n" \
633 " rows[j-1] = table.rows[j];\n" \
634 " click_column = lnk.parentNode.cellIndex;\n" \
635 " rows.sort(sortfn);\n" \
636 "\n" \
637 " if (prev_span != null) prev_span.innerHTML = '';\n" \
638 " if (span.getAttribute('sortdir')=='down') {\n" \
639 " span.innerHTML = '&uarr;';\n" \
640 " span.setAttribute('sortdir','up');\n" \
641 " rows.reverse();\n" \
642 " } else {\n" \
643 " span.innerHTML = '&darr;';\n" \
644 " span.setAttribute('sortdir','down');\n" \
645 " }\n" \
646 " for (i=0;i<rows.length;i++)\n" \
647 " table.tBodies[0].appendChild(rows[i]);\n" \
648 " prev_span = span;\n" \
649 "}\n";
651 /* portions copied from mod_dirlist (lighttpd2) */
652 static const char js_simple_table_init_sort[] = \
653 "\n" \
654 "function init_sort(init_sort_column, ascending) {\n" \
655 " var tables = document.getElementsByTagName(\"table\");\n" \
656 " for (var i = 0; i < tables.length; i++) {\n" \
657 " var table = tables[i];\n" \
658 " //var c = table.getAttribute(\"class\")\n" \
659 " //if (-1 != c.split(\" \").indexOf(\"sort\")) {\n" \
660 " var row = table.rows[0].cells;\n" \
661 " for (var j = 0; j < row.length; j++) {\n" \
662 " var n = row[j];\n" \
663 " if (n.childNodes.length == 1 && n.childNodes[0].nodeType == 3) {\n" \
664 " var link = document.createElement(\"a\");\n" \
665 " var title = n.childNodes[0].nodeValue.replace(/:$/, \"\");\n" \
666 " link.appendChild(document.createTextNode(title));\n" \
667 " link.setAttribute(\"href\", \"#\");\n" \
668 " link.setAttribute(\"class\", \"sortheader\");\n" \
669 " link.setAttribute(\"onclick\", \"resort(this);return false;\");\n" \
670 " var arrow = document.createElement(\"span\");\n" \
671 " arrow.setAttribute(\"class\", \"sortarrow\");\n" \
672 " arrow.appendChild(document.createTextNode(\":\"));\n" \
673 " link.appendChild(arrow)\n" \
674 " n.replaceChild(link, n.firstChild);\n" \
675 " }\n" \
676 " }\n" \
677 " var lnk = row[init_sort_column].firstChild;\n" \
678 " if (ascending) {\n" \
679 " var span = lnk.childNodes[1];\n" \
680 " span.setAttribute('sortdir','down');\n" \
681 " }\n" \
682 " resort(lnk);\n" \
683 " //}\n" \
684 " }\n" \
685 "}\n";
687 static void http_dirlist_append_js_table_resort (buffer *b, connection *con) {
688 char col = '0';
689 char ascending = '0';
690 if (!buffer_string_is_empty(con->uri.query)) {
691 const char *qs = con->uri.query->ptr;
692 do {
693 if (qs[0] == 'C' && qs[1] == '=') {
694 switch (qs[2]) {
695 case 'N': col = '0'; break;
696 case 'M': col = '1'; break;
697 case 'S': col = '2'; break;
698 case 'T':
699 case 'D': col = '3'; break;
700 default: break;
703 else if (qs[0] == 'O' && qs[1] == '=') {
704 switch (qs[2]) {
705 case 'A': ascending = '1'; break;
706 case 'D': ascending = '0'; break;
707 default: break;
710 } while ((qs = strchr(qs, '&')) && *++qs);
713 buffer_append_string_len(b, CONST_STR_LEN("\n<script type=\"text/javascript\">\n// <!--\n\n"));
714 buffer_append_string_len(b, js_simple_table_resort, sizeof(js_simple_table_resort)-1);
715 buffer_append_string_len(b, js_simple_table_init_sort, sizeof(js_simple_table_init_sort)-1);
716 buffer_append_string_len(b, CONST_STR_LEN("\ninit_sort("));
717 buffer_append_string_len(b, &col, 1);
718 buffer_append_string_len(b, CONST_STR_LEN(", "));
719 buffer_append_string_len(b, &ascending, 1);
720 buffer_append_string_len(b, CONST_STR_LEN(");\n\n// -->\n</script>\n\n"));
723 static void http_list_directory_header(server *srv, connection *con, plugin_data *p, buffer *out) {
724 UNUSED(srv);
726 if (p->conf.auto_layout) {
727 buffer_append_string_len(out, CONST_STR_LEN(
728 "<!DOCTYPE html>\n"
729 "<html>\n"
730 "<head>\n"
732 if (!buffer_string_is_empty(p->conf.encoding)) {
733 buffer_append_string_len(out, CONST_STR_LEN("<meta charset=\""));
734 buffer_append_string_buffer(out, p->conf.encoding);
735 buffer_append_string_len(out, CONST_STR_LEN("\">\n"));
737 buffer_append_string_len(out, CONST_STR_LEN("<title>Index of "));
738 buffer_append_string_encoded(out, CONST_BUF_LEN(con->uri.path), ENCODING_MINIMAL_XML);
739 buffer_append_string_len(out, CONST_STR_LEN("</title>\n"));
741 if (!buffer_string_is_empty(p->conf.external_css)) {
742 buffer_append_string_len(out, CONST_STR_LEN("<meta name=\"viewport\" content=\"initial-scale=1\">"));
743 buffer_append_string_len(out, CONST_STR_LEN("<link rel=\"stylesheet\" type=\"text/css\" href=\""));
744 buffer_append_string_buffer(out, p->conf.external_css);
745 buffer_append_string_len(out, CONST_STR_LEN("\">\n"));
746 } else {
747 buffer_append_string_len(out, CONST_STR_LEN(
748 "<style type=\"text/css\">\n"
749 "a, a:active {text-decoration: none; color: blue;}\n"
750 "a:visited {color: #48468F;}\n"
751 "a:hover, a:focus {text-decoration: underline; color: red;}\n"
752 "body {background-color: #F5F5F5;}\n"
753 "h2 {margin-bottom: 12px;}\n"
754 "table {margin-left: 12px;}\n"
755 "th, td {"
756 " font: 90% monospace;"
757 " text-align: left;"
758 "}\n"
759 "th {"
760 " font-weight: bold;"
761 " padding-right: 14px;"
762 " padding-bottom: 3px;"
763 "}\n"
764 "td {padding-right: 14px;}\n"
765 "td.s, th.s {text-align: right;}\n"
766 "div.list {"
767 " background-color: white;"
768 " border-top: 1px solid #646464;"
769 " border-bottom: 1px solid #646464;"
770 " padding-top: 10px;"
771 " padding-bottom: 14px;"
772 "}\n"
773 "div.foot {"
774 " font: 90% monospace;"
775 " color: #787878;"
776 " padding-top: 4px;"
777 "}\n"
778 "</style>\n"
782 buffer_append_string_len(out, CONST_STR_LEN("</head>\n<body>\n"));
785 if (!buffer_string_is_empty(p->conf.show_header)) {
786 /* if we have a HEADER file, display it in <pre class="header"></pre> */
788 buffer_copy_buffer(p->tmp_buf, con->physical.path);
789 buffer_append_slash(p->tmp_buf);
790 buffer_append_string_buffer(p->tmp_buf, p->conf.show_header);
792 http_list_directory_include_file(out, p->tmp_buf, "header", p->conf.encode_header);
795 buffer_append_string_len(out, CONST_STR_LEN("<h2>Index of "));
796 buffer_append_string_encoded(out, CONST_BUF_LEN(con->uri.path), ENCODING_MINIMAL_XML);
797 buffer_append_string_len(out, CONST_STR_LEN(
798 "</h2>\n"
799 "<div class=\"list\">\n"
800 "<table summary=\"Directory Listing\" cellpadding=\"0\" cellspacing=\"0\">\n"
801 "<thead>"
802 "<tr>"
803 "<th class=\"n\">Name</th>"
804 "<th class=\"m\">Last Modified</th>"
805 "<th class=\"s\">Size</th>"
806 "<th class=\"t\">Type</th>"
807 "</tr>"
808 "</thead>\n"
809 "<tbody>\n"
810 "<tr class=\"d\">"
811 "<td class=\"n\"><a href=\"../\">..</a>/</td>"
812 "<td class=\"m\">&nbsp;</td>"
813 "<td class=\"s\">- &nbsp;</td>"
814 "<td class=\"t\">Directory</td>"
815 "</tr>\n"
819 static void http_list_directory_footer(server *srv, connection *con, plugin_data *p, buffer *out) {
820 UNUSED(srv);
822 buffer_append_string_len(out, CONST_STR_LEN(
823 "</tbody>\n"
824 "</table>\n"
825 "</div>\n"
828 if (!buffer_string_is_empty(p->conf.show_readme)) {
829 /* if we have a README file, display it in <pre class="readme"></pre> */
831 buffer_copy_buffer(p->tmp_buf, con->physical.path);
832 buffer_append_slash(p->tmp_buf);
833 buffer_append_string_buffer(p->tmp_buf, p->conf.show_readme);
835 http_list_directory_include_file(out, p->tmp_buf, "readme", p->conf.encode_readme);
838 if(p->conf.auto_layout) {
840 buffer_append_string_len(out, CONST_STR_LEN(
841 "<div class=\"foot\">"
844 if (!buffer_string_is_empty(p->conf.set_footer)) {
845 buffer_append_string_buffer(out, p->conf.set_footer);
846 } else {
847 buffer_append_string_buffer(out, con->conf.server_tag);
850 buffer_append_string_len(out, CONST_STR_LEN(
851 "</div>\n"
854 if (!buffer_string_is_empty(p->conf.external_js)) {
855 buffer_append_string_len(out, CONST_STR_LEN("<script type=\"text/javascript\" src=\""));
856 buffer_append_string_buffer(out, p->conf.external_js);
857 buffer_append_string_len(out, CONST_STR_LEN("\"></script>\n"));
858 } else if (buffer_is_empty(p->conf.external_js)) {
859 http_dirlist_append_js_table_resort(out, con);
862 buffer_append_string_len(out, CONST_STR_LEN(
863 "</body>\n"
864 "</html>\n"
869 static int http_list_directory(server *srv, connection *con, plugin_data *p, buffer *dir) {
870 DIR *dp;
871 buffer *out;
872 struct dirent *dent;
873 struct stat st;
874 char *path, *path_file;
875 size_t i;
876 int hide_dotfiles = p->conf.hide_dot_files;
877 dirls_list_t dirs, files, *list;
878 dirls_entry_t *tmp;
879 char sizebuf[sizeof("999.9K")];
880 char datebuf[sizeof("2005-Jan-01 22:23:24")];
881 size_t k;
882 const char *content_type;
883 long name_max;
884 #if defined(HAVE_XATTR) || defined(HAVE_EXTATTR)
885 char attrval[128];
886 int attrlen;
887 #endif
888 #ifdef HAVE_LOCALTIME_R
889 struct tm tm;
890 #endif
892 if (buffer_string_is_empty(dir)) return -1;
894 i = buffer_string_length(dir);
896 #ifdef HAVE_PATHCONF
897 if (0 >= (name_max = pathconf(dir->ptr, _PC_NAME_MAX))) {
898 /* some broken fs (fuse) return 0 instead of -1 */
899 #ifdef NAME_MAX
900 name_max = NAME_MAX;
901 #else
902 name_max = 255; /* stupid default */
903 #endif
905 #elif defined __WIN32
906 name_max = FILENAME_MAX;
907 #else
908 name_max = NAME_MAX;
909 #endif
911 path = malloc(i + name_max + 1);
912 force_assert(NULL != path);
913 memcpy(path, dir->ptr, i+1);
914 path_file = path + i;
916 if (NULL == (dp = opendir(path))) {
917 log_error_write(srv, __FILE__, __LINE__, "sbs",
918 "opendir failed:", dir, strerror(errno));
920 free(path);
921 return -1;
924 dirs.ent = (dirls_entry_t**) malloc(sizeof(dirls_entry_t*) * DIRLIST_BLOB_SIZE);
925 force_assert(dirs.ent);
926 dirs.size = DIRLIST_BLOB_SIZE;
927 dirs.used = 0;
928 files.ent = (dirls_entry_t**) malloc(sizeof(dirls_entry_t*) * DIRLIST_BLOB_SIZE);
929 force_assert(files.ent);
930 files.size = DIRLIST_BLOB_SIZE;
931 files.used = 0;
933 while ((dent = readdir(dp)) != NULL) {
934 unsigned short exclude_match = 0;
936 if (dent->d_name[0] == '.') {
937 if (hide_dotfiles)
938 continue;
939 if (dent->d_name[1] == '\0')
940 continue;
941 if (dent->d_name[1] == '.' && dent->d_name[2] == '\0')
942 continue;
945 if (p->conf.hide_readme_file && !buffer_string_is_empty(p->conf.show_readme)) {
946 if (strcmp(dent->d_name, p->conf.show_readme->ptr) == 0)
947 continue;
949 if (p->conf.hide_header_file && !buffer_string_is_empty(p->conf.show_header)) {
950 if (strcmp(dent->d_name, p->conf.show_header->ptr) == 0)
951 continue;
954 /* compare d_name against excludes array
955 * elements, skipping any that match.
957 #ifdef HAVE_PCRE_H
958 for(i = 0; i < p->conf.excludes->used; i++) {
959 int n;
960 #define N 10
961 int ovec[N * 3];
962 pcre *regex = p->conf.excludes->ptr[i]->regex;
964 if ((n = pcre_exec(regex, NULL, dent->d_name,
965 strlen(dent->d_name), 0, 0, ovec, 3 * N)) < 0) {
966 if (n != PCRE_ERROR_NOMATCH) {
967 log_error_write(srv, __FILE__, __LINE__, "sd",
968 "execution error while matching:", n);
970 /* aborting would require a lot of manual cleanup here.
971 * skip instead (to not leak names that break pcre matching)
973 exclude_match = 1;
974 break;
977 else {
978 exclude_match = 1;
979 break;
983 if (exclude_match) {
984 continue;
986 #endif
988 i = strlen(dent->d_name);
990 /* NOTE: the manual says, d_name is never more than NAME_MAX
991 * so this should actually not be a buffer-overflow-risk
993 if (i > (size_t)name_max) continue;
995 memcpy(path_file, dent->d_name, i + 1);
996 if (stat(path, &st) != 0)
997 continue;
999 list = &files;
1000 if (S_ISDIR(st.st_mode))
1001 list = &dirs;
1003 if (list->used == list->size) {
1004 list->size += DIRLIST_BLOB_SIZE;
1005 list->ent = (dirls_entry_t**) realloc(list->ent, sizeof(dirls_entry_t*) * list->size);
1006 force_assert(list->ent);
1009 tmp = (dirls_entry_t*) malloc(sizeof(dirls_entry_t) + 1 + i);
1010 tmp->mtime = st.st_mtime;
1011 tmp->size = st.st_size;
1012 tmp->namelen = i;
1013 memcpy(DIRLIST_ENT_NAME(tmp), dent->d_name, i + 1);
1015 list->ent[list->used++] = tmp;
1017 closedir(dp);
1019 if (dirs.used) http_dirls_sort(dirs.ent, dirs.used);
1021 if (files.used) http_dirls_sort(files.ent, files.used);
1023 out = buffer_init();
1024 http_list_directory_header(srv, con, p, out);
1026 /* directories */
1027 for (i = 0; i < dirs.used; i++) {
1028 tmp = dirs.ent[i];
1030 #ifdef HAVE_LOCALTIME_R
1031 localtime_r(&(tmp->mtime), &tm);
1032 strftime(datebuf, sizeof(datebuf), "%Y-%b-%d %H:%M:%S", &tm);
1033 #else
1034 strftime(datebuf, sizeof(datebuf), "%Y-%b-%d %H:%M:%S", localtime(&(tmp->mtime)));
1035 #endif
1037 buffer_append_string_len(out, CONST_STR_LEN("<tr class=\"d\"><td class=\"n\"><a href=\""));
1038 buffer_append_string_encoded(out, DIRLIST_ENT_NAME(tmp), tmp->namelen, ENCODING_REL_URI_PART);
1039 buffer_append_string_len(out, CONST_STR_LEN("/\">"));
1040 buffer_append_string_encoded(out, DIRLIST_ENT_NAME(tmp), tmp->namelen, ENCODING_MINIMAL_XML);
1041 buffer_append_string_len(out, CONST_STR_LEN("</a>/</td><td class=\"m\">"));
1042 buffer_append_string_len(out, datebuf, sizeof(datebuf) - 1);
1043 buffer_append_string_len(out, CONST_STR_LEN("</td><td class=\"s\">- &nbsp;</td><td class=\"t\">Directory</td></tr>\n"));
1045 free(tmp);
1048 /* files */
1049 for (i = 0; i < files.used; i++) {
1050 tmp = files.ent[i];
1052 content_type = NULL;
1053 #if defined(HAVE_XATTR)
1054 if (con->conf.use_xattr) {
1055 memcpy(path_file, DIRLIST_ENT_NAME(tmp), tmp->namelen + 1);
1056 attrlen = sizeof(attrval) - 1;
1057 if (attr_get(path, srv->srvconf.xattr_name->ptr, attrval, &attrlen, 0) == 0) {
1058 attrval[attrlen] = '\0';
1059 content_type = attrval;
1062 #elif defined(HAVE_EXTATTR)
1063 if (con->conf.use_xattr) {
1064 memcpy(path_file, DIRLIST_ENT_NAME(tmp), tmp->namelen + 1);
1065 if(-1 != (attrlen = extattr_get_file(path, EXTATTR_NAMESPACE_USER, srv->srvconf.xattr_name->ptr, attrval, sizeof(attrval)-1))) {
1066 attrval[attrlen] = '\0';
1067 content_type = attrval;
1070 #endif
1072 if (content_type == NULL) {
1073 content_type = "application/octet-stream";
1074 for (k = 0; k < con->conf.mimetypes->used; k++) {
1075 data_string *ds = (data_string *)con->conf.mimetypes->data[k];
1076 size_t ct_len;
1078 if (buffer_is_empty(ds->key))
1079 continue;
1081 ct_len = buffer_string_length(ds->key);
1082 if (tmp->namelen < ct_len)
1083 continue;
1085 if (0 == strncasecmp(DIRLIST_ENT_NAME(tmp) + tmp->namelen - ct_len, ds->key->ptr, ct_len)) {
1086 content_type = ds->value->ptr;
1087 break;
1092 #ifdef HAVE_LOCALTIME_R
1093 localtime_r(&(tmp->mtime), &tm);
1094 strftime(datebuf, sizeof(datebuf), "%Y-%b-%d %H:%M:%S", &tm);
1095 #else
1096 strftime(datebuf, sizeof(datebuf), "%Y-%b-%d %H:%M:%S", localtime(&(tmp->mtime)));
1097 #endif
1098 http_list_directory_sizefmt(sizebuf, sizeof(sizebuf), tmp->size);
1100 buffer_append_string_len(out, CONST_STR_LEN("<tr><td class=\"n\"><a href=\""));
1101 buffer_append_string_encoded(out, DIRLIST_ENT_NAME(tmp), tmp->namelen, ENCODING_REL_URI_PART);
1102 buffer_append_string_len(out, CONST_STR_LEN("\">"));
1103 buffer_append_string_encoded(out, DIRLIST_ENT_NAME(tmp), tmp->namelen, ENCODING_MINIMAL_XML);
1104 buffer_append_string_len(out, CONST_STR_LEN("</a></td><td class=\"m\">"));
1105 buffer_append_string_len(out, datebuf, sizeof(datebuf) - 1);
1106 buffer_append_string_len(out, CONST_STR_LEN("</td><td class=\"s\">"));
1107 buffer_append_string(out, sizebuf);
1108 buffer_append_string_len(out, CONST_STR_LEN("</td><td class=\"t\">"));
1109 buffer_append_string(out, content_type);
1110 buffer_append_string_len(out, CONST_STR_LEN("</td></tr>\n"));
1112 free(tmp);
1115 free(files.ent);
1116 free(dirs.ent);
1117 free(path);
1119 http_list_directory_footer(srv, con, p, out);
1121 /* Insert possible charset to Content-Type */
1122 if (buffer_string_is_empty(p->conf.encoding)) {
1123 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("text/html"));
1124 } else {
1125 buffer_copy_string_len(p->content_charset, CONST_STR_LEN("text/html; charset="));
1126 buffer_append_string_buffer(p->content_charset, p->conf.encoding);
1127 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(p->content_charset));
1130 con->file_finished = 1;
1131 chunkqueue_append_buffer(con->write_queue, out);
1132 buffer_free(out);
1134 return 0;
1139 URIHANDLER_FUNC(mod_dirlisting_subrequest) {
1140 plugin_data *p = p_d;
1141 stat_cache_entry *sce = NULL;
1143 UNUSED(srv);
1145 /* we only handle GET and HEAD */
1146 switch(con->request.http_method) {
1147 case HTTP_METHOD_GET:
1148 case HTTP_METHOD_HEAD:
1149 break;
1150 default:
1151 return HANDLER_GO_ON;
1154 if (con->mode != DIRECT) return HANDLER_GO_ON;
1156 if (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON;
1157 if (buffer_is_empty(con->uri.path)) return HANDLER_GO_ON;
1158 if (con->uri.path->ptr[buffer_string_length(con->uri.path) - 1] != '/') return HANDLER_GO_ON;
1160 mod_dirlisting_patch_connection(srv, con, p);
1162 if (!p->conf.dir_listing) return HANDLER_GO_ON;
1164 if (con->conf.log_request_handling) {
1165 log_error_write(srv, __FILE__, __LINE__, "s", "-- handling the request as Dir-Listing");
1166 log_error_write(srv, __FILE__, __LINE__, "sb", "URI :", con->uri.path);
1169 if (HANDLER_ERROR == stat_cache_get_entry(srv, con, con->physical.path, &sce)) {
1170 log_error_write(srv, __FILE__, __LINE__, "SB", "stat_cache_get_entry failed: ", con->physical.path);
1171 SEGFAULT();
1174 if (!S_ISDIR(sce->st.st_mode)) return HANDLER_GO_ON;
1176 if (http_list_directory(srv, con, p, con->physical.path)) {
1177 /* dirlisting failed */
1178 con->http_status = 403;
1181 buffer_reset(con->physical.path);
1183 /* not found */
1184 return HANDLER_FINISHED;
1187 /* this function is called at dlopen() time and inits the callbacks */
1189 int mod_dirlisting_plugin_init(plugin *p);
1190 int mod_dirlisting_plugin_init(plugin *p) {
1191 p->version = LIGHTTPD_VERSION_ID;
1192 p->name = buffer_init_string("dirlisting");
1194 p->init = mod_dirlisting_init;
1195 p->handle_subrequest_start = mod_dirlisting_subrequest;
1196 p->set_defaults = mod_dirlisting_set_defaults;
1197 p->cleanup = mod_dirlisting_free;
1199 p->data = NULL;
1201 return 0;