Added url_encode and url_decode

This commit is contained in:
2020-12-13 16:05:55 +01:00
parent 7c5a57b3d8
commit 2bcfa97e1b
2 changed files with 55 additions and 0 deletions

View File

@ -21,3 +21,54 @@ char *format_duration(unsigned long micros, char *buf) {
}
return buf;
}
int url_encode(const char *str, char *enc, ssize_t *size) {
char *ptr = enc;
char ch;
memset(enc, 0, *size);
for (int i = 0; i < strlen(str); i++, ptr++) {
if ((ptr - enc) >= *size) {
printf("%li %li\n", ptr - enc, *size);
return -1;
}
ch = str[i];
if (ch == ':' || ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']' || ch == '@' || ch == '!' ||
ch == '$' || ch == '&' || ch == '\'' || ch == '(' || ch == ')' || ch == '*' || ch == '+' || ch == ',' ||
ch == ';' || ch == '=' || ch < ' ' || ch > '~') {
if ((ptr - enc + 2) >= *size) {
return -1;
}
sprintf(ptr, "%%%02X", ch);
ptr += 2;
} else if (ch == ' ') {
ptr[0] = '+';
} else {
ptr[0] = ch;
}
}
*size = ptr - enc;
return 0;
}
int url_decode(const char *str, char *dec, ssize_t *size) {
char *ptr = dec;
char ch, buf[3];
memset(dec, 0, *size);
for (int i = 0; i < strlen(str); i++, ptr++) {
if ((ptr - dec) >= *size) {
return -1;
}
ch = str[i];
if (ch == '+') {
ch = ' ';
} else if (ch == '%') {
memcpy(buf, str + i + 1, 2);
buf[2] = 0;
ch = (char) strtol(buf, NULL, 16);
i += 2;
}
ptr[0] = ch;
}
*size = ptr - dec;
return 0;
}

View File

@ -21,4 +21,8 @@ char *log_prefix;
char *format_duration(unsigned long micros, char *buf);
int url_encode(const char *str, char *enc, ssize_t *size);
int url_decode(const char *str, char *dec, ssize_t *size);
#endif //NECRONDA_SERVER_UTILS_H