It's 2022 ... updating all of the copyright notices in webcit-ng
[citadel.git] / webcit-ng / static.c
1 // Output static content
2 //
3 // Copyright (c) 1996-2022 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 static content.
19 void output_static(struct http_transaction *h) {
20         char filename[PATH_MAX];
21         struct stat statbuf;
22
23         if (!strncasecmp(h->url, "/ctdl/s/", 8)) {
24                 snprintf(filename, sizeof filename, "static/%s", &h->url[8]);
25         }
26         else if (!strncasecmp(h->url, "/.well-known/", 13)) {
27                 snprintf(filename, sizeof filename, "static/.well-known/%s", &h->url[13]);
28         }
29         else {
30                 do_404(h);
31                 return;
32         }
33
34         if (strstr(filename, "../")) {          // 100% guaranteed attacker.
35                 do_404(h);                      // Die in a car fire.
36                 return;
37         }
38
39         FILE *fp = fopen(filename, "r");        // Try to open the requested file.
40         if (fp == NULL) {
41                 syslog(LOG_DEBUG, "%s: %s", filename, strerror(errno));
42                 do_404(h);
43                 return;
44         }
45
46         fstat(fileno(fp), &statbuf);
47         h->response_body_length = statbuf.st_size;
48         h->response_body = malloc(h->response_body_length);
49         if (h->response_body != NULL) {
50                 fread(h->response_body, h->response_body_length, 1, fp);
51         }
52         else {
53                 h->response_body_length = 0;
54         }
55         fclose(fp);                             // Content is now in memory.
56
57         h->response_code = 200;
58         h->response_string = strdup("OK");
59         add_response_header(h, strdup("Content-type"), strdup(GuessMimeByFilename(filename, strlen(filename))));
60
61         char *datestring = http_datestring(statbuf.st_mtime);
62         if (datestring) {
63                 add_response_header(h, strdup("Last-Modified"), datestring);
64         }
65 }