beautiful
[citadel.git] / webcit-ng / static.c
1 // Output static content
2 //
3 // Copyright (c) 1996-2021 by the citadel.org team
4 //
5 // This program is open source software.  It runs great on the
6 // Linux operating system (and probably elsewhere).  You can use,
7 // copy, and run it under the terms of the GNU General Public
8 // License version 3.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14
15 #include "webcit.h"
16
17
18 // Called from perform_request() to handle the /ctdl/s/ prefix -- always static content.
19 void output_static(struct http_transaction *h) {
20         char filename[PATH_MAX];
21         struct stat statbuf;
22
23         snprintf(filename, sizeof filename, "static/%s", &h->url[8]);
24
25         if (strstr(filename, "../")) {          // 100% guaranteed attacker.
26                 do_404(h);                      // Die in a car fire.
27                 return;
28         }
29
30         FILE *fp = fopen(filename, "r");        // Try to open the requested file.
31         if (fp == NULL) {
32                 do_404(h);
33                 return;
34         }
35
36         fstat(fileno(fp), &statbuf);
37         h->response_body_length = statbuf.st_size;
38         h->response_body = malloc(h->response_body_length);
39         if (h->response_body != NULL) {
40                 fread(h->response_body, h->response_body_length, 1, fp);
41         }
42         else {
43                 h->response_body_length = 0;
44         }
45         fclose(fp);                             // Content is now in memory.
46
47         h->response_code = 200;
48         h->response_string = strdup("OK");
49         add_response_header(h, strdup("Content-type"), strdup(GuessMimeByFilename(filename, strlen(filename))));
50
51         char *datestring = http_datestring(statbuf.st_mtime);
52         if (datestring) {
53                 add_response_header(h, strdup("Last-Modified"), datestring);
54         }
55 }