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 #include <unistd.h>
21
22 #include "common.h"
23 #include "cgi.h"
24 #include "j2.h"
25
26
27 int main(int argc, char* argv[], char* envp[]) {
28 char buf[256];
29 char path[512];
30 int status = 200;
31
32 // Space for title assembly
33 char titlebuf[TITLE_MAX] = {'\0'};
34 char title[TITLE_MAX + 2] = {'\0'};
35
36 // Required environment variables
37 char* header = getenv("INDEX_HEADER");
38 char* footer = getenv("INDEX_FOOTER");
39 char* posts = getenv("INDEX_POSTS");
40
41 // List of supported query string key names
42 char* keys[] = {"q", "p", "title", "\0"};
43 // Parse the query string (if present)
44 struct querystring qs;
45 qs.qs = getenv("QUERY_STRING");
46 qs.pos = 0;
47
48 // If no title specified (return non-zero), default to "index"
49 if(cgi_qs_get_val(&qs, keys, buf) != 0)
50 strcpy(buf, "index");
51
52 // If the IP address was requested
53 if(strncmp(buf, "ip", 2) == 0) {
54 cgi_print_header("text/plain", 200);
55 printf("%s\n", cgi_remote_ip());
56 return 0;
57 }
58
59 // If the remote agent was requested
60 if(strncmp(buf, "agent", 5) == 0) {
61 cgi_print_header("text/plain", 200);
62 printf("%s\n", cgi_user_agent());
63 return 0;
64 }
65
66 // Assemble the page path
67 sprintf(path, "%s/%s.html", posts, buf);
68
69 // If the file does not exist, set status to 404 and set the page to be
70 // printed to the 404 page.
71 if(access(path, F_OK) != 0) {
72 status = 404;
73 sprintf(path, "%s/%s.html", posts, "404");
74 strcpy(title, ": 404");
75 }
76
77 // Anything below this gets printed. Make sure all variables are set and
78 // logic completed before here.
79 cgi_print_header("text/html", status);
80
81 // The specified page exists, attempt to read the title
82 html_read_title(path, titlebuf);
83 sprintf(title, "%s", titlebuf);
84 setenv("PAGE_TITLE", title, 1);
85
86 j2_cat(header);
87 j2_cat(path);
88 j2_cat(footer);
89 fflush(stdout);
90
91 return 0;
92 }
|