[mod_accesslog] %{ratio}n logs compression ratio (fixes #2133)
[lighttpd.git] / src / mod_dirlisting.c
blob160753941b7c8b62c8584a457c6575365f81700f
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"
11 #include "stream.h"
13 #include <ctype.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <dirent.h>
17 #include <assert.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <stdio.h>
21 #include <unistd.h>
22 #include <time.h>
24 /**
25 * this is a dirlisting for a lighttpd plugin
28 #ifdef HAVE_ATTR_ATTRIBUTES_H
29 #include <attr/attributes.h>
30 #endif
32 #ifdef HAVE_SYS_EXTATTR_H
33 #include <sys/extattr.h>
34 #endif
36 /* plugin config for all request/connections */
38 typedef struct {
39 #ifdef HAVE_PCRE_H
40 pcre *regex;
41 #endif
42 buffer *string;
43 } excludes;
45 typedef struct {
46 excludes **ptr;
48 size_t used;
49 size_t size;
50 } excludes_buffer;
52 typedef struct {
53 unsigned short dir_listing;
54 unsigned short hide_dot_files;
55 unsigned short show_readme;
56 unsigned short hide_readme_file;
57 unsigned short encode_readme;
58 unsigned short show_header;
59 unsigned short hide_header_file;
60 unsigned short encode_header;
61 unsigned short auto_layout;
63 excludes_buffer *excludes;
65 buffer *external_css;
66 buffer *external_js;
67 buffer *encoding;
68 buffer *set_footer;
69 } plugin_config;
71 typedef struct {
72 PLUGIN_DATA;
74 buffer *tmp_buf;
75 buffer *content_charset;
77 plugin_config **config_storage;
79 plugin_config conf;
80 } plugin_data;
82 static excludes_buffer *excludes_buffer_init(void) {
83 excludes_buffer *exb;
85 exb = calloc(1, sizeof(*exb));
87 return exb;
90 static int excludes_buffer_append(excludes_buffer *exb, buffer *string) {
91 #ifdef HAVE_PCRE_H
92 size_t i;
93 const char *errptr;
94 int erroff;
96 if (!string) return -1;
98 if (exb->size == 0) {
99 exb->size = 4;
100 exb->used = 0;
102 exb->ptr = malloc(exb->size * sizeof(*exb->ptr));
104 for(i = 0; i < exb->size ; i++) {
105 exb->ptr[i] = calloc(1, sizeof(**exb->ptr));
107 } else if (exb->used == exb->size) {
108 exb->size += 4;
110 exb->ptr = realloc(exb->ptr, exb->size * sizeof(*exb->ptr));
112 for(i = exb->used; i < exb->size; i++) {
113 exb->ptr[i] = calloc(1, sizeof(**exb->ptr));
118 if (NULL == (exb->ptr[exb->used]->regex = pcre_compile(string->ptr, 0,
119 &errptr, &erroff, NULL))) {
120 return -1;
123 exb->ptr[exb->used]->string = buffer_init();
124 buffer_copy_buffer(exb->ptr[exb->used]->string, string);
126 exb->used++;
128 return 0;
129 #else
130 UNUSED(exb);
131 UNUSED(string);
133 return -1;
134 #endif
137 static void excludes_buffer_free(excludes_buffer *exb) {
138 #ifdef HAVE_PCRE_H
139 size_t i;
141 for (i = 0; i < exb->size; i++) {
142 if (exb->ptr[i]->regex) pcre_free(exb->ptr[i]->regex);
143 if (exb->ptr[i]->string) buffer_free(exb->ptr[i]->string);
144 free(exb->ptr[i]);
147 if (exb->ptr) free(exb->ptr);
148 #endif
150 free(exb);
153 /* init the plugin data */
154 INIT_FUNC(mod_dirlisting_init) {
155 plugin_data *p;
157 p = calloc(1, sizeof(*p));
159 p->tmp_buf = buffer_init();
160 p->content_charset = buffer_init();
162 return p;
165 /* detroy the plugin data */
166 FREE_FUNC(mod_dirlisting_free) {
167 plugin_data *p = p_d;
169 UNUSED(srv);
171 if (!p) return HANDLER_GO_ON;
173 if (p->config_storage) {
174 size_t i;
175 for (i = 0; i < srv->config_context->used; i++) {
176 plugin_config *s = p->config_storage[i];
178 if (!s) continue;
180 excludes_buffer_free(s->excludes);
181 buffer_free(s->external_css);
182 buffer_free(s->external_js);
183 buffer_free(s->encoding);
184 buffer_free(s->set_footer);
186 free(s);
188 free(p->config_storage);
191 buffer_free(p->tmp_buf);
192 buffer_free(p->content_charset);
194 free(p);
196 return HANDLER_GO_ON;
199 /* handle plugin config and check values */
201 #define CONFIG_EXCLUDE "dir-listing.exclude"
202 #define CONFIG_ACTIVATE "dir-listing.activate"
203 #define CONFIG_HIDE_DOTFILES "dir-listing.hide-dotfiles"
204 #define CONFIG_EXTERNAL_CSS "dir-listing.external-css"
205 #define CONFIG_EXTERNAL_JS "dir-listing.external-js"
206 #define CONFIG_ENCODING "dir-listing.encoding"
207 #define CONFIG_SHOW_README "dir-listing.show-readme"
208 #define CONFIG_HIDE_README_FILE "dir-listing.hide-readme-file"
209 #define CONFIG_SHOW_HEADER "dir-listing.show-header"
210 #define CONFIG_HIDE_HEADER_FILE "dir-listing.hide-header-file"
211 #define CONFIG_DIR_LISTING "server.dir-listing"
212 #define CONFIG_SET_FOOTER "dir-listing.set-footer"
213 #define CONFIG_ENCODE_README "dir-listing.encode-readme"
214 #define CONFIG_ENCODE_HEADER "dir-listing.encode-header"
215 #define CONFIG_AUTO_LAYOUT "dir-listing.auto-layout"
218 SETDEFAULTS_FUNC(mod_dirlisting_set_defaults) {
219 plugin_data *p = p_d;
220 size_t i = 0;
222 config_values_t cv[] = {
223 { CONFIG_EXCLUDE, NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
224 { CONFIG_ACTIVATE, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
225 { CONFIG_HIDE_DOTFILES, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
226 { CONFIG_EXTERNAL_CSS, NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 3 */
227 { CONFIG_ENCODING, NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 4 */
228 { CONFIG_SHOW_README, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 5 */
229 { CONFIG_HIDE_README_FILE, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 6 */
230 { CONFIG_SHOW_HEADER, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 7 */
231 { CONFIG_HIDE_HEADER_FILE, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 8 */
232 { CONFIG_DIR_LISTING, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 9 */
233 { CONFIG_SET_FOOTER, NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 10 */
234 { CONFIG_ENCODE_README, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 11 */
235 { CONFIG_ENCODE_HEADER, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 12 */
236 { CONFIG_AUTO_LAYOUT, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 13 */
237 { CONFIG_EXTERNAL_JS, NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 14 */
239 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
242 if (!p) return HANDLER_ERROR;
244 p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
246 for (i = 0; i < srv->config_context->used; i++) {
247 data_config const* config = (data_config const*)srv->config_context->data[i];
248 plugin_config *s;
249 data_unset *du_excludes;
251 s = calloc(1, sizeof(plugin_config));
252 s->excludes = excludes_buffer_init();
253 s->dir_listing = 0;
254 s->external_css = buffer_init();
255 s->external_js = buffer_init();
256 s->hide_dot_files = 1;
257 s->show_readme = 0;
258 s->hide_readme_file = 0;
259 s->show_header = 0;
260 s->hide_header_file = 0;
261 s->encode_readme = 1;
262 s->encode_header = 1;
263 s->auto_layout = 1;
265 s->encoding = buffer_init();
266 s->set_footer = buffer_init();
268 cv[0].destination = s->excludes;
269 cv[1].destination = &(s->dir_listing);
270 cv[2].destination = &(s->hide_dot_files);
271 cv[3].destination = s->external_css;
272 cv[4].destination = s->encoding;
273 cv[5].destination = &(s->show_readme);
274 cv[6].destination = &(s->hide_readme_file);
275 cv[7].destination = &(s->show_header);
276 cv[8].destination = &(s->hide_header_file);
277 cv[9].destination = &(s->dir_listing); /* old name */
278 cv[10].destination = s->set_footer;
279 cv[11].destination = &(s->encode_readme);
280 cv[12].destination = &(s->encode_header);
281 cv[13].destination = &(s->auto_layout);
282 cv[14].destination = s->external_js;
284 p->config_storage[i] = s;
286 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
287 return HANDLER_ERROR;
290 if (NULL != (du_excludes = array_get_element(config->value, CONFIG_EXCLUDE))) {
291 array *excludes_list;
292 size_t j;
294 if (du_excludes->type != TYPE_ARRAY) {
295 log_error_write(srv, __FILE__, __LINE__, "sss",
296 "unexpected type for key: ", CONFIG_EXCLUDE, "array of strings");
297 return HANDLER_ERROR;
300 excludes_list = ((data_array*)du_excludes)->value;
302 #ifndef HAVE_PCRE_H
303 if (excludes_list->used > 0) {
304 log_error_write(srv, __FILE__, __LINE__, "sss",
305 "pcre support is missing for: ", CONFIG_EXCLUDE, ", please install libpcre and the headers");
306 return HANDLER_ERROR;
308 #else
309 for (j = 0; j < excludes_list->used; j++) {
310 data_unset *du_exclude = excludes_list->data[j];
312 if (du_exclude->type != TYPE_STRING) {
313 log_error_write(srv, __FILE__, __LINE__, "sssbs",
314 "unexpected type for key: ", CONFIG_EXCLUDE, "[",
315 du_exclude->key, "](string)");
316 return HANDLER_ERROR;
319 if (0 != excludes_buffer_append(s->excludes, ((data_string*)(du_exclude))->value)) {
320 log_error_write(srv, __FILE__, __LINE__, "sb",
321 "pcre-compile failed for", ((data_string*)(du_exclude))->value);
322 return HANDLER_ERROR;
325 #endif
329 return HANDLER_GO_ON;
332 #define PATCH(x) \
333 p->conf.x = s->x;
334 static int mod_dirlisting_patch_connection(server *srv, connection *con, plugin_data *p) {
335 size_t i, j;
336 plugin_config *s = p->config_storage[0];
338 PATCH(dir_listing);
339 PATCH(external_css);
340 PATCH(external_js);
341 PATCH(hide_dot_files);
342 PATCH(encoding);
343 PATCH(show_readme);
344 PATCH(hide_readme_file);
345 PATCH(show_header);
346 PATCH(hide_header_file);
347 PATCH(excludes);
348 PATCH(set_footer);
349 PATCH(encode_readme);
350 PATCH(encode_header);
351 PATCH(auto_layout);
353 /* skip the first, the global context */
354 for (i = 1; i < srv->config_context->used; i++) {
355 data_config *dc = (data_config *)srv->config_context->data[i];
356 s = p->config_storage[i];
358 /* condition didn't match */
359 if (!config_check_cond(srv, con, dc)) continue;
361 /* merge config */
362 for (j = 0; j < dc->value->used; j++) {
363 data_unset *du = dc->value->data[j];
365 if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_ACTIVATE)) ||
366 buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_DIR_LISTING))) {
367 PATCH(dir_listing);
368 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_HIDE_DOTFILES))) {
369 PATCH(hide_dot_files);
370 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_EXTERNAL_CSS))) {
371 PATCH(external_css);
372 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_EXTERNAL_JS))) {
373 PATCH(external_js);
374 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_ENCODING))) {
375 PATCH(encoding);
376 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_SHOW_README))) {
377 PATCH(show_readme);
378 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_HIDE_README_FILE))) {
379 PATCH(hide_readme_file);
380 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_SHOW_HEADER))) {
381 PATCH(show_header);
382 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_HIDE_HEADER_FILE))) {
383 PATCH(hide_header_file);
384 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_SET_FOOTER))) {
385 PATCH(set_footer);
386 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_EXCLUDE))) {
387 PATCH(excludes);
388 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_ENCODE_README))) {
389 PATCH(encode_readme);
390 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_ENCODE_HEADER))) {
391 PATCH(encode_header);
392 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_AUTO_LAYOUT))) {
393 PATCH(auto_layout);
398 return 0;
400 #undef PATCH
402 typedef struct {
403 size_t namelen;
404 time_t mtime;
405 off_t size;
406 } dirls_entry_t;
408 typedef struct {
409 dirls_entry_t **ent;
410 size_t used;
411 size_t size;
412 } dirls_list_t;
414 #define DIRLIST_ENT_NAME(ent) ((char*)(ent) + sizeof(dirls_entry_t))
415 #define DIRLIST_BLOB_SIZE 16
417 /* simple combsort algorithm */
418 static void http_dirls_sort(dirls_entry_t **ent, int num) {
419 int gap = num;
420 int i, j;
421 int swapped;
422 dirls_entry_t *tmp;
424 do {
425 gap = (gap * 10) / 13;
426 if (gap == 9 || gap == 10)
427 gap = 11;
428 if (gap < 1)
429 gap = 1;
430 swapped = 0;
432 for (i = 0; i < num - gap; i++) {
433 j = i + gap;
434 if (strcmp(DIRLIST_ENT_NAME(ent[i]), DIRLIST_ENT_NAME(ent[j])) > 0) {
435 tmp = ent[i];
436 ent[i] = ent[j];
437 ent[j] = tmp;
438 swapped = 1;
442 } while (gap > 1 || swapped);
445 /* buffer must be able to hold "999.9K"
446 * conversion is simple but not perfect
448 static int http_list_directory_sizefmt(char *buf, size_t bufsz, off_t size) {
449 const char unit[] = " KMGTPE"; /* Kilo, Mega, Giga, Tera, Peta, Exa */
450 const char *u = unit; /* u will always increment at least once */
451 int remain;
452 size_t buflen;
454 if (size < 100)
455 size += 99;
456 if (size < 100)
457 size = 0;
459 while (1) {
460 remain = (int) size & 1023;
461 size >>= 10;
462 u++;
463 if ((size & (~0 ^ 1023)) == 0)
464 break;
467 remain /= 100;
468 if (remain > 9)
469 remain = 9;
470 if (size > 999) {
471 size = 0;
472 remain = 9;
473 u++;
476 li_itostrn(buf, bufsz, size);
477 buflen = strlen(buf);
478 if (buflen + 3 >= bufsz) return buflen;
479 buf[buflen+0] = '.';
480 buf[buflen+1] = remain + '0';
481 buf[buflen+2] = *u;
482 buf[buflen+3] = '\0';
484 return buflen + 3;
487 /* don't want to block when open()ing a fifo */
488 #if defined(O_NONBLOCK)
489 # define FIFO_NONBLOCK O_NONBLOCK
490 #else
491 # define FIFO_NONBLOCK 0
492 #endif
494 static void http_list_directory_include_file(buffer *out, buffer *path, const char *classname, int encode) {
495 int fd = open(path->ptr, O_RDONLY | FIFO_NONBLOCK);
496 ssize_t rd;
497 char buf[8192];
499 if (-1 == fd) return;
501 if (encode) {
502 buffer_append_string_len(out, CONST_STR_LEN("<pre class=\""));
503 buffer_append_string(out, classname);
504 buffer_append_string_len(out, CONST_STR_LEN("\">"));
507 while ((rd = read(fd, buf, sizeof(buf))) > 0) {
508 if (encode) {
509 buffer_append_string_encoded(out, buf, (size_t)rd, ENCODING_MINIMAL_XML);
510 } else {
511 buffer_append_string_len(out, buf, (size_t)rd);
514 close(fd);
516 if (encode) {
517 buffer_append_string_len(out, CONST_STR_LEN("</pre>"));
521 /* portions copied from mod_status
522 * modified and specialized for stable dirlist sorting by name */
523 static const char js_simple_table_resort[] = \
524 "var click_column;\n" \
525 "var name_column = 0;\n" \
526 "var date_column = 1;\n" \
527 "var size_column = 2;\n" \
528 "var type_column = 3;\n" \
529 "var prev_span = null;\n" \
530 "\n" \
531 "if (typeof(String.prototype.localeCompare) === 'undefined') {\n" \
532 " String.prototype.localeCompare = function(str, locale, options) {\n" \
533 " return ((this == str) ? 0 : ((this > str) ? 1 : -1));\n" \
534 " };\n" \
535 "}\n" \
536 "\n" \
537 "if (typeof(String.prototype.toLocaleUpperCase) === 'undefined') {\n" \
538 " String.prototype.toLocaleUpperCase = function() {\n" \
539 " return this.toUpperCase();\n" \
540 " };\n" \
541 "}\n" \
542 "\n" \
543 "function get_inner_text(el) {\n" \
544 " if((typeof el == 'string')||(typeof el == 'undefined'))\n" \
545 " return el;\n" \
546 " if(el.innerText)\n" \
547 " return el.innerText;\n" \
548 " else {\n" \
549 " var str = \"\";\n" \
550 " var cs = el.childNodes;\n" \
551 " var l = cs.length;\n" \
552 " for (i=0;i<l;i++) {\n" \
553 " if (cs[i].nodeType==1) str += get_inner_text(cs[i]);\n" \
554 " else if (cs[i].nodeType==3) str += cs[i].nodeValue;\n" \
555 " }\n" \
556 " }\n" \
557 " return str;\n" \
558 "}\n" \
559 "\n" \
560 "function isdigit(c) {\n" \
561 " return (c >= '0' && c <= '9');\n" \
562 "}\n" \
563 "\n" \
564 "function unit_multiplier(unit) {\n" \
565 " return (unit=='K') ? 1000\n" \
566 " : (unit=='M') ? 1000000\n" \
567 " : (unit=='G') ? 1000000000\n" \
568 " : (unit=='T') ? 1000000000000\n" \
569 " : (unit=='P') ? 1000000000000000\n" \
570 " : (unit=='E') ? 1000000000000000000 : 1;\n" \
571 "}\n" \
572 "\n" \
573 "function sortfn_then_by_name(a,b,sort_column) {\n" \
574 " if (sort_column == name_column || sort_column == type_column) {\n" \
575 " var ad = (a.cells[type_column].innerHTML === 'Directory');\n" \
576 " var bd = (b.cells[type_column].innerHTML === 'Directory');\n" \
577 " if (ad != bd) return (ad ? -1 : 1);\n" \
578 " }\n" \
579 " var at = get_inner_text(a.cells[sort_column]);\n" \
580 " var bt = get_inner_text(b.cells[sort_column]);\n" \
581 " var cmp;\n" \
582 " if (a.cells[sort_column].className == 'int') {\n" \
583 " cmp = parseInt(at)-parseInt(bt);\n" \
584 " } else if (sort_column == date_column) {\n" \
585 " cmp = Date.parse(at.replace(/-/g, '/'))\n" \
586 " - Date.parse(bt.replace(/-/g, '/'));\n" \
587 " var ad = isdigit(at.substr(0,1));\n" \
588 " var bd = isdigit(bt.substr(0,1));\n" \
589 " if (ad != bd) return (!ad ? -1 : 1);\n" \
590 " } else if (sort_column == size_column) {\n" \
591 " var ai = parseInt(at, 10) * unit_multiplier(at.substr(-1,1));\n" \
592 " var bi = parseInt(bt, 10) * unit_multiplier(bt.substr(-1,1));\n" \
593 " if (at.substr(0,1) == '-') ai = -1;\n" \
594 " if (bt.substr(0,1) == '-') bi = -1;\n" \
595 " cmp = ai - bi;\n" \
596 " } else {\n" \
597 " cmp = at.toLocaleUpperCase().localeCompare(bt.toLocaleUpperCase());\n" \
598 " if (0 != cmp) return cmp;\n" \
599 " cmp = at.localeCompare(bt);\n" \
600 " }\n" \
601 " if (0 != cmp || sort_column == name_column) return cmp;\n" \
602 " return sortfn_then_by_name(a,b,name_column);\n" \
603 "}\n" \
604 "\n" \
605 "function sortfn(a,b) {\n" \
606 " return sortfn_then_by_name(a,b,click_column);\n" \
607 "}\n" \
608 "\n" \
609 "function resort(lnk) {\n" \
610 " var span = lnk.childNodes[1];\n" \
611 " var table = lnk.parentNode.parentNode.parentNode.parentNode;\n" \
612 " var rows = new Array();\n" \
613 " for (j=1;j<table.rows.length;j++)\n" \
614 " rows[j-1] = table.rows[j];\n" \
615 " click_column = lnk.parentNode.cellIndex;\n" \
616 " rows.sort(sortfn);\n" \
617 "\n" \
618 " if (prev_span != null) prev_span.innerHTML = '';\n" \
619 " if (span.getAttribute('sortdir')=='down') {\n" \
620 " span.innerHTML = '&uarr;';\n" \
621 " span.setAttribute('sortdir','up');\n" \
622 " rows.reverse();\n" \
623 " } else {\n" \
624 " span.innerHTML = '&darr;';\n" \
625 " span.setAttribute('sortdir','down');\n" \
626 " }\n" \
627 " for (i=0;i<rows.length;i++)\n" \
628 " table.tBodies[0].appendChild(rows[i]);\n" \
629 " prev_span = span;\n" \
630 "}\n";
632 /* portions copied from mod_dirlist (lighttpd2) */
633 static const char js_simple_table_init_sort[] = \
634 "\n" \
635 "function init_sort(init_sort_column, ascending) {\n" \
636 " var tables = document.getElementsByTagName(\"table\");\n" \
637 " for (var i = 0; i < tables.length; i++) {\n" \
638 " var table = tables[i];\n" \
639 " //var c = table.getAttribute(\"class\")\n" \
640 " //if (-1 != c.split(\" \").indexOf(\"sort\")) {\n" \
641 " var row = table.rows[0].cells;\n" \
642 " for (var j = 0; j < row.length; j++) {\n" \
643 " var n = row[j];\n" \
644 " if (n.childNodes.length == 1 && n.childNodes[0].nodeType == 3) {\n" \
645 " var link = document.createElement(\"a\");\n" \
646 " var title = n.childNodes[0].nodeValue.replace(/:$/, \"\");\n" \
647 " link.appendChild(document.createTextNode(title));\n" \
648 " link.setAttribute(\"href\", \"#\");\n" \
649 " link.setAttribute(\"class\", \"sortheader\");\n" \
650 " link.setAttribute(\"onclick\", \"resort(this);return false;\");\n" \
651 " var arrow = document.createElement(\"span\");\n" \
652 " arrow.setAttribute(\"class\", \"sortarrow\");\n" \
653 " arrow.appendChild(document.createTextNode(\":\"));\n" \
654 " link.appendChild(arrow)\n" \
655 " n.replaceChild(link, n.firstChild);\n" \
656 " }\n" \
657 " }\n" \
658 " var lnk = row[init_sort_column].firstChild;\n" \
659 " if (ascending) {\n" \
660 " var span = lnk.childNodes[1];\n" \
661 " span.setAttribute('sortdir','down');\n" \
662 " }\n" \
663 " resort(lnk);\n" \
664 " //}\n" \
665 " }\n" \
666 "}\n";
668 static void http_dirlist_append_js_table_resort (buffer *b, connection *con) {
669 char col = '0';
670 char ascending = '0';
671 if (!buffer_string_is_empty(con->uri.query)) {
672 const char *qs = con->uri.query->ptr;
673 do {
674 if (qs[0] == 'C' && qs[1] == '=') {
675 switch (qs[2]) {
676 case 'N': col = '0'; break;
677 case 'M': col = '1'; break;
678 case 'S': col = '2'; break;
679 case 'T':
680 case 'D': col = '3'; break;
681 default: break;
684 else if (qs[0] == 'O' && qs[1] == '=') {
685 switch (qs[2]) {
686 case 'A': ascending = '1'; break;
687 case 'D': ascending = '0'; break;
688 default: break;
691 } while ((qs = strchr(qs, '&')) && *++qs);
694 buffer_append_string_len(b, CONST_STR_LEN("\n<script type=\"text/javascript\">\n// <!--\n\n"));
695 buffer_append_string_len(b, js_simple_table_resort, sizeof(js_simple_table_resort)-1);
696 buffer_append_string_len(b, js_simple_table_init_sort, sizeof(js_simple_table_init_sort)-1);
697 buffer_append_string_len(b, CONST_STR_LEN("\ninit_sort("));
698 buffer_append_string_len(b, &col, 1);
699 buffer_append_string_len(b, CONST_STR_LEN(", "));
700 buffer_append_string_len(b, &ascending, 1);
701 buffer_append_string_len(b, CONST_STR_LEN(");\n\n// -->\n</script>\n\n"));
704 static void http_list_directory_header(server *srv, connection *con, plugin_data *p, buffer *out) {
705 UNUSED(srv);
707 if (p->conf.auto_layout) {
708 buffer_append_string_len(out, CONST_STR_LEN(
709 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n"
710 "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n"
711 "<head>\n"
712 "<title>Index of "
714 buffer_append_string_encoded(out, CONST_BUF_LEN(con->uri.path), ENCODING_MINIMAL_XML);
715 buffer_append_string_len(out, CONST_STR_LEN("</title>\n"));
717 if (!buffer_string_is_empty(p->conf.external_css)) {
718 buffer_append_string_len(out, CONST_STR_LEN("<link rel=\"stylesheet\" type=\"text/css\" href=\""));
719 buffer_append_string_buffer(out, p->conf.external_css);
720 buffer_append_string_len(out, CONST_STR_LEN("\" />\n"));
721 } else {
722 buffer_append_string_len(out, CONST_STR_LEN(
723 "<style type=\"text/css\">\n"
724 "a, a:active {text-decoration: none; color: blue;}\n"
725 "a:visited {color: #48468F;}\n"
726 "a:hover, a:focus {text-decoration: underline; color: red;}\n"
727 "body {background-color: #F5F5F5;}\n"
728 "h2 {margin-bottom: 12px;}\n"
729 "table {margin-left: 12px;}\n"
730 "th, td {"
731 " font: 90% monospace;"
732 " text-align: left;"
733 "}\n"
734 "th {"
735 " font-weight: bold;"
736 " padding-right: 14px;"
737 " padding-bottom: 3px;"
738 "}\n"
739 "td {padding-right: 14px;}\n"
740 "td.s, th.s {text-align: right;}\n"
741 "div.list {"
742 " background-color: white;"
743 " border-top: 1px solid #646464;"
744 " border-bottom: 1px solid #646464;"
745 " padding-top: 10px;"
746 " padding-bottom: 14px;"
747 "}\n"
748 "div.foot {"
749 " font: 90% monospace;"
750 " color: #787878;"
751 " padding-top: 4px;"
752 "}\n"
753 "</style>\n"
757 buffer_append_string_len(out, CONST_STR_LEN("</head>\n<body>\n"));
760 /* HEADER.txt */
761 if (p->conf.show_header) {
762 /* if we have a HEADER file, display it in <pre class="header"></pre> */
764 buffer_copy_buffer(p->tmp_buf, con->physical.path);
765 buffer_append_slash(p->tmp_buf);
766 buffer_append_string_len(p->tmp_buf, CONST_STR_LEN("HEADER.txt"));
768 http_list_directory_include_file(out, p->tmp_buf, "header", p->conf.encode_header);
771 buffer_append_string_len(out, CONST_STR_LEN("<h2>Index of "));
772 buffer_append_string_encoded(out, CONST_BUF_LEN(con->uri.path), ENCODING_MINIMAL_XML);
773 buffer_append_string_len(out, CONST_STR_LEN(
774 "</h2>\n"
775 "<div class=\"list\">\n"
776 "<table summary=\"Directory Listing\" cellpadding=\"0\" cellspacing=\"0\">\n"
777 "<thead>"
778 "<tr>"
779 "<th class=\"n\">Name</th>"
780 "<th class=\"m\">Last Modified</th>"
781 "<th class=\"s\">Size</th>"
782 "<th class=\"t\">Type</th>"
783 "</tr>"
784 "</thead>\n"
785 "<tbody>\n"
786 "<tr class=\"d\">"
787 "<td class=\"n\"><a href=\"../\">..</a>/</td>"
788 "<td class=\"m\">&nbsp;</td>"
789 "<td class=\"s\">- &nbsp;</td>"
790 "<td class=\"t\">Directory</td>"
791 "</tr>\n"
795 static void http_list_directory_footer(server *srv, connection *con, plugin_data *p, buffer *out) {
796 UNUSED(srv);
798 buffer_append_string_len(out, CONST_STR_LEN(
799 "</tbody>\n"
800 "</table>\n"
801 "</div>\n"
804 if (p->conf.show_readme) {
805 /* if we have a README file, display it in <pre class="readme"></pre> */
807 buffer_copy_buffer(p->tmp_buf, con->physical.path);
808 buffer_append_slash(p->tmp_buf);
809 buffer_append_string_len(p->tmp_buf, CONST_STR_LEN("README.txt"));
811 http_list_directory_include_file(out, p->tmp_buf, "readme", p->conf.encode_readme);
814 if(p->conf.auto_layout) {
816 if (!buffer_string_is_empty(p->conf.external_js)) {
817 buffer_append_string_len(out, CONST_STR_LEN("<script type=\"text/javascript\" src=\""));
818 buffer_append_string_buffer(out, p->conf.external_js);
819 buffer_append_string_len(out, CONST_STR_LEN("\" />\n"));
820 } else if (buffer_is_empty(p->conf.external_js)) {
821 http_dirlist_append_js_table_resort(out, con);
824 buffer_append_string_len(out, CONST_STR_LEN(
825 "<div class=\"foot\">"
828 if (!buffer_string_is_empty(p->conf.set_footer)) {
829 buffer_append_string_buffer(out, p->conf.set_footer);
830 } else {
831 buffer_append_string_buffer(out, con->conf.server_tag);
834 buffer_append_string_len(out, CONST_STR_LEN(
835 "</div>\n"
836 "</body>\n"
837 "</html>\n"
842 static int http_list_directory(server *srv, connection *con, plugin_data *p, buffer *dir) {
843 DIR *dp;
844 buffer *out;
845 struct dirent *dent;
846 struct stat st;
847 char *path, *path_file;
848 size_t i;
849 int hide_dotfiles = p->conf.hide_dot_files;
850 dirls_list_t dirs, files, *list;
851 dirls_entry_t *tmp;
852 char sizebuf[sizeof("999.9K")];
853 char datebuf[sizeof("2005-Jan-01 22:23:24")];
854 size_t k;
855 const char *content_type;
856 long name_max;
857 #if defined(HAVE_XATTR) || defined(HAVE_EXTATTR)
858 char attrval[128];
859 int attrlen;
860 #endif
861 #ifdef HAVE_LOCALTIME_R
862 struct tm tm;
863 #endif
865 if (buffer_string_is_empty(dir)) return -1;
867 i = buffer_string_length(dir);
869 #ifdef HAVE_PATHCONF
870 if (0 >= (name_max = pathconf(dir->ptr, _PC_NAME_MAX))) {
871 /* some broken fs (fuse) return 0 instead of -1 */
872 #ifdef NAME_MAX
873 name_max = NAME_MAX;
874 #else
875 name_max = 255; /* stupid default */
876 #endif
878 #elif defined __WIN32
879 name_max = FILENAME_MAX;
880 #else
881 name_max = NAME_MAX;
882 #endif
884 path = malloc(i + name_max + 1);
885 force_assert(NULL != path);
886 memcpy(path, dir->ptr, i+1);
887 path_file = path + i;
889 if (NULL == (dp = opendir(path))) {
890 log_error_write(srv, __FILE__, __LINE__, "sbs",
891 "opendir failed:", dir, strerror(errno));
893 free(path);
894 return -1;
897 dirs.ent = (dirls_entry_t**) malloc(sizeof(dirls_entry_t*) * DIRLIST_BLOB_SIZE);
898 force_assert(dirs.ent);
899 dirs.size = DIRLIST_BLOB_SIZE;
900 dirs.used = 0;
901 files.ent = (dirls_entry_t**) malloc(sizeof(dirls_entry_t*) * DIRLIST_BLOB_SIZE);
902 force_assert(files.ent);
903 files.size = DIRLIST_BLOB_SIZE;
904 files.used = 0;
906 while ((dent = readdir(dp)) != NULL) {
907 unsigned short exclude_match = 0;
909 if (dent->d_name[0] == '.') {
910 if (hide_dotfiles)
911 continue;
912 if (dent->d_name[1] == '\0')
913 continue;
914 if (dent->d_name[1] == '.' && dent->d_name[2] == '\0')
915 continue;
918 if (p->conf.hide_readme_file) {
919 if (strcmp(dent->d_name, "README.txt") == 0)
920 continue;
922 if (p->conf.hide_header_file) {
923 if (strcmp(dent->d_name, "HEADER.txt") == 0)
924 continue;
927 /* compare d_name against excludes array
928 * elements, skipping any that match.
930 #ifdef HAVE_PCRE_H
931 for(i = 0; i < p->conf.excludes->used; i++) {
932 int n;
933 #define N 10
934 int ovec[N * 3];
935 pcre *regex = p->conf.excludes->ptr[i]->regex;
937 if ((n = pcre_exec(regex, NULL, dent->d_name,
938 strlen(dent->d_name), 0, 0, ovec, 3 * N)) < 0) {
939 if (n != PCRE_ERROR_NOMATCH) {
940 log_error_write(srv, __FILE__, __LINE__, "sd",
941 "execution error while matching:", n);
943 /* aborting would require a lot of manual cleanup here.
944 * skip instead (to not leak names that break pcre matching)
946 exclude_match = 1;
947 break;
950 else {
951 exclude_match = 1;
952 break;
956 if (exclude_match) {
957 continue;
959 #endif
961 i = strlen(dent->d_name);
963 /* NOTE: the manual says, d_name is never more than NAME_MAX
964 * so this should actually not be a buffer-overflow-risk
966 if (i > (size_t)name_max) continue;
968 memcpy(path_file, dent->d_name, i + 1);
969 if (stat(path, &st) != 0)
970 continue;
972 list = &files;
973 if (S_ISDIR(st.st_mode))
974 list = &dirs;
976 if (list->used == list->size) {
977 list->size += DIRLIST_BLOB_SIZE;
978 list->ent = (dirls_entry_t**) realloc(list->ent, sizeof(dirls_entry_t*) * list->size);
979 force_assert(list->ent);
982 tmp = (dirls_entry_t*) malloc(sizeof(dirls_entry_t) + 1 + i);
983 tmp->mtime = st.st_mtime;
984 tmp->size = st.st_size;
985 tmp->namelen = i;
986 memcpy(DIRLIST_ENT_NAME(tmp), dent->d_name, i + 1);
988 list->ent[list->used++] = tmp;
990 closedir(dp);
992 if (dirs.used) http_dirls_sort(dirs.ent, dirs.used);
994 if (files.used) http_dirls_sort(files.ent, files.used);
996 out = buffer_init();
997 buffer_copy_string_len(out, CONST_STR_LEN("<?xml version=\"1.0\" encoding=\""));
998 if (buffer_string_is_empty(p->conf.encoding)) {
999 buffer_append_string_len(out, CONST_STR_LEN("iso-8859-1"));
1000 } else {
1001 buffer_append_string_buffer(out, p->conf.encoding);
1003 buffer_append_string_len(out, CONST_STR_LEN("\"?>\n"));
1004 http_list_directory_header(srv, con, p, out);
1006 /* directories */
1007 for (i = 0; i < dirs.used; i++) {
1008 tmp = dirs.ent[i];
1010 #ifdef HAVE_LOCALTIME_R
1011 localtime_r(&(tmp->mtime), &tm);
1012 strftime(datebuf, sizeof(datebuf), "%Y-%b-%d %H:%M:%S", &tm);
1013 #else
1014 strftime(datebuf, sizeof(datebuf), "%Y-%b-%d %H:%M:%S", localtime(&(tmp->mtime)));
1015 #endif
1017 buffer_append_string_len(out, CONST_STR_LEN("<tr class=\"d\"><td class=\"n\"><a href=\""));
1018 buffer_append_string_encoded(out, DIRLIST_ENT_NAME(tmp), tmp->namelen, ENCODING_REL_URI_PART);
1019 buffer_append_string_len(out, CONST_STR_LEN("/\">"));
1020 buffer_append_string_encoded(out, DIRLIST_ENT_NAME(tmp), tmp->namelen, ENCODING_MINIMAL_XML);
1021 buffer_append_string_len(out, CONST_STR_LEN("</a>/</td><td class=\"m\">"));
1022 buffer_append_string_len(out, datebuf, sizeof(datebuf) - 1);
1023 buffer_append_string_len(out, CONST_STR_LEN("</td><td class=\"s\">- &nbsp;</td><td class=\"t\">Directory</td></tr>\n"));
1025 free(tmp);
1028 /* files */
1029 for (i = 0; i < files.used; i++) {
1030 tmp = files.ent[i];
1032 content_type = NULL;
1033 #if defined(HAVE_XATTR)
1034 if (con->conf.use_xattr) {
1035 memcpy(path_file, DIRLIST_ENT_NAME(tmp), tmp->namelen + 1);
1036 attrlen = sizeof(attrval) - 1;
1037 if (attr_get(path, srv->srvconf.xattr_name->ptr, attrval, &attrlen, 0) == 0) {
1038 attrval[attrlen] = '\0';
1039 content_type = attrval;
1042 #elif defined(HAVE_EXTATTR)
1043 if (con->conf.use_xattr) {
1044 memcpy(path_file, DIRLIST_ENT_NAME(tmp), tmp->namelen + 1);
1045 if(-1 != (attrlen = extattr_get_file(path, EXTATTR_NAMESPACE_USER, srv->srvconf.xattr_name->ptr, attrval, sizeof(attrval)-1))) {
1046 attrval[attrlen] = '\0';
1047 content_type = attrval;
1050 #endif
1052 if (content_type == NULL) {
1053 content_type = "application/octet-stream";
1054 for (k = 0; k < con->conf.mimetypes->used; k++) {
1055 data_string *ds = (data_string *)con->conf.mimetypes->data[k];
1056 size_t ct_len;
1058 if (buffer_is_empty(ds->key))
1059 continue;
1061 ct_len = buffer_string_length(ds->key);
1062 if (tmp->namelen < ct_len)
1063 continue;
1065 if (0 == strncasecmp(DIRLIST_ENT_NAME(tmp) + tmp->namelen - ct_len, ds->key->ptr, ct_len)) {
1066 content_type = ds->value->ptr;
1067 break;
1072 #ifdef HAVE_LOCALTIME_R
1073 localtime_r(&(tmp->mtime), &tm);
1074 strftime(datebuf, sizeof(datebuf), "%Y-%b-%d %H:%M:%S", &tm);
1075 #else
1076 strftime(datebuf, sizeof(datebuf), "%Y-%b-%d %H:%M:%S", localtime(&(tmp->mtime)));
1077 #endif
1078 http_list_directory_sizefmt(sizebuf, sizeof(sizebuf), tmp->size);
1080 buffer_append_string_len(out, CONST_STR_LEN("<tr><td class=\"n\"><a href=\""));
1081 buffer_append_string_encoded(out, DIRLIST_ENT_NAME(tmp), tmp->namelen, ENCODING_REL_URI_PART);
1082 buffer_append_string_len(out, CONST_STR_LEN("\">"));
1083 buffer_append_string_encoded(out, DIRLIST_ENT_NAME(tmp), tmp->namelen, ENCODING_MINIMAL_XML);
1084 buffer_append_string_len(out, CONST_STR_LEN("</a></td><td class=\"m\">"));
1085 buffer_append_string_len(out, datebuf, sizeof(datebuf) - 1);
1086 buffer_append_string_len(out, CONST_STR_LEN("</td><td class=\"s\">"));
1087 buffer_append_string(out, sizebuf);
1088 buffer_append_string_len(out, CONST_STR_LEN("</td><td class=\"t\">"));
1089 buffer_append_string(out, content_type);
1090 buffer_append_string_len(out, CONST_STR_LEN("</td></tr>\n"));
1092 free(tmp);
1095 free(files.ent);
1096 free(dirs.ent);
1097 free(path);
1099 http_list_directory_footer(srv, con, p, out);
1101 /* Insert possible charset to Content-Type */
1102 if (buffer_string_is_empty(p->conf.encoding)) {
1103 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("text/html"));
1104 } else {
1105 buffer_copy_string_len(p->content_charset, CONST_STR_LEN("text/html; charset="));
1106 buffer_append_string_buffer(p->content_charset, p->conf.encoding);
1107 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(p->content_charset));
1110 con->file_finished = 1;
1111 chunkqueue_append_buffer(con->write_queue, out);
1112 buffer_free(out);
1114 return 0;
1119 URIHANDLER_FUNC(mod_dirlisting_subrequest) {
1120 plugin_data *p = p_d;
1121 stat_cache_entry *sce = NULL;
1123 UNUSED(srv);
1125 /* we only handle GET and HEAD */
1126 switch(con->request.http_method) {
1127 case HTTP_METHOD_GET:
1128 case HTTP_METHOD_HEAD:
1129 break;
1130 default:
1131 return HANDLER_GO_ON;
1134 if (con->mode != DIRECT) return HANDLER_GO_ON;
1136 if (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON;
1137 if (buffer_is_empty(con->uri.path)) return HANDLER_GO_ON;
1138 if (con->uri.path->ptr[buffer_string_length(con->uri.path) - 1] != '/') return HANDLER_GO_ON;
1140 mod_dirlisting_patch_connection(srv, con, p);
1142 if (!p->conf.dir_listing) return HANDLER_GO_ON;
1144 if (con->conf.log_request_handling) {
1145 log_error_write(srv, __FILE__, __LINE__, "s", "-- handling the request as Dir-Listing");
1146 log_error_write(srv, __FILE__, __LINE__, "sb", "URI :", con->uri.path);
1149 if (HANDLER_ERROR == stat_cache_get_entry(srv, con, con->physical.path, &sce)) {
1150 log_error_write(srv, __FILE__, __LINE__, "SB", "stat_cache_get_entry failed: ", con->physical.path);
1151 SEGFAULT();
1154 if (!S_ISDIR(sce->st.st_mode)) return HANDLER_GO_ON;
1156 if (http_list_directory(srv, con, p, con->physical.path)) {
1157 /* dirlisting failed */
1158 con->http_status = 403;
1161 buffer_reset(con->physical.path);
1163 /* not found */
1164 return HANDLER_FINISHED;
1167 /* this function is called at dlopen() time and inits the callbacks */
1169 int mod_dirlisting_plugin_init(plugin *p);
1170 int mod_dirlisting_plugin_init(plugin *p) {
1171 p->version = LIGHTTPD_VERSION_ID;
1172 p->name = buffer_init_string("dirlisting");
1174 p->init = mod_dirlisting_init;
1175 p->handle_subrequest_start = mod_dirlisting_subrequest;
1176 p->set_defaults = mod_dirlisting_set_defaults;
1177 p->cleanup = mod_dirlisting_free;
1179 p->data = NULL;
1181 return 0;