/*
 * unencode.c
 * I)ruid <druid@caughq.org>
 *
 * Function to unencode a buffer from application/x-www-form-urlencoded
 * into text/plain.
 *
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

/* Un-ench our web-ified hex characters */
char *unencode( unsigned char *text ) {
	int x, y;
	int ch;
	char *newtext;

	newtext = malloc(strlen(text)+1);
	for( x = 0, y = 0; x < strlen(text); x++ ) {
		if( text[x] == '+' )
			text[x] = ' ';
		if( text[x] == '%' ) {
			if( sscanf( &text[x+1], "%2x", &ch ) != 1 ) ch = '?';
				newtext[y] = ch;
			x += 2;
		} else
			newtext[y] = text[x];
		y++;
	}
	newtext[y] = '\0';
	realloc( newtext, strlen(newtext)+1 );

	return newtext;
}