fix base32 mask calculation

This commit is contained in:
cathugger 2017-09-25 01:47:45 +03:00
parent b20f83fcbf
commit a763e05c88
3 changed files with 58 additions and 10 deletions

View file

@ -22,27 +22,33 @@ static const u8 base32f[256] = {
*/
size_t base32_from(u8 *dst, u8 *dmask, const char *src)
{
int i, j, k = -1, l;
u8 mask = 0;
int i, j, k = -1, l, sk = 0;
u8 mask = 0, cmask = 0;
for (i = 0;;i += 5) {
j = i/5;
l = i%8;
if (!src[j]) {
if (!l) // workaround: if l==0 mask misses some upper bits
mask = 0xFF;
if (k >= 0)
dst[k] &= mask;
//printf("dst[k]:%02X mask:%02X l:%d\n", dst[k], (unsigned int)(mask & 0xFF), l);
*dmask = mask;
dst[k] &= cmask;
//printf("dst[k]:%02X mask:%02X l:%d\n", dst[k], (cmask & 0xFF), l);
*dmask = cmask;
return (size_t)(k + 1);
}
k = i/8;
if (k != sk)
cmask = 0;
sk = k;
mask = (0x1F << 3) >> l;
cmask |= mask;
//printf("1:m[%02X] cm[%02X]\n",mask,cmask);
dst[k] &= ~mask;
dst[k] |= (base32f[(u8)src[j]] << 3) >> l;
if (((0x1F << 8) >> (l+5-8)) & 0xFF) {
mask = ((0x1F << 8) >> (l+5-8)) & 0xFF;
++k;
sk = k;
mask = ((0x1F << 8) >> (l+5-8)) & 0xFF;
cmask = mask;
//printf("2:m[%02X] cm[%02X]\n",mask,cmask);
dst[k] &= ~mask;
dst[k] |= ((base32f[(u8)src[j]] << 8) >> (l+5-8)) & 0xFF;
}

7
main.c
View file

@ -75,6 +75,7 @@ static void filters_add(const char *filter)
size_t ret;
ret = base32_from(buf,&bf.mask,filter);
//printf("--m:%02X\n", bf.mask);
if (!ret)
return;
bf.f = malloc(ret);
@ -113,13 +114,15 @@ static void loadfilterfile(const char *fname)
static void printfilters()
{
fprintf(stderr, "current filters:\n");
#if 0
for (size_t i = 0; i < VEC_LENGTH(filters); ++i) {
fprintf(stderr, "\t%s\n", VEC_BUF(filters, i).str);
}
#endif
for (size_t i = 0; i < VEC_LENGTH(bfilters); ++i) {
char buf[256];
base32_to(buf, VEC_BUF(bfilters, i).f, VEC_BUF(bfilters, i).len);
fprintf(stderr, "\t%s\n", buf);
base32_to(buf,VEC_BUF(bfilters,i).f,VEC_BUF(bfilters,i).len);
fprintf(stderr, "\t%s [%02X]\n",buf,VEC_BUF(bfilters,i).mask);
}
}

View file

@ -21,6 +21,42 @@ struct texttestcase {
{"foobar", "mzxw6ytboi", "foobar"},
};
/*
r:0, mask:FF
--
r:2, mask:C0
f -- f
r:3, mask:F0
fo -- fo
r:4, mask:80
foo -- foo
r:5, mask:E0
foob -- foob
r:5, mask:FF
fooba -- fooba
r:7, mask:C0
foobar -- foobar
*/
/*
struct masktestcase {
const char *src;
u8 mask;
} tests1[] = {
{"", 0x00},
{"a", 0x00},
{"ab", 0x00},
{"abc", 0x00},
{"abcd", 0x00},
{"abcde", 0x00},
{"abcdef", 0x00},
{"abcdefg", 0x00},
{"abcdefgh", 0x00},
{"abcdefghi", 0x00},
{"abcdefghij", 0x00},
};
*/
int main()
{
char buf[1024], buf2[1024], mask;
@ -30,6 +66,9 @@ int main()
assert(strcmp(buf, tests0[i].out) == 0);
r = base32_from((u8 *)buf2, (u8 *)&mask, buf);
buf2[r] = 0;
if (r > 0) {
assert((buf2[r-1] & ~mask) == 0);
}
//fprintf(stderr, "r:%d, mask:%02X\n", (int)r, ((unsigned int)mask) & 0xFF);
//assert(r == strlen(buf2));
//assert(r == strlen(tests0[i].rev));