#include "cgi.h" #include "stdinc.h" void content_type(char *type) { printf("Content-type: %s\r\n\r\n", type); } void *param_add(param_t *list, char *name, char *value) { param_t *cursor = list; if (name == NULL || value == NULL) return list; if (cursor == NULL) { cursor = calloc(1, sizeof(param_t)); cursor->name = strdup(name); cursor->value = strdup(value); html_escape(cursor->value); cursor->next = NULL; } for (cursor = list; cursor->next; cursor = cursor->next); if (cursor->next == NULL) { cursor->next = calloc(1, sizeof(param_t)); cursor = cursor->next; cursor->name = strdup(name); cursor->value = strdup(value); html_escape(cursor->value); cursor->next = NULL; } else bork("Should not be here!"); return list; } char *html_escape(char *string) { char *p = string; int i; char *hex[] = {"A", "B", "C", "D", "E", "F"}; char *again = p; for (i = 10; i < 255; i++) { p = again; char esc[6] = { 0 }; char res[6] = { 0 }; sprintf(esc, "%%%x", i); sprintf(res, "%c", i); char *pos = NULL; while ((pos = strstr(p, esc)) != NULL) { if (pos) { memmove(pos, pos + 1 + strlen(res), strlen(pos)); *pos = (char) res[0]; } } p = again; int x; for (x = 1; x < 9; x++) { int y; for (y = 0; y < 6; y++) { sprintf(esc, "%%%d%s", x, hex[y]); sprintf(res, "%d%s", x, hex[y]); while ((pos = strstr(p, esc)) != NULL) { memmove(pos, pos + strlen(res), strlen(pos)); *pos = (char) strtol(res, (char **) NULL, 16); } } } while ((pos = strstr(p, "+")) != NULL) *pos = ' '; } return string; } char *param(char *name) { param_t *cursor = _params->next; while (cursor) { if (!(strcmp(cursor->name, name))) return strdup(cursor->value); cursor = cursor->next; } return NULL; } void param_free(param_t *list) { while (list) { param_t *next = list->next; free(list->name); free(list->value); free(list); list = next; } } void *get_params(void) { _params = calloc(1, sizeof(param_t)); int post = 0; char *method = getenv("REQUEST_METHOD"); if (method == NULL) return NULL; else if (!strcmp(method, "POST") || !strcmp(method, "GET")) { if (!strcmp(method, "POST")) post = 1; char *buf; char *p; if (post) { char *length = getenv("CONTENT_LENGTH"); int bytes = atoi(length); if (bytes == 0) bork("CONTENT_LENGTH is zero"); buf = calloc(1, bytes); size_t len = read(fileno(stdin), buf, bytes); buf[len] = '\0'; } else buf = strdup(getenv("QUERY_STRING")); if (strlen(buf) == 0) return NULL; p = buf; while (1) { char *start = p; p = strchr(start, '='); *p = '\0'; char *name = strdup(start); p++; char *end = strchr(p, '&'); if (end != NULL) *end = '\0'; char *value = strdup(p); _params = param_add(_params, name, value); if (end == NULL) break; else p = end + 1; } } return _params; }