forked from aperezdc/ngx-fancyindex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ngx_http_fancyindex_module.c
1582 lines (1314 loc) · 52.6 KB
/
ngx_http_fancyindex_module.c
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
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
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ngx_http_fancyindex_module.c
* Copyright © 2007-2016 Adrian Perez <[email protected]>
*
* Module used for fancy indexing of directories. Features and differences
* with the stock nginx autoindex module:
*
* - Output is a table instead of a <pre> element with embedded <a> links.
* - Header and footer may be added to every generated directory listing.
* - Default header and/or footer are generated if custom ones are not
* configured. Files used for header and footer can only be local path
* names (i.e. you cannot insert the result of a subrequest.)
* - Proper HTML is generated: it should validate both as XHTML 1.0 Strict
* and HTML 4.01.
*
* Base functionality heavy based upon the stock nginx autoindex module,
* which in turn was made by Igor Sysoev, like the majority of nginx.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
#include <ngx_log.h>
#include "template.h"
#if defined(__GNUC__) && (__GNUC__ >= 3)
# define ngx_force_inline __attribute__((__always_inline__))
#else /* !__GNUC__ */
# define ngx_force_inline
#endif /* __GNUC__ */
static const char *short_weekday[] = {
"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun",
};
static const char *long_weekday[] = {
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sunday",
};
static const char *short_month[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
};
static const char *long_month[] = {
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December",
};
#define DATETIME_FORMATS(F_, t) \
F_ ('a', 3, "%3s", short_weekday[((t)->ngx_tm_wday + 6) % 7]) \
F_ ('A', 9, "%s", long_weekday [((t)->ngx_tm_wday + 6) % 7]) \
F_ ('b', 3, "%3s", short_month[(t)->ngx_tm_mon - 1] ) \
F_ ('B', 9, "%s", long_month [(t)->ngx_tm_mon - 1] ) \
F_ ('d', 2, "%02d", (t)->ngx_tm_mday ) \
F_ ('e', 2, "%2d", (t)->ngx_tm_mday ) \
F_ ('F', 10, "%d-%02d-%02d", \
(t)->ngx_tm_year, \
(t)->ngx_tm_mon, \
(t)->ngx_tm_mday ) \
F_ ('H', 2, "%02d", (t)->ngx_tm_hour ) \
F_ ('I', 2, "%02d", ((t)->ngx_tm_hour % 12) + 1 ) \
F_ ('k', 2, "%2d", (t)->ngx_tm_hour ) \
F_ ('l', 2, "%2d", ((t)->ngx_tm_hour % 12) + 1 ) \
F_ ('m', 2, "%02d", (t)->ngx_tm_mon ) \
F_ ('M', 2, "%02d", (t)->ngx_tm_min ) \
F_ ('p', 2, "%2s", (((t)->ngx_tm_hour < 12) ? "AM" : "PM") ) \
F_ ('P', 2, "%2s", (((t)->ngx_tm_hour < 12) ? "am" : "pm") ) \
F_ ('r', 11, "%02d:%02d:%02d %2s", \
((t)->ngx_tm_hour % 12) + 1, \
(t)->ngx_tm_min, \
(t)->ngx_tm_sec, \
(((t)->ngx_tm_hour < 12) ? "AM" : "PM") ) \
F_ ('R', 5, "%02d:%02d", (t)->ngx_tm_hour, (t)->ngx_tm_min ) \
F_ ('S', 2, "%02d", (t)->ngx_tm_sec ) \
F_ ('T', 8, "%02d:%02d:%02d", \
(t)->ngx_tm_hour, \
(t)->ngx_tm_min, \
(t)->ngx_tm_sec ) \
F_ ('u', 1, "%1d", (((t)->ngx_tm_wday + 6) % 7) + 1 ) \
F_ ('w', 1, "%1d", ((t)->ngx_tm_wday + 6) % 7 ) \
F_ ('y', 2, "%02d", (t)->ngx_tm_year % 100 ) \
F_ ('Y', 4, "%04d", (t)->ngx_tm_year )
static size_t
ngx_fancyindex_timefmt_calc_size (const ngx_str_t *fmt)
{
#define DATETIME_CASE(letter, fmtlen, fmt, ...) \
case letter: result += (fmtlen); break;
size_t i, result = 0;
for (i = 0; i < fmt->len; i++) {
if (fmt->data[i] == '%') {
if (++i >= fmt->len) {
result++;
break;
}
switch (fmt->data[i]) {
DATETIME_FORMATS(DATETIME_CASE,)
default:
result++;
}
} else {
result++;
}
}
return result;
#undef DATETIME_CASE
}
static u_char*
ngx_fancyindex_timefmt (u_char *buffer, const ngx_str_t *fmt, const ngx_tm_t *tm)
{
#define DATETIME_CASE(letter, fmtlen, fmt, ...) \
case letter: buffer = ngx_snprintf(buffer, fmtlen, fmt, ##__VA_ARGS__); break;
size_t i;
for (i = 0; i < fmt->len; i++) {
if (fmt->data[i] == '%') {
if (++i >= fmt->len) {
*buffer++ = '%';
break;
}
switch (fmt->data[i]) {
DATETIME_FORMATS(DATETIME_CASE, tm)
default:
*buffer++ = fmt->data[i];
}
} else {
*buffer++ = fmt->data[i];
}
}
return buffer;
#undef DATETIME_CASE
}
typedef struct {
ngx_str_t path;
ngx_str_t local;
} ngx_fancyindex_headerfooter_conf_t;
/**
* Configuration structure for the fancyindex module. The configuration
* commands defined in the module do fill in the members of this structure.
*/
typedef struct {
ngx_flag_t enable; /**< Module is enabled. */
ngx_uint_t default_sort; /**< Default sort criterion. */
ngx_flag_t dirs_first; /**< Group directories together first when sorting */
ngx_flag_t localtime; /**< File mtime dates are sent in local time. */
ngx_flag_t exact_size; /**< Sizes are sent always in bytes. */
ngx_flag_t hide_symlinks; /**< Hide symbolic links in listings. */
ngx_flag_t show_path; /**< Whether to display or not the path + '</h1>' after the header */
ngx_flag_t hide_parent; /**< Hide parent directory. */
ngx_flag_t show_dot_files; /**< Show files that start with a dot.*/
ngx_str_t css_href; /**< Link to a CSS stylesheet, or empty if none. */
ngx_str_t time_format; /**< Format used for file timestamps. */
ngx_array_t *ignore; /**< List of files to ignore in listings. */
ngx_fancyindex_headerfooter_conf_t header;
ngx_fancyindex_headerfooter_conf_t footer;
} ngx_http_fancyindex_loc_conf_t;
#define NGX_HTTP_FANCYINDEX_SORT_CRITERION_NAME 0
#define NGX_HTTP_FANCYINDEX_SORT_CRITERION_SIZE 1
#define NGX_HTTP_FANCYINDEX_SORT_CRITERION_DATE 2
#define NGX_HTTP_FANCYINDEX_SORT_CRITERION_NAME_DESC 3
#define NGX_HTTP_FANCYINDEX_SORT_CRITERION_SIZE_DESC 4
#define NGX_HTTP_FANCYINDEX_SORT_CRITERION_DATE_DESC 5
static ngx_conf_enum_t ngx_http_fancyindex_sort_criteria[] = {
{ ngx_string("name"), NGX_HTTP_FANCYINDEX_SORT_CRITERION_NAME },
{ ngx_string("size"), NGX_HTTP_FANCYINDEX_SORT_CRITERION_SIZE },
{ ngx_string("date"), NGX_HTTP_FANCYINDEX_SORT_CRITERION_DATE },
{ ngx_string("name_desc"), NGX_HTTP_FANCYINDEX_SORT_CRITERION_NAME_DESC },
{ ngx_string("size_desc"), NGX_HTTP_FANCYINDEX_SORT_CRITERION_SIZE_DESC },
{ ngx_string("date_desc"), NGX_HTTP_FANCYINDEX_SORT_CRITERION_DATE_DESC },
{ ngx_null_string, 0 }
};
enum {
NGX_HTTP_FANCYINDEX_HEADERFOOTER_SUBREQUEST,
NGX_HTTP_FANCYINDEX_HEADERFOOTER_LOCAL,
};
static ngx_uint_t
headerfooter_kind(const ngx_str_t *value)
{
static const struct {
ngx_str_t name;
ngx_uint_t value;
} values[] = {
{ ngx_string("subrequest"), NGX_HTTP_FANCYINDEX_HEADERFOOTER_SUBREQUEST },
{ ngx_string("local"), NGX_HTTP_FANCYINDEX_HEADERFOOTER_LOCAL },
};
unsigned i;
for (i = 0; i < sizeof(values) / sizeof(values[0]); i++) {
if (value->len == values[i].name.len &&
ngx_strcasecmp(value->data, values[i].name.data) == 0)
{
return values[i].value;
}
}
return NGX_CONF_UNSET_UINT;
}
static char*
ngx_fancyindex_conf_set_headerfooter(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_fancyindex_headerfooter_conf_t *item =
(void*) (((char*) conf) + cmd->offset);
ngx_str_t *values = cf->args->elts;
if (item->path.data)
return "is duplicate";
item->path = values[1];
/* Kind of path. Default is "subrequest". */
ngx_uint_t kind = NGX_HTTP_FANCYINDEX_HEADERFOOTER_SUBREQUEST;
if (cf->args->nelts == 3) {
kind = headerfooter_kind(&values[2]);
if (kind == NGX_CONF_UNSET_UINT) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"unknown header/footer kind \"%V\"", &values[2]);
return NGX_CONF_ERROR;
}
}
if (kind == NGX_HTTP_FANCYINDEX_HEADERFOOTER_LOCAL) {
ngx_file_t file;
ngx_file_info_t fi;
ssize_t n;
ngx_memzero(&file, sizeof(ngx_file_t));
file.log = cf->log;
file.fd = ngx_open_file(item->path.data, NGX_FILE_RDONLY, 0, 0);
if (file.fd == NGX_INVALID_FILE) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, ngx_errno,
"cannot open file \"%V\"", &values[1]);
return NGX_CONF_ERROR;
}
if (ngx_fd_info(file.fd, &fi) == NGX_FILE_ERROR) {
ngx_close_file(file.fd);
ngx_conf_log_error(NGX_LOG_EMERG, cf, ngx_errno,
"cannot get info for file \"%V\"", &values[1]);
return NGX_CONF_ERROR;
}
item->local.len = ngx_file_size(&fi);
item->local.data = ngx_pcalloc(cf->pool, item->local.len + 1);
if (item->local.data == NULL) {
ngx_close_file(file.fd);
return NGX_CONF_ERROR;
}
n = item->local.len;
while (n > 0) {
ssize_t r = ngx_read_file(&file,
item->local.data + file.offset,
n,
file.offset);
if (r == NGX_ERROR) {
ngx_close_file(file.fd);
ngx_conf_log_error(NGX_LOG_EMERG, cf, ngx_errno,
"cannot read file \"%V\"", &values[1]);
return NGX_CONF_ERROR;
}
n -= r;
}
item->local.data[item->local.len] = '\0';
}
return NGX_CONF_OK;
}
#define NGX_HTTP_FANCYINDEX_PREALLOCATE 50
/**
* Calculates the length of a NULL-terminated string. It is ugly having to
* remember to substract 1 from the sizeof result.
*/
#define ngx_sizeof_ssz(_s) (sizeof(_s) - 1)
/**
* Compute the length of a statically allocated array
*/
#define DIM(x) (sizeof(x)/sizeof(*(x)))
/**
* Copy a static zero-terminated string. Useful to output template
* string pieces into a temporary buffer.
*/
#define ngx_cpymem_ssz(_p, _t) \
(ngx_cpymem((_p), (_t), sizeof(_t) - 1))
/**
* Copy a ngx_str_t.
*/
#define ngx_cpymem_str(_p, _s) \
(ngx_cpymem((_p), (_s).data, (_s).len))
/**
* Check whether a particular bit is set in a particular value.
*/
#define ngx_has_flag(_where, _what) \
(((_where) & (_what)) == (_what))
typedef struct {
ngx_str_t name;
size_t utf_len;
ngx_uint_t escape;
ngx_uint_t escape_html;
ngx_uint_t dir;
time_t mtime;
off_t size;
} ngx_http_fancyindex_entry_t;
static int ngx_libc_cdecl
ngx_http_fancyindex_cmp_entries_name_desc(const void *one, const void *two);
static int ngx_libc_cdecl
ngx_http_fancyindex_cmp_entries_size_desc(const void *one, const void *two);
static int ngx_libc_cdecl
ngx_http_fancyindex_cmp_entries_mtime_desc(const void *one, const void *two);
static int ngx_libc_cdecl
ngx_http_fancyindex_cmp_entries_name_asc(const void *one, const void *two);
static int ngx_libc_cdecl
ngx_http_fancyindex_cmp_entries_size_asc(const void *one, const void *two);
static int ngx_libc_cdecl
ngx_http_fancyindex_cmp_entries_mtime_asc(const void *one, const void *two);
static ngx_int_t ngx_http_fancyindex_error(ngx_http_request_t *r,
ngx_dir_t *dir, ngx_str_t *name);
static ngx_int_t ngx_http_fancyindex_init(ngx_conf_t *cf);
static void *ngx_http_fancyindex_create_loc_conf(ngx_conf_t *cf);
static char *ngx_http_fancyindex_merge_loc_conf(ngx_conf_t *cf,
void *parent, void *child);
static char *ngx_http_fancyindex_ignore(ngx_conf_t *cf,
ngx_command_t *cmd,
void *conf);
static uintptr_t
ngx_fancyindex_escape_filename(u_char *dst, u_char*src, size_t size);
/*
* These are used only once per handler invocation. We can tell GCC to
* inline them always, if possible (see how ngx_force_inline is defined
* above).
*/
static ngx_inline ngx_buf_t*
make_header_buf(ngx_http_request_t *r, const ngx_str_t css_href)
ngx_force_inline;
static ngx_command_t ngx_http_fancyindex_commands[] = {
{ ngx_string("fancyindex"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, enable),
NULL },
{ ngx_string("fancyindex_default_sort"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_enum_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, default_sort),
&ngx_http_fancyindex_sort_criteria },
{ ngx_string("fancyindex_directories_first"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, dirs_first),
NULL },
{ ngx_string("fancyindex_localtime"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, localtime),
NULL },
{ ngx_string("fancyindex_exact_size"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, exact_size),
NULL },
{ ngx_string("fancyindex_header"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE12,
ngx_fancyindex_conf_set_headerfooter,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, header),
NULL },
{ ngx_string("fancyindex_footer"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE12,
ngx_fancyindex_conf_set_headerfooter,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, footer),
NULL },
{ ngx_string("fancyindex_css_href"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
ngx_conf_set_str_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, css_href),
NULL },
{ ngx_string("fancyindex_ignore"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_1MORE,
ngx_http_fancyindex_ignore,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
{ ngx_string("fancyindex_hide_symlinks"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, hide_symlinks),
NULL },
{ ngx_string("fancyindex_show_path"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, show_path),
NULL },
{ ngx_string("fancyindex_show_dotfiles"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, show_dot_files),
NULL },
{ ngx_string("fancyindex_hide_parent_dir"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, hide_parent),
NULL },
{ ngx_string("fancyindex_time_format"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
ngx_conf_set_str_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_fancyindex_loc_conf_t, time_format),
NULL },
ngx_null_command
};
static ngx_http_module_t ngx_http_fancyindex_module_ctx = {
NULL, /* preconfiguration */
ngx_http_fancyindex_init, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_http_fancyindex_create_loc_conf, /* create location configuration */
ngx_http_fancyindex_merge_loc_conf /* merge location configuration */
};
ngx_module_t ngx_http_fancyindex_module = {
NGX_MODULE_V1,
&ngx_http_fancyindex_module_ctx, /* module context */
ngx_http_fancyindex_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static const ngx_str_t css_href_pre =
ngx_string("<link rel=\"stylesheet\" href=\"");
static const ngx_str_t css_href_post =
ngx_string("\" type=\"text/css\"/>\n");
#ifdef NGX_ESCAPE_URI_COMPONENT
static inline uintptr_t
ngx_fancyindex_escape_filename(u_char *dst, u_char *src, size_t size)
{
return ngx_escape_uri(dst, src, size, NGX_ESCAPE_URI_COMPONENT);
}
#else /* !NGX_ESCAPE_URI_COMPONENT */
static uintptr_t
ngx_fancyindex_escape_filename(u_char *dst, u_char *src, size_t size)
{
/*
* The ngx_escape_uri() function will not escape colons or the
* ? character, which signals the beginning of the query string.
* So we handle those characters ourselves.
*
* TODO: Get rid of this once ngx_escape_uri() works as expected!
*/
u_int escapes = 0;
u_char *psrc = src;
size_t psize = size;
while (psize--) {
switch (*psrc++) {
case ':':
case '?':
case '[':
case ']':
escapes++;
break;
}
}
if (dst == NULL) {
return escapes + ngx_escape_uri(NULL, src, size, NGX_ESCAPE_HTML);
}
else if (escapes == 0) {
/* No need to do extra escaping, avoid the temporary buffer */
return ngx_escape_uri(dst, src, size, NGX_ESCAPE_HTML);
}
else {
uintptr_t uescapes = ngx_escape_uri(NULL, src, size, NGX_ESCAPE_HTML);
size_t bufsz = size + 2 * uescapes;
/*
* GCC and CLANG both support stack-allocated variable length
* arrays. Take advantage of that to avoid a malloc-free cycle.
*/
#if defined(__GNUC__) || defined(__clang__)
u_char cbuf[bufsz];
u_char *buf = cbuf;
#else /* __GNUC__ || __clang__ */
u_char *buf = (u_char*) malloc(sizeof(u_char) * bufsz);
#endif /* __GNUC__ || __clang__ */
ngx_escape_uri(buf, src, size, NGX_ESCAPE_HTML);
while (bufsz--) {
switch (*buf) {
case ':':
*dst++ = '%';
*dst++ = '3';
*dst++ = 'A';
break;
case '?':
*dst++ = '%';
*dst++ = '3';
*dst++ = 'F';
break;
case '[':
*dst++ = '%';
*dst++ = '5';
*dst++ = 'B';
break;
case ']':
*dst++ = '%';
*dst++ = '5';
*dst++ = 'D';
break;
default:
*dst++ = *buf;
}
buf++;
}
#if !defined(__GNUC__) && !defined(__clang__)
free(buf);
#endif /* !__GNUC__ && !__clang__ */
return escapes + uescapes;
}
}
#endif /* NGX_ESCAPE_URI_COMPONENT */
static ngx_inline ngx_buf_t*
make_header_buf(ngx_http_request_t *r, const ngx_str_t css_href)
{
ngx_buf_t *b;
size_t blen = r->uri.len
+ ngx_sizeof_ssz(t01_head1)
+ ngx_sizeof_ssz(t02_head2)
+ ngx_sizeof_ssz(t03_head3)
+ ngx_sizeof_ssz(t04_body1)
;
if (css_href.len) {
blen += css_href_pre.len \
+ css_href.len \
+ css_href_post.len
;
}
if ((b = ngx_create_temp_buf(r->pool, blen)) == NULL)
return NULL;
b->last = ngx_cpymem_ssz(b->last, t01_head1);
if (css_href.len) {
b->last = ngx_cpymem_str(b->last, css_href_pre);
b->last = ngx_cpymem_str(b->last, css_href);
b->last = ngx_cpymem_str(b->last, css_href_post);
}
b->last = ngx_cpymem_ssz(b->last, t02_head2);
b->last = ngx_cpymem_str(b->last, r->uri);
b->last = ngx_cpymem_ssz(b->last, t03_head3);
b->last = ngx_cpymem_ssz(b->last, t04_body1);
return b;
}
static ngx_inline ngx_int_t
make_content_buf(
ngx_http_request_t *r, ngx_buf_t **pb,
ngx_http_fancyindex_loc_conf_t *alcf)
{
ngx_http_fancyindex_entry_t *entry;
int (*sort_cmp_func)(const void *, const void *);
const char *sort_url_args = "";
off_t length;
size_t len, root, allocated, escape_html;
int64_t multiplier;
u_char *filename, *last;
ngx_tm_t tm;
ngx_array_t entries;
ngx_time_t *tp;
ngx_uint_t i, j;
ngx_str_t path;
ngx_dir_t dir;
ngx_buf_t *b;
static const char *sizes[] = { "EiB", "PiB", "TiB", "GiB", "MiB", "KiB", "B" };
static const int64_t exbibyte = 1024LL * 1024LL * 1024LL *
1024LL * 1024LL * 1024LL;
/*
* NGX_DIR_MASK_LEN is lesser than NGX_HTTP_FANCYINDEX_PREALLOCATE
*/
if ((last = ngx_http_map_uri_to_path(r, &path, &root,
NGX_HTTP_FANCYINDEX_PREALLOCATE)) == NULL)
return NGX_HTTP_INTERNAL_SERVER_ERROR;
allocated = path.len;
path.len = last - path.data;
if (path.len > 1) {
path.len--;
}
path.data[path.len] = '\0';
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
"http fancyindex: \"%s\"", path.data);
if (ngx_open_dir(&path, &dir) == NGX_ERROR) {
ngx_int_t rc, err = ngx_errno;
ngx_uint_t level;
if (err == NGX_ENOENT || err == NGX_ENOTDIR || err == NGX_ENAMETOOLONG) {
level = NGX_LOG_ERR;
rc = NGX_HTTP_NOT_FOUND;
} else if (err == NGX_EACCES) {
level = NGX_LOG_ERR;
rc = NGX_HTTP_FORBIDDEN;
} else {
level = NGX_LOG_CRIT;
rc = NGX_HTTP_INTERNAL_SERVER_ERROR;
}
ngx_log_error(level, r->connection->log, err,
ngx_open_dir_n " \"%s\" failed", path.data);
return rc;
}
#if (NGX_SUPPRESS_WARN)
/* MSVC thinks 'entries' may be used without having been initialized */
ngx_memzero(&entries, sizeof(ngx_array_t));
#endif /* NGX_SUPPRESS_WARN */
if (ngx_array_init(&entries, r->pool, 40,
sizeof(ngx_http_fancyindex_entry_t)) != NGX_OK)
return ngx_http_fancyindex_error(r, &dir, &path);
filename = path.data;
filename[path.len] = '/';
/* Read directory entries and their associated information. */
for (;;) {
ngx_set_errno(0);
if (ngx_read_dir(&dir) == NGX_ERROR) {
ngx_int_t err = ngx_errno;
if (err != NGX_ENOMOREFILES) {
ngx_log_error(NGX_LOG_CRIT, r->connection->log, err,
ngx_read_dir_n " \"%V\" failed", &path);
return ngx_http_fancyindex_error(r, &dir, &path);
}
break;
}
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
"http fancyindex file: \"%s\"", ngx_de_name(&dir));
len = ngx_de_namelen(&dir);
if (!alcf->show_dot_files && ngx_de_name(&dir)[0] == '.')
continue;
if (alcf->hide_symlinks && ngx_de_is_link (&dir))
continue;
#if NGX_PCRE
{
ngx_str_t str;
str.len = len;
str.data = ngx_de_name(&dir);
if (alcf->ignore && ngx_regex_exec_array(alcf->ignore, &str,
r->connection->log)
!= NGX_DECLINED)
{
continue;
}
}
#else /* !NGX_PCRE */
if (alcf->ignore) {
u_int match_found = 0;
ngx_str_t *s = alcf->ignore->elts;
for (i = 0; i < alcf->ignore->nelts; i++, s++) {
if (ngx_strcmp(ngx_de_name(&dir), s->data) == 0) {
match_found = 1;
break;
}
}
if (match_found) {
continue;
}
}
#endif /* NGX_PCRE */
if (!dir.valid_info) {
/* 1 byte for '/' and 1 byte for terminating '\0' */
if (path.len + 1 + len + 1 > allocated) {
allocated = path.len + 1 + len + 1
+ NGX_HTTP_FANCYINDEX_PREALLOCATE;
if ((filename = ngx_palloc(r->pool, allocated)) == NULL)
return ngx_http_fancyindex_error(r, &dir, &path);
last = ngx_cpystrn(filename, path.data, path.len + 1);
*last++ = '/';
}
ngx_cpystrn(last, ngx_de_name(&dir), len + 1);
if (ngx_de_info(filename, &dir) == NGX_FILE_ERROR) {
ngx_int_t err = ngx_errno;
if (err != NGX_ENOENT) {
ngx_log_error(NGX_LOG_ERR, r->connection->log, err,
ngx_de_info_n " \"%s\" failed", filename);
continue;
}
if (ngx_de_link_info(filename, &dir) == NGX_FILE_ERROR) {
ngx_log_error(NGX_LOG_CRIT, r->connection->log, ngx_errno,
ngx_de_link_info_n " \"%s\" failed", filename);
return ngx_http_fancyindex_error(r, &dir, &path);
}
}
}
if ((entry = ngx_array_push(&entries)) == NULL)
return ngx_http_fancyindex_error(r, &dir, &path);
entry->name.len = len;
entry->name.data = ngx_palloc(r->pool, len + 1);
if (entry->name.data == NULL)
return ngx_http_fancyindex_error(r, &dir, &path);
ngx_cpystrn(entry->name.data, ngx_de_name(&dir), len + 1);
entry->escape = 2 * ngx_fancyindex_escape_filename(NULL,
ngx_de_name(&dir),
len);
entry->escape_html = ngx_escape_html(NULL,
entry->name.data,
entry->name.len);
entry->dir = ngx_de_is_dir(&dir);
entry->mtime = ngx_de_mtime(&dir);
entry->size = ngx_de_size(&dir);
entry->utf_len = (r->headers_out.charset.len == 5 &&
ngx_strncasecmp(r->headers_out.charset.data, (u_char*) "utf-8", 5) == 0)
? ngx_utf8_length(entry->name.data, entry->name.len)
: len;
}
if (ngx_close_dir(&dir) == NGX_ERROR) {
ngx_log_error(NGX_LOG_ALERT, r->connection->log, ngx_errno,
ngx_close_dir_n " \"%s\" failed", &path);
}
/*
* Calculate needed buffer length.
*/
escape_html = ngx_escape_html(NULL, r->uri.data, r->uri.len);
if (alcf->show_path)
len = r->uri.len + escape_html
+ ngx_sizeof_ssz(t05_body2)
+ ngx_sizeof_ssz(t06_list1)
+ ngx_sizeof_ssz(t_parentdir_entry)
+ ngx_sizeof_ssz(t07_list2)
+ ngx_fancyindex_timefmt_calc_size (&alcf->time_format) * entries.nelts
;
else
len = r->uri.len + escape_html
+ ngx_sizeof_ssz(t06_list1)
+ ngx_sizeof_ssz(t_parentdir_entry)
+ ngx_sizeof_ssz(t07_list2)
+ ngx_fancyindex_timefmt_calc_size (&alcf->time_format) * entries.nelts
;
/*
* If we are a the root of the webserver (URI = "/" --> length of 1),
* do not display the "Parent Directory" link.
*/
if (r->uri.len == 1) {
len -= ngx_sizeof_ssz(t_parentdir_entry);
}
entry = entries.elts;
for (i = 0; i < entries.nelts; i++) {
/*
* Genearated table rows are as follows, unneeded whitespace
* is stripped out:
*
* <tr>
* <td><a href="U[?sort]">fname</a></td>
* <td>size</td><td>date</td>
* </tr>
*/
len += ngx_sizeof_ssz("<tr><td colspan=\"2\" class=\"link\"><a href=\"")
+ entry[i].name.len + entry[i].escape /* Escaped URL */
+ ngx_sizeof_ssz("?C=x&O=y") /* URL sorting arguments */
+ ngx_sizeof_ssz("\" title=\"")
+ entry[i].name.len + entry[i].utf_len + entry[i].escape_html
+ ngx_sizeof_ssz("\">")
+ entry[i].name.len + entry[i].utf_len + entry[i].escape_html
+ ngx_sizeof_ssz("</a></td><td class=\"size\">")
+ 20 /* File size */
+ ngx_sizeof_ssz("</td><td class=\"date\">") /* Date prefix */
+ ngx_sizeof_ssz("</td></tr>\n") /* Date suffix */
+ 2 /* CR LF */
;
}
if ((b = ngx_create_temp_buf(r->pool, len)) == NULL)
return NGX_HTTP_INTERNAL_SERVER_ERROR;
/*
* Determine the sorting criteria. URL arguments look like:
*
* C=x[&O=y]
*
* Where x={M,S,N} and y={A,D}
*/
if ((r->args.len == 3 || (r->args.len == 7 && r->args.data[3] == '&')) &&
r->args.data[0] == 'C' && r->args.data[1] == '=')
{
/* Determine whether the direction of the sorting */
ngx_int_t sort_descending = r->args.len == 7
&& r->args.data[4] == 'O'
&& r->args.data[5] == '='
&& r->args.data[6] == 'D';
/* Pick the sorting criteria */
switch (r->args.data[2]) {
case 'M': /* Sort by mtime */
if (sort_descending) {
sort_cmp_func = ngx_http_fancyindex_cmp_entries_mtime_desc;
if (alcf->default_sort != NGX_HTTP_FANCYINDEX_SORT_CRITERION_DATE_DESC)
sort_url_args = "?C=M&O=D";
}
else {
sort_cmp_func = ngx_http_fancyindex_cmp_entries_mtime_asc;
if (alcf->default_sort != NGX_HTTP_FANCYINDEX_SORT_CRITERION_DATE)
sort_url_args = "?C=M&O=A";
}
break;
case 'S': /* Sort by size */
if (sort_descending) {
sort_cmp_func = ngx_http_fancyindex_cmp_entries_size_desc;
if (alcf->default_sort != NGX_HTTP_FANCYINDEX_SORT_CRITERION_SIZE_DESC)
sort_url_args = "?C=S&O=D";
}
else {
sort_cmp_func = ngx_http_fancyindex_cmp_entries_size_asc;
if (alcf->default_sort != NGX_HTTP_FANCYINDEX_SORT_CRITERION_SIZE)
sort_url_args = "?C=S&O=A";
}
break;
case 'N': /* Sort by name */
default:
if (sort_descending) {
sort_cmp_func = ngx_http_fancyindex_cmp_entries_name_desc;
if (alcf->default_sort != NGX_HTTP_FANCYINDEX_SORT_CRITERION_NAME_DESC)
sort_url_args = "?C=N&O=D";
}
else {
sort_cmp_func = ngx_http_fancyindex_cmp_entries_name_asc;
if (alcf->default_sort != NGX_HTTP_FANCYINDEX_SORT_CRITERION_NAME)
sort_url_args = "?C=N&O=A";
}
break;
}
}
else {
switch (alcf->default_sort) {
case NGX_HTTP_FANCYINDEX_SORT_CRITERION_DATE_DESC:
sort_cmp_func = ngx_http_fancyindex_cmp_entries_mtime_desc;
break;
case NGX_HTTP_FANCYINDEX_SORT_CRITERION_DATE:
sort_cmp_func = ngx_http_fancyindex_cmp_entries_mtime_asc;
break;
case NGX_HTTP_FANCYINDEX_SORT_CRITERION_SIZE_DESC:
sort_cmp_func = ngx_http_fancyindex_cmp_entries_size_desc;
break;
case NGX_HTTP_FANCYINDEX_SORT_CRITERION_SIZE:
sort_cmp_func = ngx_http_fancyindex_cmp_entries_size_asc;
break;
case NGX_HTTP_FANCYINDEX_SORT_CRITERION_NAME_DESC:
sort_cmp_func = ngx_http_fancyindex_cmp_entries_name_desc;
break;
case NGX_HTTP_FANCYINDEX_SORT_CRITERION_NAME:
default:
sort_cmp_func = ngx_http_fancyindex_cmp_entries_name_asc;
break;
}
}
/* Sort entries, if needed */
if (entries.nelts > 1) {
if (alcf->dirs_first)
{
ngx_http_fancyindex_entry_t *l, *r;
l = entry;
r = entry + entries.nelts - 1;
while (l < r)
{
while (l < r && l->dir)
l++;