fileshare/src/util.c

86 lines
2.3 KiB
C

/*
* vim: sw=2 ts=2 expandtab
*
* "THE PIZZA-WARE LICENSE" (derived from "THE BEER-WARE LICENCE"):
* Thomas Kolb <cfr34k@tkolb.de> wrote this file. As long as you retain this
* notice you can do whatever you want with this stuff. If we meet some day,
* and you think this stuff is worth it, you can buy me a pizza in return.
* - Thomas Kolb
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <malloc.h>
#include <errno.h>
#include "util.h"
#include "logger.h"
void remove_trailing_slash(char *str) {
size_t offset = strlen(str)-1;
if((offset != 0) && (str[offset] == '/')) {
str[offset] = '\0';
}
}
void urlencode(const char *str, char *result) {
uint8_t c;
while(*str) {
c = *str;
if((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
c == '-' ||
c == '_' ||
c == '!' ||
c == '(' ||
c == ')' ||
c == '$' ||
c == '*' ||
c == '\'' ||
c == ',' ||
c == '.') {
// simply print safe characters
result += sprintf(result, "%c", c);
} else {
// encode all others
result += sprintf(result, "%%%02X", c);
}
str++;
}
}
/*!
* Append src to target, reallocating target on the way if necessary.
*
* \param target The string to append to.
* \param targetsize A pointer to the size of target. Will be updated by this
* function when target is reallocated.
* \param src The string to append to target.
* \returns A pointer to new string (target becomes invalid in the
* event of reallocation) or NULL on a realloc error.
*/
char* safe_append(char *target, size_t *targetsize, const char *src) {
size_t targetlen = strlen(target);
size_t srclen = strlen(src);
size_t newsize = 2*targetlen + srclen + 1;
// check if reallocation is necessary
if((targetlen + srclen) >= *targetsize) {
LOG(LVL_DEBUG, "safe_append: reallocating target string: %lu -> %lu characters", *targetsize, newsize);
target = realloc(target, newsize * sizeof(char));
if(target == NULL) {
LOG(LVL_ERR, "safe_append: realloc failed: %s", strerror(errno));
return NULL;
}
*targetsize = newsize;
}
return strcat(target, src);
}