r23784: use the GPLv3 boilerplate as recommended by the FSF and the license text
[abartlet/samba.git/.git] / source3 / smbd / mangle_hash2.c
1 /* 
2    Unix SMB/CIFS implementation.
3    new hash based name mangling implementation
4    Copyright (C) Andrew Tridgell 2002
5    Copyright (C) Simo Sorce 2002
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 /*
22   this mangling scheme uses the following format
23
24   Annnn~n.AAA
25
26   where nnnnn is a base 36 hash, and A represents characters from the original string
27
28   The hash is taken of the leading part of the long filename, in uppercase
29
30   for simplicity, we only allow ascii characters in 8.3 names
31  */
32
33  /* hash alghorithm changed to FNV1 by idra@samba.org (Simo Sorce).
34   * see http://www.isthe.com/chongo/tech/comp/fnv/index.html for a
35   * discussion on Fowler / Noll / Vo (FNV) Hash by one of it's authors
36   */
37
38 /*
39   ===============================================================================
40   NOTE NOTE NOTE!!!
41
42   This file deliberately uses non-multibyte string functions in many places. This
43   is *not* a mistake. This code is multi-byte safe, but it gets this property
44   through some very subtle knowledge of the way multi-byte strings are encoded 
45   and the fact that this mangling algorithm only supports ascii characters in
46   8.3 names.
47
48   please don't convert this file to use the *_m() functions!!
49   ===============================================================================
50 */
51
52
53 #include "includes.h"
54
55 #if 1
56 #define M_DEBUG(level, x) DEBUG(level, x)
57 #else
58 #define M_DEBUG(level, x)
59 #endif
60
61 /* these flags are used to mark characters in as having particular
62    properties */
63 #define FLAG_BASECHAR 1
64 #define FLAG_ASCII 2
65 #define FLAG_ILLEGAL 4
66 #define FLAG_WILDCARD 8
67
68 /* the "possible" flags are used as a fast way to find possible DOS
69    reserved filenames */
70 #define FLAG_POSSIBLE1 16
71 #define FLAG_POSSIBLE2 32
72 #define FLAG_POSSIBLE3 64
73 #define FLAG_POSSIBLE4 128
74
75 /* by default have a max of 4096 entries in the cache. */
76 #ifndef MANGLE_CACHE_SIZE
77 #define MANGLE_CACHE_SIZE 4096
78 #endif
79
80 #define FNV1_PRIME 0x01000193
81 /*the following number is a fnv1 of the string: idra@samba.org 2002 */
82 #define FNV1_INIT  0xa6b93095
83
84 /* these tables are used to provide fast tests for characters */
85 static unsigned char char_flags[256];
86
87 #define FLAG_CHECK(c, flag) (char_flags[(unsigned char)(c)] & (flag))
88
89 /*
90   this determines how many characters are used from the original filename
91   in the 8.3 mangled name. A larger value leads to a weaker hash and more collisions.
92   The largest possible value is 6.
93 */
94 static unsigned mangle_prefix;
95
96 /* we will use a very simple direct mapped prefix cache. The big
97    advantage of this cache structure is speed and low memory usage 
98
99    The cache is indexed by the low-order bits of the hash, and confirmed by
100    hashing the resulting cache entry to match the known hash
101 */
102 static char **prefix_cache;
103 static unsigned int *prefix_cache_hashes;
104
105 /* these are the characters we use in the 8.3 hash. Must be 36 chars long */
106 static const char *basechars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
107 static unsigned char base_reverse[256];
108 #define base_forward(v) basechars[v]
109
110 /* the list of reserved dos names - all of these are illegal */
111 static const char *reserved_names[] = 
112 { "AUX", "LOCK$", "CON", "COM1", "COM2", "COM3", "COM4",
113   "LPT1", "LPT2", "LPT3", "NUL", "PRN", NULL };
114
115 /* 
116    hash a string of the specified length. The string does not need to be
117    null terminated 
118
119    this hash needs to be fast with a low collision rate (what hash doesn't?)
120 */
121 static unsigned int mangle_hash(const char *key, unsigned int length)
122 {
123         unsigned int value;
124         unsigned int   i;
125         fstring str;
126
127         /* we have to uppercase here to ensure that the mangled name
128            doesn't depend on the case of the long name. Note that this
129            is the only place where we need to use a multi-byte string
130            function */
131         length = MIN(length,sizeof(fstring)-1);
132         strncpy(str, key, length);
133         str[length] = 0;
134         strupper_m(str);
135
136         /* the length of a multi-byte string can change after a strupper_m */
137         length = strlen(str);
138
139         /* Set the initial value from the key size. */
140         for (value = FNV1_INIT, i=0; i < length; i++) {
141                 value *= (unsigned int)FNV1_PRIME;
142                 value ^= (unsigned int)(str[i]);
143         }
144
145         /* note that we force it to a 31 bit hash, to keep within the limits
146            of the 36^6 mangle space */
147         return value & ~0x80000000;  
148 }
149
150 /* 
151    initialise (ie. allocate) the prefix cache
152  */
153 static BOOL cache_init(void)
154 {
155         if (prefix_cache) {
156                 return True;
157         }
158
159         prefix_cache = SMB_CALLOC_ARRAY(char *,MANGLE_CACHE_SIZE);
160         if (!prefix_cache) {
161                 return False;
162         }
163
164         prefix_cache_hashes = SMB_CALLOC_ARRAY(unsigned int, MANGLE_CACHE_SIZE);
165         if (!prefix_cache_hashes) {
166                 return False;
167         }
168
169         return True;
170 }
171
172 /*
173   insert an entry into the prefix cache. The string might not be null
174   terminated */
175 static void cache_insert(const char *prefix, int length, unsigned int hash)
176 {
177         int i = hash % MANGLE_CACHE_SIZE;
178
179         if (prefix_cache[i]) {
180                 free(prefix_cache[i]);
181         }
182
183         prefix_cache[i] = SMB_STRNDUP(prefix, length);
184         prefix_cache_hashes[i] = hash;
185 }
186
187 /*
188   lookup an entry in the prefix cache. Return NULL if not found.
189 */
190 static const char *cache_lookup(unsigned int hash)
191 {
192         int i = hash % MANGLE_CACHE_SIZE;
193
194         if (!prefix_cache[i] || hash != prefix_cache_hashes[i]) {
195                 return NULL;
196         }
197
198         /* yep, it matched */
199         return prefix_cache[i];
200 }
201
202
203 /* 
204    determine if a string is possibly in a mangled format, ignoring
205    case 
206
207    In this algorithm, mangled names use only pure ascii characters (no
208    multi-byte) so we can avoid doing a UCS2 conversion 
209  */
210 static BOOL is_mangled_component(const char *name, size_t len)
211 {
212         unsigned int i;
213
214         M_DEBUG(10,("is_mangled_component %s (len %lu) ?\n", name, (unsigned long)len));
215
216         /* check the length */
217         if (len > 12 || len < 8)
218                 return False;
219
220         /* the best distinguishing characteristic is the ~ */
221         if (name[6] != '~')
222                 return False;
223
224         /* check extension */
225         if (len > 8) {
226                 if (name[8] != '.')
227                         return False;
228                 for (i=9; name[i] && i < len; i++) {
229                         if (! FLAG_CHECK(name[i], FLAG_ASCII)) {
230                                 return False;
231                         }
232                 }
233         }
234         
235         /* check lead characters */
236         for (i=0;i<mangle_prefix;i++) {
237                 if (! FLAG_CHECK(name[i], FLAG_ASCII)) {
238                         return False;
239                 }
240         }
241         
242         /* check rest of hash */
243         if (! FLAG_CHECK(name[7], FLAG_BASECHAR)) {
244                 return False;
245         }
246         for (i=mangle_prefix;i<6;i++) {
247                 if (! FLAG_CHECK(name[i], FLAG_BASECHAR)) {
248                         return False;
249                 }
250         }
251
252         M_DEBUG(10,("is_mangled_component %s (len %lu) -> yes\n", name, (unsigned long)len));
253
254         return True;
255 }
256
257
258
259 /* 
260    determine if a string is possibly in a mangled format, ignoring
261    case 
262
263    In this algorithm, mangled names use only pure ascii characters (no
264    multi-byte) so we can avoid doing a UCS2 conversion 
265
266    NOTE! This interface must be able to handle a path with unix
267    directory separators. It should return true if any component is
268    mangled
269  */
270 static BOOL is_mangled(const char *name, const struct share_params *parm)
271 {
272         const char *p;
273         const char *s;
274
275         M_DEBUG(10,("is_mangled %s ?\n", name));
276
277         for (s=name; (p=strchr(s, '/')); s=p+1) {
278                 if (is_mangled_component(s, PTR_DIFF(p, s))) {
279                         return True;
280                 }
281         }
282         
283         /* and the last part ... */
284         return is_mangled_component(s,strlen(s));
285 }
286
287
288 /* 
289    see if a filename is an allowable 8.3 name.
290
291    we are only going to allow ascii characters in 8.3 names, as this
292    simplifies things greatly (it means that we know the string won't
293    get larger when converted from UNIX to DOS formats)
294 */
295 static BOOL is_8_3(const char *name, BOOL check_case, BOOL allow_wildcards, const struct share_params *p)
296 {
297         int len, i;
298         char *dot_p;
299
300         /* as a special case, the names '.' and '..' are allowable 8.3 names */
301         if (name[0] == '.') {
302                 if (!name[1] || (name[1] == '.' && !name[2])) {
303                         return True;
304                 }
305         }
306
307         /* the simplest test is on the overall length of the
308          filename. Note that we deliberately use the ascii string
309          length (not the multi-byte one) as it is faster, and gives us
310          the result we need in this case. Using strlen_m would not
311          only be slower, it would be incorrect */
312         len = strlen(name);
313         if (len > 12)
314                 return False;
315
316         /* find the '.'. Note that once again we use the non-multibyte
317            function */
318         dot_p = strchr(name, '.');
319
320         if (!dot_p) {
321                 /* if the name doesn't contain a '.' then its length
322                    must be less than 8 */
323                 if (len > 8) {
324                         return False;
325                 }
326         } else {
327                 int prefix_len, suffix_len;
328
329                 /* if it does contain a dot then the prefix must be <=
330                    8 and the suffix <= 3 in length */
331                 prefix_len = PTR_DIFF(dot_p, name);
332                 suffix_len = len - (prefix_len+1);
333
334                 if (prefix_len > 8 || suffix_len > 3 || suffix_len == 0) {
335                         return False;
336                 }
337
338                 /* a 8.3 name cannot contain more than 1 '.' */
339                 if (strchr(dot_p+1, '.')) {
340                         return False;
341                 }
342         }
343
344         /* the length are all OK. Now check to see if the characters themselves are OK */
345         for (i=0; name[i]; i++) {
346                 /* note that we may allow wildcard petterns! */
347                 if (!FLAG_CHECK(name[i], FLAG_ASCII|(allow_wildcards ? FLAG_WILDCARD : 0)) && name[i] != '.') {
348                         return False;
349                 }
350         }
351
352         /* it is a good 8.3 name */
353         return True;
354 }
355
356
357 /*
358   reset the mangling cache on a smb.conf reload. This only really makes sense for
359   mangling backends that have parameters in smb.conf, and as this backend doesn't
360   this is a NULL operation
361 */
362 static void mangle_reset(void)
363 {
364         /* noop */
365 }
366
367
368 /*
369   try to find a 8.3 name in the cache, and if found then
370   replace the string with the original long name. 
371 */
372 static BOOL check_cache(char *name, size_t maxlen, const struct share_params *p)
373 {
374         unsigned int hash, multiplier;
375         unsigned int i;
376         const char *prefix;
377         char extension[4];
378
379         /* make sure that this is a mangled name from this cache */
380         if (!is_mangled(name, p)) {
381                 M_DEBUG(10,("check_cache: %s -> not mangled\n", name));
382                 return False;
383         }
384
385         /* we need to extract the hash from the 8.3 name */
386         hash = base_reverse[(unsigned char)name[7]];
387         for (multiplier=36, i=5;i>=mangle_prefix;i--) {
388                 unsigned int v = base_reverse[(unsigned char)name[i]];
389                 hash += multiplier * v;
390                 multiplier *= 36;
391         }
392
393         /* now look in the prefix cache for that hash */
394         prefix = cache_lookup(hash);
395         if (!prefix) {
396                 M_DEBUG(10,("check_cache: %s -> %08X -> not found\n", name, hash));
397                 return False;
398         }
399
400         /* we found it - construct the full name */
401         if (name[8] == '.') {
402                 strncpy(extension, name+9, 3);
403                 extension[3] = 0;
404         } else {
405                 extension[0] = 0;
406         }
407
408         if (extension[0]) {
409                 M_DEBUG(10,("check_cache: %s -> %s.%s\n", name, prefix, extension));
410                 slprintf(name, maxlen, "%s.%s", prefix, extension);
411         } else {
412                 M_DEBUG(10,("check_cache: %s -> %s\n", name, prefix));
413                 safe_strcpy(name, prefix, maxlen);
414         }
415
416         return True;
417 }
418
419
420 /*
421   look for a DOS reserved name
422 */
423 static BOOL is_reserved_name(const char *name)
424 {
425         if (FLAG_CHECK(name[0], FLAG_POSSIBLE1) &&
426             FLAG_CHECK(name[1], FLAG_POSSIBLE2) &&
427             FLAG_CHECK(name[2], FLAG_POSSIBLE3) &&
428             FLAG_CHECK(name[3], FLAG_POSSIBLE4)) {
429                 /* a likely match, scan the lot */
430                 int i;
431                 for (i=0; reserved_names[i]; i++) {
432                         int len = strlen(reserved_names[i]);
433                         /* note that we match on COM1 as well as COM1.foo */
434                         if (strnequal(name, reserved_names[i], len) &&
435                             (name[len] == '.' || name[len] == 0)) {
436                                 return True;
437                         }
438                 }
439         }
440
441         return False;
442 }
443
444 /*
445  See if a filename is a legal long filename.
446  A filename ending in a '.' is not legal unless it's "." or "..". JRA.
447  A filename ending in ' ' is not legal either. See bug id #2769.
448 */
449
450 static BOOL is_legal_name(const char *name)
451 {
452         const char *dot_pos = NULL;
453         BOOL alldots = True;
454         size_t numdots = 0;
455
456         while (*name) {
457                 if (((unsigned int)name[0]) > 128 && (name[1] != 0)) {
458                         /* Possible start of mb character. */
459                         char mbc[2];
460                         /*
461                          * Note that if CH_UNIX is utf8 a string may be 3
462                          * bytes, but this is ok as mb utf8 characters don't
463                          * contain embedded ascii bytes. We are really checking
464                          * for mb UNIX asian characters like Japanese (SJIS) here.
465                          * JRA.
466                          */
467                         if (convert_string(CH_UNIX, CH_UTF16LE, name, 2, mbc, 2, False) == 2) {
468                                 /* Was a good mb string. */
469                                 name += 2;
470                                 continue;
471                         }
472                 }
473
474                 if (FLAG_CHECK(name[0], FLAG_ILLEGAL)) {
475                         return False;
476                 }
477                 if (name[0] == '.') {
478                         dot_pos = name;
479                         numdots++;
480                 } else {
481                         alldots = False;
482                 }
483                 if ((name[0] == ' ') && (name[1] == '\0')) {
484                         /* Can't end in ' ' */
485                         return False;
486                 }
487                 name++;
488         }
489
490         if (dot_pos) {
491                 if (alldots && (numdots == 1 || numdots == 2))
492                         return True; /* . or .. is a valid name */
493
494                 /* A valid long name cannot end in '.' */
495                 if (dot_pos[1] == '\0')
496                         return False;
497         }
498         return True;
499 }
500
501 /*
502   the main forward mapping function, which converts a long filename to 
503   a 8.3 name
504
505   if need83 is not set then we only do the mangling if the name is illegal
506   as a long name
507
508   if cache83 is not set then we don't cache the result
509
510   the name parameter must be able to hold 13 bytes
511 */
512 static void name_map(fstring name, BOOL need83, BOOL cache83, int default_case, const struct share_params *p)
513 {
514         char *dot_p;
515         char lead_chars[7];
516         char extension[4];
517         unsigned int extension_length, i;
518         unsigned int prefix_len;
519         unsigned int hash, v;
520         char new_name[13];
521
522         /* reserved names are handled specially */
523         if (!is_reserved_name(name)) {
524                 /* if the name is already a valid 8.3 name then we don't need to 
525                    do anything */
526                 if (is_8_3(name, False, False, p)) {
527                         return;
528                 }
529
530                 /* if the caller doesn't strictly need 8.3 then just check for illegal 
531                    filenames */
532                 if (!need83 && is_legal_name(name)) {
533                         return;
534                 }
535         }
536
537         /* find the '.' if any */
538         dot_p = strrchr(name, '.');
539
540         if (dot_p) {
541                 /* if the extension contains any illegal characters or
542                    is too long or zero length then we treat it as part
543                    of the prefix */
544                 for (i=0; i<4 && dot_p[i+1]; i++) {
545                         if (! FLAG_CHECK(dot_p[i+1], FLAG_ASCII)) {
546                                 dot_p = NULL;
547                                 break;
548                         }
549                 }
550                 if (i == 0 || i == 4) dot_p = NULL;
551         }
552
553         /* the leading characters in the mangled name is taken from
554            the first characters of the name, if they are ascii otherwise
555            '_' is used
556         */
557         for (i=0;i<mangle_prefix && name[i];i++) {
558                 lead_chars[i] = name[i];
559                 if (! FLAG_CHECK(lead_chars[i], FLAG_ASCII)) {
560                         lead_chars[i] = '_';
561                 }
562                 lead_chars[i] = toupper_ascii(lead_chars[i]);
563         }
564         for (;i<mangle_prefix;i++) {
565                 lead_chars[i] = '_';
566         }
567
568         /* the prefix is anything up to the first dot */
569         if (dot_p) {
570                 prefix_len = PTR_DIFF(dot_p, name);
571         } else {
572                 prefix_len = strlen(name);
573         }
574
575         /* the extension of the mangled name is taken from the first 3
576            ascii chars after the dot */
577         extension_length = 0;
578         if (dot_p) {
579                 for (i=1; extension_length < 3 && dot_p[i]; i++) {
580                         char c = dot_p[i];
581                         if (FLAG_CHECK(c, FLAG_ASCII)) {
582                                 extension[extension_length++] = toupper_ascii(c);
583                         }
584                 }
585         }
586            
587         /* find the hash for this prefix */
588         v = hash = mangle_hash(name, prefix_len);
589
590         /* now form the mangled name. */
591         for (i=0;i<mangle_prefix;i++) {
592                 new_name[i] = lead_chars[i];
593         }
594         new_name[7] = base_forward(v % 36);
595         new_name[6] = '~';      
596         for (i=5; i>=mangle_prefix; i--) {
597                 v = v / 36;
598                 new_name[i] = base_forward(v % 36);
599         }
600
601         /* add the extension */
602         if (extension_length) {
603                 new_name[8] = '.';
604                 memcpy(&new_name[9], extension, extension_length);
605                 new_name[9+extension_length] = 0;
606         } else {
607                 new_name[8] = 0;
608         }
609
610         if (cache83) {
611                 /* put it in the cache */
612                 cache_insert(name, prefix_len, hash);
613         }
614
615         M_DEBUG(10,("name_map: %s -> %08X -> %s (cache=%d)\n", 
616                    name, hash, new_name, cache83));
617
618         /* and overwrite the old name */
619         fstrcpy(name, new_name);
620
621         /* all done, we've managed to mangle it */
622 }
623
624
625 /* initialise the flags table 
626
627   we allow only a very restricted set of characters as 'ascii' in this
628   mangling backend. This isn't a significant problem as modern clients
629   use the 'long' filenames anyway, and those don't have these
630   restrictions. 
631 */
632 static void init_tables(void)
633 {
634         int i;
635
636         memset(char_flags, 0, sizeof(char_flags));
637
638         for (i=1;i<128;i++) {
639                 if (i <= 0x1f) {
640                         /* Control characters. */
641                         char_flags[i] |= FLAG_ILLEGAL;
642                 }
643
644                 if ((i >= '0' && i <= '9') || 
645                     (i >= 'a' && i <= 'z') || 
646                     (i >= 'A' && i <= 'Z')) {
647                         char_flags[i] |=  (FLAG_ASCII | FLAG_BASECHAR);
648                 }
649                 if (strchr("_-$~", i)) {
650                         char_flags[i] |= FLAG_ASCII;
651                 }
652
653                 if (strchr("*\\/?<>|\":", i)) {
654                         char_flags[i] |= FLAG_ILLEGAL;
655                 }
656
657                 if (strchr("*?\"<>", i)) {
658                         char_flags[i] |= FLAG_WILDCARD;
659                 }
660         }
661
662         memset(base_reverse, 0, sizeof(base_reverse));
663         for (i=0;i<36;i++) {
664                 base_reverse[(unsigned char)base_forward(i)] = i;
665         }       
666
667         /* fill in the reserved names flags. These are used as a very
668            fast filter for finding possible DOS reserved filenames */
669         for (i=0; reserved_names[i]; i++) {
670                 unsigned char c1, c2, c3, c4;
671
672                 c1 = (unsigned char)reserved_names[i][0];
673                 c2 = (unsigned char)reserved_names[i][1];
674                 c3 = (unsigned char)reserved_names[i][2];
675                 c4 = (unsigned char)reserved_names[i][3];
676
677                 char_flags[c1] |= FLAG_POSSIBLE1;
678                 char_flags[c2] |= FLAG_POSSIBLE2;
679                 char_flags[c3] |= FLAG_POSSIBLE3;
680                 char_flags[c4] |= FLAG_POSSIBLE4;
681                 char_flags[tolower_ascii(c1)] |= FLAG_POSSIBLE1;
682                 char_flags[tolower_ascii(c2)] |= FLAG_POSSIBLE2;
683                 char_flags[tolower_ascii(c3)] |= FLAG_POSSIBLE3;
684                 char_flags[tolower_ascii(c4)] |= FLAG_POSSIBLE4;
685
686                 char_flags[(unsigned char)'.'] |= FLAG_POSSIBLE4;
687         }
688 }
689
690 /*
691   the following provides the abstraction layer to make it easier
692   to drop in an alternative mangling implementation */
693 static struct mangle_fns mangle_fns = {
694         mangle_reset,
695         is_mangled,
696         is_8_3,
697         check_cache,
698         name_map
699 };
700
701 /* return the methods for this mangling implementation */
702 struct mangle_fns *mangle_hash2_init(void)
703 {
704         /* the mangle prefix can only be in the mange 1 to 6 */
705         mangle_prefix = lp_mangle_prefix();
706         if (mangle_prefix > 6) {
707                 mangle_prefix = 6;
708         }
709         if (mangle_prefix < 1) {
710                 mangle_prefix = 1;
711         }
712
713         init_tables();
714         mangle_reset();
715
716         if (!cache_init()) {
717                 return NULL;
718         }
719
720         return &mangle_fns;
721 }
722
723 static void posix_mangle_reset(void)
724 {;}
725
726 static BOOL posix_is_mangled(const char *s, const struct share_params *p)
727 {
728         return False;
729 }
730
731 static BOOL posix_is_8_3(const char *fname, BOOL check_case, BOOL allow_wildcards, const struct share_params *p)
732 {
733         return False;
734 }
735
736 static BOOL posix_check_cache( char *s, size_t maxlen, const struct share_params *p )
737 {
738         return False;
739 }
740
741 static void posix_name_map(char *OutName, BOOL need83, BOOL cache83, int default_case, const struct share_params *p)
742 {
743         if (need83) {
744                 memset(OutName, '\0', 13);
745         }
746 }
747
748 /* POSIX paths backend - no mangle. */
749 static struct mangle_fns posix_mangle_fns = {
750         posix_mangle_reset,
751         posix_is_mangled,
752         posix_is_8_3,
753         posix_check_cache,
754         posix_name_map
755 };
756
757 struct mangle_fns *posix_mangle_init(void)
758 {
759         return &posix_mangle_fns;
760 }