1 /**
2 * This CGI program renders the oper.io blog
3 * Copyright (C) 2019 Aaron Ball <nullspoon@oper.io>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
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 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18 #include <stdio.h>
19 #include <stdlib.h>
20
21 #include "common.h"
22 #include "cgi.h"
23 #include "j2.h"
24
25
26 int main(int argc, char* argv[], char* envp[]) {
27 char buf[256];
28 char path[512];
29 int status = 200;
30
31 // Space for title assembly
32 char titlebuf[TITLE_MAX] = {'\0'};
33 char title[TITLE_MAX + 2] = {'\0'};
34
35 // Required environment variables
36 char* header = getenv("INDEX_HEADER");
37 char* footer = getenv("INDEX_FOOTER");
38 char* posts = getenv("INDEX_POSTS");
39
40 // List of supported query string key names
41 char* keys[] = {"q", "p", "title", "\0"};
42 // Parse the query string (if present)
43 struct querystring qs;
44 qs.qs = getenv("QUERY_STRING");
45 qs.pos = 0;
46
47 // If no title specified (return non-zero), default to "index"
48 if(cgi_qs_get_val(&qs, keys, buf) != 0)
49 strcpy(buf, "index");
50
51 // If the IP address was requested
52 if(strncmp(buf, "ip", 2) == 0) {
53 cgi_print_header("text/plain", 200);
54 printf("%s\n", cgi_remote_ip());
55 return 0;
56 }
57
58 // If the remote agent was requested
59 if(strncmp(buf, "agent", 5) == 0) {
60 cgi_print_header("text/plain", 200);
61 printf("%s\n", cgi_user_agent());
62 return 0;
63 }
64
65 // Assemble the page path
66 sprintf(path, "%s/%s.html", posts, buf);
67
68 // If the file does not exist, set status to 404 and set the page to be
69 // printed to the 404 page.
70 if(access(path, F_OK) != 0) {
71 status = 404;
72 sprintf(path, "%s/%s.html", posts, "404");
73 strcpy(title, ": 404");
74 }
75
76 // Anything below this gets printed. Make sure all variables are set and
77 // logic completed before here.
78 cgi_print_header("text/html", status);
79
80 // The specified page exists, attempt to read the title
81 html_read_title(path, titlebuf);
82 sprintf(title, "%s", titlebuf);
83 setenv("PAGE_TITLE", title, 1);
84
85 j2_cat(header);
86 j2_cat(path);
87 j2_cat(footer);
88 fflush(stdout);
89
90 return 0;
91 }
|