util.c (1724B)
1 /* This work is in the public domain. See COPYING file for details. */ 2 3 extern int header_sent; 4 5 #include <errno.h> 6 #include <stdarg.h> 7 #include <stdio.h> 8 #include <stdlib.h> 9 #include <string.h> 10 11 #include "util.h" 12 13 void 14 fatal(const char *fmt, ...) 15 { 16 va_list ap; 17 18 if (!header_sent) { 19 puts("Content-Type: text/html\r"); 20 puts("Status: 200 OK\r"); 21 puts("\r"); 22 header_sent = TRUE; 23 } 24 25 fputs("ERROR: ", stdout); 26 va_start(ap, fmt); 27 vfprintf(stdout, fmt, ap); 28 va_end(ap); 29 30 if (fmt[0] && fmt[strlen(fmt)-1] == ':') { 31 fprintf(stdout, " %s\n", strerror(errno)); 32 } else { 33 fprintf(stdout, "\n"); 34 } 35 36 exit(1); 37 } 38 39 void * 40 emalloc(size_t size) 41 { 42 void *p; 43 if ((p = malloc(size)) == NULL) 44 fatal("malloc:"); 45 return p; 46 } 47 48 void * 49 ecalloc(size_t nmemb, size_t size) 50 { 51 void *p; 52 if ((p = calloc(nmemb, size)) == NULL) 53 fatal("calloc:"); 54 return p; 55 } 56 57 void * 58 erealloc(void *ptr, size_t size) 59 { 60 void *p; 61 if ((p = realloc(ptr, size)) == NULL) 62 fatal("realloc:"); 63 return p; 64 } 65 66 FILE * 67 file_open(char *path) 68 { 69 FILE *f; 70 if ((f = fopen(path, "r")) == NULL) 71 fatal("%s:", path); 72 return f; 73 } 74 75 void 76 file_print(FILE *f, FILE *stream) 77 { 78 char c; 79 80 if (fseek(f, 0, SEEK_SET) == -1) 81 fatal("fseek:"); 82 83 while ((c = fgetc(f)) != EOF) { 84 fputc(c, stream); 85 } 86 } 87 88 void 89 file_close(FILE *f) 90 { 91 fclose(f); 92 } 93 94 void 95 parse_html_str(char *str) 96 { 97 char *x, *y, tmp; 98 99 x = y = str; 100 while (*y != '\0') { 101 if (*y == '%') { 102 if (*(y+1) == '\0' || *(y+2) == '\0') 103 fatal("parse_html_str: hex char missing"); 104 tmp = *(y+3); 105 *(y+3) = '\0'; 106 *x = strtol(y+1, NULL, 16); 107 if (*x != 13) /* ignore carriage return */ 108 x++; 109 *(y+3) = tmp; 110 y+=3; 111 } else { 112 if (*y == '+') 113 *y = ' '; 114 *x++ = *y++; 115 } 116 } 117 *x = '\0'; 118 }