summaryrefslogtreecommitdiff
path: root/src/cgi.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/cgi.c')
-rw-r--r--src/cgi.c97
1 files changed, 97 insertions, 0 deletions
diff --git a/src/cgi.c b/src/cgi.c
new file mode 100644
index 0000000..8aad33d
--- /dev/null
+++ b/src/cgi.c
@@ -0,0 +1,97 @@
+/**
+ * This CGI program renders the oper.io blog
+ * Copyright (C) 2019 Aaron Ball <nullspoon@oper.io>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "cgi.h"
+
+void cgi_print_header(char* ctype, int status) {
+ printf("Content-type: %s\n", ctype);
+ printf("Status: %d\n", status);
+ printf("\n");
+}
+
+char* cgi_remote_ip() {
+ if(getenv("HTTP_X_FORWARDED_FOR"))
+ return getenv("HTTP_X_FORWARDED_FOR");
+ else
+ return getenv("REMOTE_ADDR");
+ return NULL;
+}
+
+char* cgi_user_agent() {
+ if(getenv("HTTP_USER_AGENT"))
+ return getenv("HTTP_USER_AGENT");
+ return NULL;
+}
+
+
+int cgi_read_qs(struct querystring* q, char* buf) {
+ // If query string is null, probably env var isn't set
+ if(!q->qs)
+ return EOF;
+
+ int i = q->pos;
+ while(q->qs[i] != '\0' && i < QS_MAX) {
+ if(q->qs[i] == '=' || q->qs[i] == '&')
+ break;
+ i++;
+ }
+
+ // Copy section into buffer
+ strncpy(buf, &q->qs[q->pos], i - q->pos);
+ buf[i - q->pos] = '\0';
+
+ // Advance start position to i + 1 to skip the current delimiter
+ q->pos = i + 1;
+
+ if(q->qs[i] == '\0')
+ return EOF;
+
+ return 0;
+}
+
+
+/**
+ * cgi_qs_get_val:
+ * Gets the value of the first occurrence of the requested key. Supports more
+ * than one key to allow for easy backwards compatibility without re-traversing
+ * the query string.
+ *
+ * @qs Query string struct
+ * @keys Array of character arrays containing the query string keys
+ * @out Output buffer
+ *
+ * Returns 0 on success, and -1 on failure
+ */
+int cgi_qs_get_val(struct querystring* qs, char** keys, char* out) {
+ int i = 0;
+ int res = 0;
+ char buf[256];
+
+ while((res = cgi_read_qs(qs, buf)) != EOF) {
+ while(keys[i][0] != '\0') {
+ if(strcmp(buf, keys[i]) == 0) {
+ if(res == EOF)
+ return -1;
+ cgi_read_qs(qs, out);
+ return 0;
+ }
+ i++;
+ }
+ }
+ return -1;
+}
+

Generated by cgit