bunkum

an old and silly c99 web server with some fun features
Log | Files | Refs | README

response.c (1912B)


      1 #include <stddef.h>
      2 #include <string.h>
      3 #include <stdlib.h>
      4 #include <stdio.h>
      5 
      6 #include "../utils/log.h"
      7 #include "../utils/hashmap.h"
      8 #include "../utils/time.h"
      9 #include "response.h"
     10 
     11 response_t __resp_new(enum StatusCode code, char* code_name) {
     12 	response_t resp;
     13 	memset(resp.header, 0, 512);
     14 	sprintf(resp.header, "HTTP/1.1 %d %s\r\n", code, code_name);
     15 
     16 	resp_add_hdr(&resp, "Server", "Bunkum/0.0.1");
     17 
     18 	char datebuf[32];
     19 	time_to_str(time(0), datebuf);
     20 	resp_add_hdr(&resp, "Date", datebuf);
     21 
     22 	return resp;
     23 }
     24 
     25 void resp_add_hdr(response_t* r, char* hdr, char* val) {
     26 	char header[64];
     27 	sprintf(header, "%s: %s\r\n", hdr, val);
     28 	strcat(r->header, header);
     29 }
     30 
     31 void resp_add_content(response_t* r, char* content, size_t content_len) {
     32 	char length[32];
     33 	sprintf(length, "%ld", content_len);
     34 	resp_add_hdr(r, "Content-Length", length);
     35 
     36 	strcat(r->header, "\r\n");
     37 	size_t header_len = strlen(r->header);
     38 
     39 	r->sz = strlen(r->header)+content_len;
     40 	r->content = malloc(r->sz);
     41 	strcpy(r->content, r->header);
     42 	memcpy(r->content+header_len, content, content_len);
     43 }
     44 
     45 const char* exts[] = {
     46   "html", "css", "js", "png", "gif", "jpeg", "svg", "ttf",
     47   "woff", "woff2", "pdf", "csv", "gz", "tar", "zip", "json", NULL
     48 }; // TODO sentinel sketchy
     49 
     50 const char* mtypes[] = {
     51   "text/html", "text/css", "text/javascript", "image/png", "image/gif",
     52   "image/jpeg", "image/svg+xml", "font/ttf", "font/woff", "font/woff2",
     53   "application/pdf", "text/csv", "application/gzip",  "application/x-tar",
     54   "application/zip", "application/json"
     55 };
     56 
     57 const char* ext_to_mtype(char* ext) {
     58 	if (ext == NULL) return"text/plain";
     59 
     60 	for (size_t i = 0; exts[i] != NULL; i++) {
     61 		if (strcmp(ext, exts[i]) == 0) return mtypes[i];
     62 	}
     63 
     64 	log_warn("Giving up on mapping %s extension to a MIME type!", ext);
     65 	return "text/plain";
     66 }
     67 
     68 void resp_set_ctype(response_t* r, char* ext) {
     69 	resp_add_hdr(r, "Content-Type", (char*)ext_to_mtype(ext));
     70 }