simplefiles

A lightweight C CGI web application for managing files.
git clone https://scm.kuandu.systems/git-raw/simplefiles.git
Log | Files | Refs | README | LICENSE

http.c (1343B)


      1 #include <assert.h>
      2 #include <stdio.h>
      3 #include <string.h>
      4 #include <unistd.h>
      5 
      6 #include "http.h"
      7 
      8 static int saved_stdout;
      9 
     10 static void
     11 capture_stdout(FILE *fp)
     12 {
     13 	saved_stdout = dup(STDOUT_FILENO);
     14 	assert(saved_stdout != -1);
     15 
     16 	assert(dup2(fileno(fp), STDOUT_FILENO) != -1);
     17 }
     18 
     19 static void
     20 restore_stdout(void)
     21 {
     22 	assert(dup2(saved_stdout, STDOUT_FILENO) != -1);
     23 	close(saved_stdout);
     24 }
     25 
     26 static void
     27 test_valid_filename(void)
     28 {
     29 	FILE *fp;
     30 	char buffer[1024];
     31 	size_t n;
     32 
     33 	fp = tmpfile();
     34 	assert(fp != NULL);
     35 
     36 	capture_stdout(fp);
     37 
     38 	assert(download_headers("hello.txt", 123) == 0);
     39 
     40 	fflush(stdout);
     41 	rewind(fp);
     42 
     43 	n = fread(buffer, 1, sizeof(buffer) - 1, fp);
     44 	buffer[n] = '\0';
     45 
     46 	restore_stdout();
     47 
     48 	assert(strstr(buffer,
     49 	    "Content-Disposition: attachment; filename=\"hello.txt\"\r\n")
     50 	    != NULL);
     51 
     52 	assert(strstr(buffer, "Content-Length: 123\r\n") != NULL);
     53 
     54 	fclose(fp);
     55 
     56 	printf("ok: valid download headers\n");
     57 }
     58 
     59 static void
     60 test_reject_cr(void)
     61 {
     62 	assert(download_headers("hello\r\nX-Injected: yes", 123) == -1);
     63 
     64 	printf("ok: reject CR in filename\n");
     65 }
     66 
     67 static void
     68 test_reject_lf(void)
     69 {
     70 	assert(download_headers("hello\nX-Injected: yes", 123) == -1);
     71 
     72 	printf("ok: reject LF in filename\n");
     73 }
     74 
     75 int
     76 main(void)
     77 {
     78 	test_valid_filename();
     79 	test_reject_cr();
     80 	test_reject_lf();
     81 
     82 	printf("all tests passed\n");
     83 
     84 	return 0;
     85 }