1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Key to pathname encoder
4 * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
5 * Written by David Howells (dhowells@redhat.com)
8 #include <linux/slab.h>
11 static const char cachefiles_charmap[64] =
12 "0123456789" /* 0 - 9 */
13 "abcdefghijklmnopqrstuvwxyz" /* 10 - 35 */
14 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* 36 - 61 */
18 static const char cachefiles_filecharmap[256] = {
19 /* we skip space and tab and control chars */
20 [33 ... 46] = 1, /* '!' -> '.' */
21 /* we skip '/' as it's significant to pathwalk */
22 [48 ... 127] = 1, /* '0' -> '~' */
26 * turn the raw key into something cooked
27 * - the raw key should include the length in the two bytes at the front
28 * - the key may be up to 514 bytes in length (including the length word)
29 * - "base64" encode the strange keys, mapping 3 bytes of raw to four of
31 * - need to cut the cooked key into 252 char lengths (189 raw bytes)
33 char *cachefiles_cook_key(const u8 *raw, int keylen, uint8_t type)
35 unsigned char csum, ch;
38 int loop, len, max, seg, mark, print;
40 _enter(",%d", keylen);
42 BUG_ON(keylen < 2 || keylen > 514);
44 csum = raw[0] + raw[1];
46 for (loop = 2; loop < keylen; loop++) {
49 print &= cachefiles_filecharmap[ch];
53 /* if the path is usable ASCII, then we render it directly */
55 max += 2; /* two base64'd length chars on the front */
56 max += 5; /* @checksum/M */
57 max += 3 * 2; /* maximum number of segment dividers (".../M")
58 * is ((514 + 251) / 252) = 3
60 max += 1; /* NUL on end */
62 /* calculate the maximum length of the cooked key */
63 keylen = (keylen + 2) / 3;
66 max += 5; /* @checksum/M */
67 max += 3 * 2; /* maximum number of segment dividers (".../M")
68 * is ((514 + 188) / 189) = 3
70 max += 1; /* NUL on end */
73 max += 1; /* 2nd NUL on end */
75 _debug("max: %d", max);
77 key = kmalloc(max, cachefiles_gfp);
83 /* build the cooked key */
84 sprintf(key, "@%02x%c+", (unsigned) csum, 0);
89 acc = *(uint16_t *) raw;
92 key[len + 1] = cachefiles_charmap[acc & 63];
94 key[len] = cachefiles_charmap[acc & 63];
98 for (loop = keylen; loop > 0; loop--) {
111 case FSCACHE_COOKIE_TYPE_INDEX: type = 'I'; break;
112 case FSCACHE_COOKIE_TYPE_DATAFILE: type = 'D'; break;
113 default: type = 'S'; break;
117 for (loop = keylen; loop > 0; loop--) {
129 _debug("acc: %06x", acc);
131 key[len++] = cachefiles_charmap[acc & 63];
133 key[len++] = cachefiles_charmap[acc & 63];
135 key[len++] = cachefiles_charmap[acc & 63];
137 key[len++] = cachefiles_charmap[acc & 63];
143 case FSCACHE_COOKIE_TYPE_INDEX: type = 'J'; break;
144 case FSCACHE_COOKIE_TYPE_DATAFILE: type = 'E'; break;
145 default: type = 'T'; break;
153 _leave(" = %s %d", key, len);