urldecode.c (655B)
1 /* 2 * Copyright 2021 Jacob R. Edwards 3 * Decode URI Percent Encoding (See RFC 2396, Section 2.4.1., "Escaped Encoding") 4 */ 5 6 #include <stdio.h> 7 #include <stdlib.h> 8 9 int 10 main(void) 11 { 12 char *b; 13 size_t l; 14 size_t s; 15 char o[3]; 16 int p; 17 unsigned char c; 18 char *e; 19 20 o[2] = 0; 21 b = NULL; 22 s = 0; 23 while ((l = getdelim(&b, &s, '%', stdin)) != -1) { 24 if (b[l - 1] == '%') { 25 --l; 26 if (fread(o, 1, 2, stdin) != 2) 27 goto badescape; 28 c = strtoul(o, &e, 16); 29 if (*e) { 30 badescape: 31 perror("bad escape"); 32 return 1; 33 } 34 p = 1; 35 } else 36 p = 0; 37 if (fwrite(b, 1, l, stdout) != l || (p && fputc(c, stdout) < 0)) 38 return 1; 39 } 40 41 return 0; 42 }