1 /* Key to pathname encoder
3 * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com)
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public Licence
8 * as published by the Free Software Foundation; either version
9 * 2 of the Licence, or (at your option) any later version.
12 #include <linux/slab.h>
15 static const char cachefiles_charmap
[64] =
16 "0123456789" /* 0 - 9 */
17 "abcdefghijklmnopqrstuvwxyz" /* 10 - 35 */
18 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* 36 - 61 */
22 static const char cachefiles_filecharmap
[256] = {
23 /* we skip space and tab and control chars */
24 [33 ... 46] = 1, /* '!' -> '.' */
25 /* we skip '/' as it's significant to pathwalk */
26 [48 ... 127] = 1, /* '0' -> '~' */
30 * turn the raw key into something cooked
31 * - the raw key should include the length in the two bytes at the front
32 * - the key may be up to 514 bytes in length (including the length word)
33 * - "base64" encode the strange keys, mapping 3 bytes of raw to four of
35 * - need to cut the cooked key into 252 char lengths (189 raw bytes)
37 char *cachefiles_cook_key(const u8
*raw
, int keylen
, uint8_t type
)
39 unsigned char csum
, ch
;
42 int loop
, len
, max
, seg
, mark
, print
;
44 _enter(",%d", keylen
);
46 BUG_ON(keylen
< 2 || keylen
> 514);
48 csum
= raw
[0] + raw
[1];
50 for (loop
= 2; loop
< keylen
; loop
++) {
53 print
&= cachefiles_filecharmap
[ch
];
57 /* if the path is usable ASCII, then we render it directly */
59 max
+= 2; /* two base64'd length chars on the front */
60 max
+= 5; /* @checksum/M */
61 max
+= 3 * 2; /* maximum number of segment dividers (".../M")
62 * is ((514 + 251) / 252) = 3
64 max
+= 1; /* NUL on end */
66 /* calculate the maximum length of the cooked key */
67 keylen
= (keylen
+ 2) / 3;
70 max
+= 5; /* @checksum/M */
71 max
+= 3 * 2; /* maximum number of segment dividers (".../M")
72 * is ((514 + 188) / 189) = 3
74 max
+= 1; /* NUL on end */
77 max
+= 1; /* 2nd NUL on end */
79 _debug("max: %d", max
);
81 key
= kmalloc(max
, cachefiles_gfp
);
87 /* build the cooked key */
88 sprintf(key
, "@%02x%c+", (unsigned) csum
, 0);
93 acc
= *(uint16_t *) raw
;
96 key
[len
+ 1] = cachefiles_charmap
[acc
& 63];
98 key
[len
] = cachefiles_charmap
[acc
& 63];
102 for (loop
= keylen
; loop
> 0; loop
--) {
115 case FSCACHE_COOKIE_TYPE_INDEX
: type
= 'I'; break;
116 case FSCACHE_COOKIE_TYPE_DATAFILE
: type
= 'D'; break;
117 default: type
= 'S'; break;
121 for (loop
= keylen
; loop
> 0; loop
--) {
133 _debug("acc: %06x", acc
);
135 key
[len
++] = cachefiles_charmap
[acc
& 63];
137 key
[len
++] = cachefiles_charmap
[acc
& 63];
139 key
[len
++] = cachefiles_charmap
[acc
& 63];
141 key
[len
++] = cachefiles_charmap
[acc
& 63];
147 case FSCACHE_COOKIE_TYPE_INDEX
: type
= 'J'; break;
148 case FSCACHE_COOKIE_TYPE_DATAFILE
: type
= 'E'; break;
149 default: type
= 'T'; break;
157 _leave(" = %p %d", key
, len
);