commit 08f5deb4f4060a24b7619de46f64e164615725f8
parent 5278f8f077195cc3da3dacee5b376cdd8e811bb6
Author: sin <sin@2f30.org>
Date: Thu, 17 Dec 2015 12:59:44 +0000
Add url{encode,decode}()
Diffstat:
M | sbtd.h | | | 2 | ++ |
M | util.c | | | 60 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++----- |
2 files changed, 57 insertions(+), 5 deletions(-)
diff --git a/sbtd.h b/sbtd.h
@@ -44,3 +44,5 @@ uint8_t *hex2bin(const char *, uint8_t *, size_t);
char *bin2hex(const uint8_t *, char *, size_t);
void sha1sum(uint8_t *, unsigned long, uint8_t *);
int readfile(char *, char **, size_t *);
+char *urlencode(char *);
+char *urldecode(char *);
diff --git a/util.c b/util.c
@@ -22,6 +22,7 @@
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
+#include <string.h>
#include <unistd.h>
#include "sbtd.h"
@@ -59,11 +60,11 @@ tstbit(uint32_t *b, int n)
uint8_t
hex2int(int c)
{
- c = tolower(c);
+ c = toupper(c);
if (c >= '0' && c <= '9')
return c - '0';
- if (c >= 'a' && c <= 'f')
- return c - 'a' + 10;
+ if (c >= 'A' && c <= 'F')
+ return c - 'A' + 10;
errx(1, "%c is not hex", c);
}
@@ -77,11 +78,10 @@ hex2bin(const char *h, uint8_t *b, size_t n)
return b;
}
-
char *
bin2hex(const uint8_t *b, char *h, size_t n)
{
- const char *c = "0123456789abcdef";
+ const char *c = "0123456789ABCDEF";
size_t i;
for (i = 0; i < n; i++) {
@@ -122,3 +122,53 @@ readfile(char *file, char **b, size_t *n)
close(fd);
return 0;
}
+
+char *
+urlencode(char *s)
+{
+ const char *c = "0123456789ABCDEF";
+ char *p = s, *buf, *bp;
+
+ bp = buf = emalloc(strlen(s) * 3 + 1);
+ while (*p) {
+ if (*p == '-' ||
+ *p == '_' ||
+ *p == '.' ||
+ *p == '~' ||
+ isalnum(*p)) {
+ *bp++ = *p;
+ } else if (*p == ' ') {
+ *bp++ = '+';
+ } else {
+ *bp++ = '%';
+ *bp++ = c[(*p >> 4) & 0xf];
+ *bp++ = c[*p & 0xf];
+ }
+ p++;
+ }
+ *bp = '\0';
+ return buf;
+}
+
+char *
+urldecode(char *s)
+{
+ char *p = s, *buf, *bp;
+
+ bp = buf = emalloc(strlen(s) + 1);
+ while (*p) {
+ if (*p == '%') {
+ if (p[1] && p[2]) {
+ *bp++ = hex2int(p[1]) << 4 | hex2int(p[2]);
+ p += 2;
+ }
+ } else if (*p == '+') {
+ *bp++ = ' ';
+ } else {
+ *bp++ = *p;
+ }
+ p++;
+ }
+ *bp = '\0';
+ return buf;
+}