2015-01-29 20:52:44 +00:00
|
|
|
/* See LICENSE file for copyright and license details. */
|
|
|
|
#include <string.h>
|
|
|
|
|
|
|
|
#include "../util.h"
|
|
|
|
|
|
|
|
size_t
|
|
|
|
unescape(char *s)
|
|
|
|
{
|
|
|
|
size_t len, i, off, m, factor, q;
|
|
|
|
|
|
|
|
len = strlen(s);
|
|
|
|
|
|
|
|
for (i = 0; i < len; i++) {
|
|
|
|
if (s[i] != '\\')
|
|
|
|
continue;
|
|
|
|
off = 0;
|
|
|
|
|
|
|
|
switch (s[i + 1]) {
|
2015-01-29 20:59:27 +00:00
|
|
|
case '\\': s[i] = '\\'; off++; break;
|
2015-02-14 21:54:18 +00:00
|
|
|
case '\'': s[i] = '\'', off++; break;
|
|
|
|
case '"': s[i] = '"', off++; break;
|
2015-01-29 20:59:27 +00:00
|
|
|
case 'a': s[i] = '\a'; off++; break;
|
|
|
|
case 'b': s[i] = '\b'; off++; break;
|
2015-02-14 21:54:18 +00:00
|
|
|
case 'e': s[i] = 033; off++; break;
|
2015-01-29 20:59:27 +00:00
|
|
|
case 'f': s[i] = '\f'; off++; break;
|
|
|
|
case 'n': s[i] = '\n'; off++; break;
|
|
|
|
case 'r': s[i] = '\r'; off++; break;
|
|
|
|
case 't': s[i] = '\t'; off++; break;
|
|
|
|
case 'v': s[i] = '\v'; off++; break;
|
2015-02-14 21:54:18 +00:00
|
|
|
case 'x':
|
|
|
|
/* "\xH[H]" hexadecimal escape */
|
|
|
|
for (m = i + 2; m < i + 1 + 3 && m < len; m++)
|
|
|
|
if ((s[m] < '0' && s[m] > '9') &&
|
|
|
|
(s[m] < 'A' && s[m] > 'F') &&
|
|
|
|
(s[m] < 'a' && s[m] > 'f'))
|
|
|
|
break;
|
|
|
|
if (m == i + 2)
|
2017-02-04 21:15:13 +00:00
|
|
|
eprintf("invalid escape sequence '\\%c'\n", s[i + 1]);
|
2015-02-14 21:54:18 +00:00
|
|
|
off += m - i - 1;
|
|
|
|
for (--m, q = 0, factor = 1; m > i + 1; m--) {
|
|
|
|
if (s[m] >= '0' && s[m] <= '9')
|
|
|
|
q += (s[m] - '0') * factor;
|
|
|
|
else if (s[m] >= 'A' && s[m] <= 'F')
|
|
|
|
q += ((s[m] - 'A') + 10) * factor;
|
|
|
|
else if (s[m] >= 'a' && s[m] <= 'f')
|
|
|
|
q += ((s[m] - 'a') + 10) * factor;
|
|
|
|
factor *= 16;
|
|
|
|
}
|
|
|
|
s[i] = q;
|
|
|
|
break;
|
2015-01-29 20:52:44 +00:00
|
|
|
case '\0':
|
2017-02-04 21:15:13 +00:00
|
|
|
eprintf("null escape sequence\n");
|
2015-01-29 20:52:44 +00:00
|
|
|
default:
|
2016-02-20 20:40:11 +00:00
|
|
|
/* "\O[OOO]" octal escape */
|
|
|
|
for (m = i + 1; m < i + 1 + 4 && m < len; m++)
|
2015-01-29 20:52:44 +00:00
|
|
|
if (s[m] < '0' || s[m] > '7')
|
|
|
|
break;
|
|
|
|
if (m == i + 1)
|
2017-02-04 21:15:13 +00:00
|
|
|
eprintf("invalid escape sequence '\\%c'\n", s[i + 1]);
|
2015-01-29 20:52:44 +00:00
|
|
|
off += m - i - 1;
|
|
|
|
for (--m, q = 0, factor = 1; m > i; m--) {
|
|
|
|
q += (s[m] - '0') * factor;
|
|
|
|
factor *= 8;
|
|
|
|
}
|
2016-02-20 20:54:12 +00:00
|
|
|
s[i] = (q > 255) ? 255 : q;
|
2015-01-29 20:52:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for (m = i + 1; m <= len - off; m++)
|
|
|
|
s[m] = s[m + off];
|
|
|
|
len -= off;
|
|
|
|
}
|
|
|
|
|
|
|
|
return len;
|
|
|
|
}
|