apcgi

Web client for aps on trusted networks
git clone git://jacobedwards.org/apcgi
Log | Files | Refs | README

urlencode.c (637B)


      1 /*
      2  * Copyright 2021 Jacob R. Edwards
      3  * Percent Encode URI (See RFC 2396, Sections 2., "Characters") 
      4  */
      5 
      6 #include <stdio.h>
      7 #include <string.h>
      8 #include <unistd.h>
      9 
     10 int
     11 main(void)
     12 {
     13 	int i, il, ol;
     14 	unsigned char ib[1024], ob[sizeof(ib) * 3 + 1];
     15 
     16 	while ((il = read(0, ib, sizeof(ib))) > 0) {
     17 		ol = 0;
     18 		for (i = 0; i < il; ++i) {
     19 			if (ib[i] == ' ') {
     20 				ob[ol++] = '+';
     21 			} else if (ib[i] <= 0x20 || strchr(":/?#[]@!$&'()*+,;=" "+%\x7F", ib[i])) {
     22 				if (sprintf(ob + ol, "%%%.2X", ib[i]) != 3)
     23 					return 1;
     24 				ol += 3;
     25 			} else
     26 				ob[ol++] = ib[i];
     27 		}
     28 		if (write(1, ob, ol) != ol)
     29 			return 1;
     30 	}
     31 
     32 	return il == -1;
     33 }