Initial public busybox upstream commit
[busybox4maemo] / networking / httpd_indexcgi.c
1 /*
2  * Copyright (c) 2007 Denys Vlasenko <vda.linux@googlemail.com>
3  *
4  * Licensed under GPLv2, see file LICENSE in this tarball for details.
5  */
6
7 /*
8  * This program is a CGI application. It outputs directory index page.
9  * Put it into cgi-bin/index.cgi and chmod 0755.
10  */
11
12 /* Build a-la
13 i486-linux-uclibc-gcc \
14 -static -static-libgcc \
15 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 \
16 -Wall -Wshadow -Wwrite-strings -Wundef -Wstrict-prototypes -Werror \
17 -Wold-style-definition -Wdeclaration-after-statement -Wno-pointer-sign \
18 -Wmissing-prototypes -Wmissing-declarations \
19 -Os -fno-builtin-strlen -finline-limit=0 -fomit-frame-pointer \
20 -ffunction-sections -fdata-sections -fno-guess-branch-probability \
21 -funsigned-char \
22 -falign-functions=1 -falign-jumps=1 -falign-labels=1 -falign-loops=1 \
23 -march=i386 -mpreferred-stack-boundary=2 \
24 -Wl,-Map -Wl,link.map -Wl,--warn-common -Wl,--sort-common -Wl,--gc-sections \
25 httpd_indexcgi.c -o index.cgi
26 */
27
28 /* We don't use printf, as it pulls in >12 kb of code from uclibc (i386). */
29 /* Currently malloc machinery is the biggest part of libc we pull in. */
30 /* We have only one realloc and one strdup, any idea how to do without? */
31 /* Size (i386, approximate):
32  *   text    data     bss     dec     hex filename
33  *  13036      44    3052   16132    3f04 index.cgi
34  *   2576       4    2048    4628    1214 index.cgi.o
35  */
36
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <errno.h>
40 #include <stdint.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <stdio.h>
45 #include <dirent.h>
46 #include <time.h>
47
48 /* Appearance of the table is controlled by style sheet *ONLY*,
49  * formatting code uses <TAG class=CLASS> to apply style
50  * to elements. Edit stylesheet to your liking and recompile. */
51
52 #define STYLE_STR \
53 "<style>"                                               "\n"\
54 "table {"                                               "\n"\
55   "width:100%;"                                         "\n"\
56   "background-color:#fff5ee;"                           "\n"\
57   "border-width:1px;" /* 1px 1px 1px 1px; */            "\n"\
58   "border-spacing:2px;"                                 "\n"\
59   "border-style:solid;" /* solid solid solid solid; */  "\n"\
60   "border-color:black;" /* black black black black; */  "\n"\
61   "border-collapse:collapse;"                           "\n"\
62 "}"                                                     "\n"\
63 "th {"                                                  "\n"\
64   "border-width:1px;" /* 1px 1px 1px 1px; */            "\n"\
65   "padding:1px;" /* 1px 1px 1px 1px; */                 "\n"\
66   "border-style:solid;" /* solid solid solid solid; */  "\n"\
67   "border-color:black;" /* black black black black; */  "\n"\
68 "}"                                                     "\n"\
69 "td {"                                                  "\n"\
70              /* top right bottom left */                    \
71   "border-width:0px 1px 0px 1px;"                       "\n"\
72   "padding:1px;" /* 1px 1px 1px 1px; */                 "\n"\
73   "border-style:solid;" /* solid solid solid solid; */  "\n"\
74   "border-color:black;" /* black black black black; */  "\n"\
75   "white-space:nowrap;"                                 "\n"\
76 "}"                                                     "\n"\
77 "tr.hdr { background-color:#eee5de; }"                  "\n"\
78 "tr.o { background-color:#ffffff; }"                    "\n"\
79 /* tr.e { ... } - for even rows (currently none) */         \
80 "tr.foot { background-color:#eee5de; }"                 "\n"\
81 "th.cnt { text-align:left; }"                           "\n"\
82 "th.sz { text-align:right; }"                           "\n"\
83 "th.dt { text-align:right; }"                           "\n"\
84 "td.sz { text-align:right; }"                           "\n"\
85 "td.dt { text-align:right; }"                           "\n"\
86 "col.nm { width:98%; }"                                 "\n"\
87 "col.sz { width:1%; }"                                  "\n"\
88 "col.dt { width:1%; }"                                  "\n"\
89 "</style>"                                              "\n"\
90
91 typedef struct dir_list_t {
92         char  *dl_name;
93         mode_t dl_mode;
94         off_t  dl_size;
95         time_t dl_mtime;
96 } dir_list_t;
97
98 static int compare_dl(dir_list_t *a, dir_list_t *b)
99 {
100         /* ".." is 'less than' any other dir entry */
101         if (strcmp(a->dl_name, "..") == 0) {
102                 return -1;
103         }
104         if (strcmp(b->dl_name, "..") == 0) {
105                 return 1;
106         }
107         if (S_ISDIR(a->dl_mode) != S_ISDIR(b->dl_mode)) {
108                 /* 1 if b is a dir (and thus a is 'after' b, a > b),
109                  * else -1 (a < b) */
110                 return (S_ISDIR(b->dl_mode) != 0) ? 1 : -1;
111         }
112         return strcmp(a->dl_name, b->dl_name);
113 }
114
115 static char buffer[2*1024 > sizeof(STYLE_STR) ? 2*1024 : sizeof(STYLE_STR)];
116 static char *dst = buffer;
117 enum {
118         BUFFER_SIZE = sizeof(buffer),
119         HEADROOM = 64,
120 };
121
122 /* After this call, you have at least size + HEADROOM bytes available
123  * ahead of dst */
124 static void guarantee(int size)
125 {
126         if (buffer + (BUFFER_SIZE-HEADROOM) - dst >= size)
127                 return;
128         write(1, buffer, dst - buffer);
129         dst = buffer;
130 }
131
132 /* NB: formatters do not store terminating NUL! */
133
134 /* HEADROOM bytes are available after dst after this call */
135 static void fmt_str(/*char *dst,*/ const char *src)
136 {
137         unsigned len = strlen(src);
138         guarantee(len);
139         memcpy(dst, src, len);
140         dst += len;
141 }
142
143 /* HEADROOM bytes after dst are available after this call */
144 static void fmt_url(/*char *dst,*/ const char *name)
145 {
146         while (*name) {
147                 unsigned c = *name++;
148                 guarantee(3);
149                 *dst = c;
150                 if ((c - '0') > 9 /* not a digit */
151                  && ((c|0x20) - 'a') > 26 /* not A-Z or a-z */
152                  && !strchr("._-+@", c)
153                 ) {
154                         *dst++ = '%';
155                         *dst++ = "0123456789ABCDEF"[c >> 4];
156                         *dst = "0123456789ABCDEF"[c & 0xf];
157                 }
158                 dst++;
159         }
160 }
161
162 /* HEADROOM bytes are available after dst after this call */
163 static void fmt_html(/*char *dst,*/ const char *name)
164 {
165         while (*name) {
166                 char c = *name++;
167                 if (c == '<')
168                         fmt_str("&lt;");
169                 else if (c == '>')
170                         fmt_str("&gt;");
171                 else if (c == '&') {
172                         fmt_str("&amp;");
173                 } else {
174                         guarantee(1);
175                         *dst++ = c;
176                         continue;
177                 }
178         }
179 }
180
181 /* HEADROOM bytes are available after dst after this call */
182 static void fmt_ull(/*char *dst,*/ unsigned long long n)
183 {
184         char buf[sizeof(n)*3 + 2];
185         char *p;
186
187         p = buf + sizeof(buf) - 1;
188         *p = '\0';
189         do {
190                 *--p = (n % 10) + '0';
191                 n /= 10;
192         } while (n);
193         fmt_str(/*dst,*/ p);
194 }
195
196 /* Does not call guarantee - eats into headroom instead */
197 static void fmt_02u(/*char *dst,*/ unsigned n)
198 {
199         /* n %= 100; - not needed, callers don't pass big n */
200         dst[0] = (n / 10) + '0';
201         dst[1] = (n % 10) + '0';
202         dst += 2;
203 }
204
205 /* Does not call guarantee - eats into headroom instead */
206 static void fmt_04u(/*char *dst,*/ unsigned n)
207 {
208         /* n %= 10000; - not needed, callers don't pass big n */
209         fmt_02u(n / 100);
210         fmt_02u(n % 100);
211 }
212
213 int main(void)
214 {
215         dir_list_t *dir_list;
216         dir_list_t *cdir;
217         unsigned dir_list_count;
218         unsigned count_dirs;
219         unsigned count_files;
220         unsigned long long size_total;
221         int odd;
222         DIR *dirp;
223         char *QUERY_STRING;
224
225         QUERY_STRING = getenv("QUERY_STRING");
226         if (!QUERY_STRING
227          || QUERY_STRING[0] != '/'
228          || strstr(QUERY_STRING, "/../")
229          || strcmp(strrchr(QUERY_STRING, '/'), "/..") == 0
230         ) {
231                 return 1;
232         }
233
234         if (chdir("..")
235          || (QUERY_STRING[1] && chdir(QUERY_STRING + 1))
236         ) {
237                 return 1;
238         }
239
240         dirp = opendir(".");
241         if (!dirp)
242                 return 1;
243         dir_list = NULL;
244         dir_list_count = 0;
245         while (1) {
246                 struct dirent *dp;
247                 struct stat sb;
248
249                 dp = readdir(dirp);
250                 if (!dp)
251                         break;
252                 if (dp->d_name[0] == '.' && !dp->d_name[1])
253                         continue;
254                 if (stat(dp->d_name, &sb) != 0)
255                         continue;
256                 dir_list = realloc(dir_list, (dir_list_count + 1) * sizeof(dir_list[0]));
257                 dir_list[dir_list_count].dl_name = strdup(dp->d_name);
258                 dir_list[dir_list_count].dl_mode = sb.st_mode;
259                 dir_list[dir_list_count].dl_size = sb.st_size;
260                 dir_list[dir_list_count].dl_mtime = sb.st_mtime;
261                 dir_list_count++;
262         }
263         closedir(dirp);
264
265         qsort(dir_list, dir_list_count, sizeof(dir_list[0]), (void*)compare_dl);
266
267         fmt_str(
268                 "" /* Additional headers (currently none) */
269                 "\r\n" /* Mandatory empty line after headers */
270                 "<html><head><title>Index of ");
271         /* Guard against directories with &, > etc */
272         fmt_html(QUERY_STRING);
273         fmt_str(
274                 "</title>\n"
275                 STYLE_STR
276                 "</head>" "\n"
277                 "<body>" "\n"
278                 "<h1>Index of ");
279         fmt_html(QUERY_STRING);
280         fmt_str(
281                 "</h1>" "\n"
282                 "<table>" "\n"
283                 "<col class=nm><col class=sz><col class=dt>" "\n"
284                 "<tr class=hdr><th class=cnt>Name<th class=sz>Size<th class=dt>Last modified" "\n");
285
286         odd = 0;
287         count_dirs = 0;
288         count_files = 0;
289         size_total = 0;
290         cdir = dir_list;
291         while (dir_list_count--) {
292                 struct tm *tm;
293
294                 if (S_ISDIR(cdir->dl_mode)) {
295                         count_dirs++;
296                 } else if (S_ISREG(cdir->dl_mode)) {
297                         count_files++;
298                         size_total += cdir->dl_size;
299                 } else
300                         goto next;
301
302                 fmt_str("<tr class=");
303                 *dst++ = (odd ? 'o' : 'e');
304                 fmt_str("><td class=nm><a href='");
305                 fmt_url(cdir->dl_name); /* %20 etc */
306                 if (S_ISDIR(cdir->dl_mode))
307                         *dst++ = '/';
308                 fmt_str("'>");
309                 fmt_html(cdir->dl_name); /* &lt; etc */
310                 if (S_ISDIR(cdir->dl_mode))
311                         *dst++ = '/';
312                 fmt_str("</a><td class=sz>");
313                 if (S_ISREG(cdir->dl_mode))
314                         fmt_ull(cdir->dl_size);
315                 fmt_str("<td class=dt>");
316                 tm = gmtime(&cdir->dl_mtime);
317                 fmt_04u(1900 + tm->tm_year); *dst++ = '-';
318                 fmt_02u(tm->tm_mon + 1); *dst++ = '-';
319                 fmt_02u(tm->tm_mday); *dst++ = ' ';
320                 fmt_02u(tm->tm_hour); *dst++ = ':';
321                 fmt_02u(tm->tm_min); *dst++ = ':';
322                 fmt_02u(tm->tm_sec);
323                 *dst++ = '\n';
324
325                 odd = 1 - odd;
326  next:
327                 cdir++;
328         }
329
330         fmt_str("<tr class=foot><th class=cnt>Files: ");
331         fmt_ull(count_files);
332         /* count_dirs - 1: we don't want to count ".." */
333         fmt_str(", directories: ");
334         fmt_ull(count_dirs - 1);
335         fmt_str("<th class=sz>");
336         fmt_ull(size_total);
337         fmt_str("<th class=dt>\n");
338         /* "</table></body></html>" - why bother? */
339         guarantee(BUFFER_SIZE * 2); /* flush */
340
341         return 0;
342 }