scan.c (1859B)
1 #include <stddef.h> 2 3 #include "scan.h" 4 5 #ifdef __cplusplus 6 extern "C" { 7 #endif 8 9 static int hdr_is_ws(unsigned char c) { 10 return c == ' ' || c == '\t' || c == '\r'; 11 } 12 13 static int hdr_lower(unsigned char c) { 14 if (c >= 'A' && c <= 'Z') return c + ('a' - 'A'); 15 return c; 16 } 17 18 // Case-insensitive literal match, bounded by remaining length. 19 static int hdr_match_word(const unsigned char *p, size_t left, const char *word) { 20 size_t i = 0; 21 while (word[i]) { 22 if (i >= left) return 0; 23 if (hdr_lower(p[i]) != (unsigned char)word[i]) return 0; 24 i++; 25 } 26 return 1; 27 } 28 29 int hdr_match_label(const unsigned char *line, size_t linelen, int *which, 30 const unsigned char **val, size_t *vallen) { 31 size_t i = 0; 32 int w = 0; 33 size_t wlen = 0; 34 35 while (i < linelen && hdr_is_ws(line[i])) i++; 36 37 if (hdr_match_word(line + i, linelen - i, "public-key")) { 38 w = 1; 39 wlen = 10; 40 } else if (hdr_match_word(line + i, linelen - i, "private-key")) { 41 w = 2; 42 wlen = 11; 43 } else { 44 return 0; 45 } 46 i += wlen; 47 48 while (i < linelen && hdr_is_ws(line[i])) i++; 49 if (i >= linelen || line[i] != ':') return 0; 50 i++; 51 52 while (i < linelen && hdr_is_ws(line[i])) i++; 53 54 *which = w; 55 *val = line + i; 56 *vallen = linelen - i; 57 while (*vallen > 0 && hdr_is_ws((*val)[*vallen - 1])) (*vallen)--; 58 return 1; 59 } 60 61 int hdr_next_line(const unsigned char **pos, const unsigned char *end, 62 const unsigned char **line, size_t *linelen) { 63 const unsigned char *nl; 64 if (*pos >= end) return 0; 65 *line = *pos; 66 nl = *pos; 67 while (nl < end && *nl != '\n') nl++; 68 *linelen = (size_t)(nl - *pos); 69 // Strip a trailing carriage return so CRLF streams parse cleanly 70 if (*linelen > 0 && (*pos)[*linelen - 1] == '\r') (*linelen)--; 71 *pos = (nl < end) ? nl + 1 : end; 72 return 1; 73 } 74 75 #ifdef __cplusplus 76 } // extern "C" 77 #endif