C语言 URL 转义函数分析:format_url_for_hs
该 C 语言函数 format_url_for_hs 用于对 URL 进行转义,将特殊字符进行转义处理。
该函数使用 alloca 函数在栈上分配内存用于存储转义后的字符串。转义后的字符串存在于函数内部的局部变量 dst 中。
函数内部使用指针 to 指向 dst,并逐个字符地进行转义处理,并将结果写入 dst 中。
在函数结束后,dst 所占用的内存会被自动释放。
代码分析:
static const char metachar[] = {'\', '^', '.', '$', '|', '(', ')', '[', ']', '+', '?', '{', '}', '!'};
static inline int is_metachar(char ch)
{
int i;
for (i = 0; i < sizeof(metachar); i++) {
if (ch == metachar[i])
return 1;
}
return 0;
}
static int format_url_for_hs(const char *str, int len, char *xfmt, int xfmt_len, int match_method)
{
unsigned int i = 0;
unsigned int total;
const char *now = str;
char *to, *dst = NULL;
if (!len)
return -1;
total = 2 * len + 4;
dst = alloca(total);
if (dst == NULL) {
strlcpy(xfmt, str, xfmt_len);
WAF_DBG("alloca len %u failed\n", total);
return 0;
}
to = dst;
if (str[0] != '*' && match_method == MATCH_ACCURATE) {
*to = '^';
to++;
} else {
i = 1;
now++;
}
for (; i < len; i++) {
if (is_metachar(*now)) {
*to = '\';
to++;
} else if (i && *now == '*') {
*to = '.';
to++;
}
*to++ = *now++;
}
if (str[len-1] != '*' && match_method == MATCH_ACCURATE) {
*to = '$';
to++;
}
*to = '\0';
assert(to < (dst + total));
strlcpy(xfmt, dst, xfmt_len);
return 0;
}
总结:
format_url_for_hs 函数使用 alloca 函数在栈上分配内存,并在函数内部进行转义操作。由于使用的是栈内存,所以在函数结束后,该内存会被自动释放。
原文地址: https://www.cveoy.top/t/topic/milu 著作权归作者所有。请勿转载和采集!