charcnv: removed the allow_badcharcnv and allow_bad_conv options to convert_string*()
[kai/samba-autobuild/.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  * ============================================================================
54  * Whenever you change anything in the FLAG_ or other fields,
55  * re-initialize the tables char_flags and base_reverse by running the
56  * init_tables() routine once and dump its results. To do this, a
57  * single smbd run with
58  *
59  * #define DYNAMIC_MANGLE_TABLES 1
60  *
61  * and debug level 10 should be sufficient.
62  * ============================================================================
63  */
64
65
66 #include "includes.h"
67 #include "smbd/globals.h"
68 #include "memcache.h"
69 #include "mangle.h"
70
71 #if 1
72 #define M_DEBUG(level, x) DEBUG(level, x)
73 #else
74 #define M_DEBUG(level, x)
75 #endif
76
77 /* these flags are used to mark characters in as having particular
78    properties */
79 #define FLAG_BASECHAR 1
80 #define FLAG_ASCII 2
81 #define FLAG_ILLEGAL 4
82 #define FLAG_WILDCARD 8
83
84 /* the "possible" flags are used as a fast way to find possible DOS
85    reserved filenames */
86 #define FLAG_POSSIBLE1 16
87 #define FLAG_POSSIBLE2 32
88 #define FLAG_POSSIBLE3 64
89 #define FLAG_POSSIBLE4 128
90
91 /* by default have a max of 4096 entries in the cache. */
92 #ifndef MANGLE_CACHE_SIZE
93 #define MANGLE_CACHE_SIZE 4096
94 #endif
95
96 #define FNV1_PRIME 0x01000193
97 /*the following number is a fnv1 of the string: idra@samba.org 2002 */
98 #define FNV1_INIT  0xa6b93095
99
100 #define FLAG_CHECK(c, flag) (char_flags[(unsigned char)(c)] & (flag))
101
102 /* these are the characters we use in the 8.3 hash. Must be 36 chars long */
103 static const char basechars[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
104 #define base_forward(v) basechars[v]
105
106 /* the list of reserved dos names - all of these are illegal */
107 static const char * const reserved_names[] =
108 { "AUX", "LOCK$", "CON", "COM1", "COM2", "COM3", "COM4",
109   "LPT1", "LPT2", "LPT3", "NUL", "PRN", NULL };
110
111 #define DYNAMIC_MANGLE_TABLES 0
112
113 #if DYNAMIC_MANGLE_TABLES
114
115 /* these tables are used to provide fast tests for characters */
116 static unsigned char char_flags[256];
117 static unsigned char base_reverse[256];
118
119 /* initialise the flags table
120
121   we allow only a very restricted set of characters as 'ascii' in this
122   mangling backend. This isn't a significant problem as modern clients
123   use the 'long' filenames anyway, and those don't have these
124   restrictions.
125 */
126 static void init_tables(void)
127 {
128         int i;
129
130         memset(char_flags, 0, sizeof(char_flags));
131
132         for (i=1;i<128;i++) {
133                 if (i <= 0x1f) {
134                         /* Control characters. */
135                         char_flags[i] |= FLAG_ILLEGAL;
136                 }
137
138                 if ((i >= '0' && i <= '9') ||
139                     (i >= 'a' && i <= 'z') ||
140                     (i >= 'A' && i <= 'Z')) {
141                         char_flags[i] |=  (FLAG_ASCII | FLAG_BASECHAR);
142                 }
143                 if (strchr("_-$~", i)) {
144                         char_flags[i] |= FLAG_ASCII;
145                 }
146
147                 if (strchr("*\\/?<>|\":", i)) {
148                         char_flags[i] |= FLAG_ILLEGAL;
149                 }
150
151                 if (strchr("*?\"<>", i)) {
152                         char_flags[i] |= FLAG_WILDCARD;
153                 }
154         }
155
156         memset(base_reverse, 0, sizeof(base_reverse));
157         for (i=0;i<36;i++) {
158                 base_reverse[(unsigned char)base_forward(i)] = i;
159         }
160
161         /* fill in the reserved names flags. These are used as a very
162            fast filter for finding possible DOS reserved filenames */
163         for (i=0; reserved_names[i]; i++) {
164                 unsigned char c1, c2, c3, c4;
165
166                 c1 = (unsigned char)reserved_names[i][0];
167                 c2 = (unsigned char)reserved_names[i][1];
168                 c3 = (unsigned char)reserved_names[i][2];
169                 c4 = (unsigned char)reserved_names[i][3];
170
171                 char_flags[c1] |= FLAG_POSSIBLE1;
172                 char_flags[c2] |= FLAG_POSSIBLE2;
173                 char_flags[c3] |= FLAG_POSSIBLE3;
174                 char_flags[c4] |= FLAG_POSSIBLE4;
175                 char_flags[tolower_ascii(c1)] |= FLAG_POSSIBLE1;
176                 char_flags[tolower_ascii(c2)] |= FLAG_POSSIBLE2;
177                 char_flags[tolower_ascii(c3)] |= FLAG_POSSIBLE3;
178                 char_flags[tolower_ascii(c4)] |= FLAG_POSSIBLE4;
179
180                 char_flags[(unsigned char)'.'] |= FLAG_POSSIBLE4;
181         }
182
183 #if 0
184         DEBUG(10, ("char_flags\n"));
185         dump_data(10, char_flags, sizeof(char_flags));
186
187         DEBUG(10, ("base_reverse\n"));
188         dump_data(10, base_reverse, sizeof(base_reverse));
189 #endif
190 }
191
192 #else
193
194 /*
195  * These tables were initialized by a single run of the above
196  * init_tables() routine, dumping the tables and a simple emacs macro.
197  *
198  * Technically we could leave out the 0's at the end of the array
199  * initializers, but I'll leave it in: less surprise.
200  */
201
202 static uint8_t char_flags[256] = {
203         0x80, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
204         0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
205         0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
206         0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
207         0x00, 0x00, 0x0C, 0x00, 0x02, 0x00, 0x00, 0x00,
208         0x00, 0x00, 0x0C, 0x00, 0x00, 0x02, 0x80, 0x04,
209         0x03, 0x83, 0x83, 0x83, 0x83, 0x03, 0x03, 0x03,
210         0x03, 0x03, 0x04, 0x00, 0x0C, 0x00, 0x0C, 0x0C,
211         0x00, 0x13, 0x03, 0x53, 0x03, 0x03, 0x03, 0x03,
212         0x03, 0x03, 0x03, 0x83, 0x53, 0x43, 0x53, 0x23,
213         0x33, 0x03, 0x23, 0x03, 0x43, 0x23, 0x03, 0x03,
214         0x43, 0x03, 0x03, 0x00, 0x04, 0x00, 0x00, 0x02,
215         0x00, 0x13, 0x03, 0x53, 0x03, 0x03, 0x03, 0x03,
216         0x03, 0x03, 0x03, 0x83, 0x53, 0x43, 0x53, 0x23,
217         0x33, 0x03, 0x23, 0x03, 0x43, 0x23, 0x03, 0x03,
218         0x43, 0x03, 0x03, 0x00, 0x04, 0x00, 0x02, 0x00,
219         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
220         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
221         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
222         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
223         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
224         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
225         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
226         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
227         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
228         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
229         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
230         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
231         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
232         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
233         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
234         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
235 };
236
237 static uint8_t base_reverse[256] = {
238         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
239         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
240         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
241         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
242         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
243         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
244         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
245         0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
246         0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10,
247         0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
248         0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20,
249         0x21, 0x22, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00,
250         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
251         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
252         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
253         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
254         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
255         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
256         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
257         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
258         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
259         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
260         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
261         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
262         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
263         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
264         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
265         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
266         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
267         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
268         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
269         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
270 };
271
272 #endif
273
274 /* 
275    hash a string of the specified length. The string does not need to be
276    null terminated 
277
278    this hash needs to be fast with a low collision rate (what hash doesn't?)
279 */
280 static unsigned int mangle_hash(const char *key, unsigned int length)
281 {
282         unsigned int value;
283         unsigned int   i;
284         fstring str;
285
286         /* we have to uppercase here to ensure that the mangled name
287            doesn't depend on the case of the long name. Note that this
288            is the only place where we need to use a multi-byte string
289            function */
290         length = MIN(length,sizeof(fstring)-1);
291         strncpy(str, key, length);
292         str[length] = 0;
293         strupper_m(str);
294
295         /* the length of a multi-byte string can change after a strupper_m */
296         length = strlen(str);
297
298         /* Set the initial value from the key size. */
299         for (value = FNV1_INIT, i=0; i < length; i++) {
300                 value *= (unsigned int)FNV1_PRIME;
301                 value ^= (unsigned int)(str[i]);
302         }
303
304         /* note that we force it to a 31 bit hash, to keep within the limits
305            of the 36^6 mangle space */
306         return value & ~0x80000000;  
307 }
308
309 /*
310   insert an entry into the prefix cache. The string might not be null
311   terminated */
312 static void cache_insert(const char *prefix, int length, unsigned int hash)
313 {
314         char *str = SMB_STRNDUP(prefix, length);
315
316         if (str == NULL) {
317                 return;
318         }
319
320         memcache_add(smbd_memcache(), MANGLE_HASH2_CACHE,
321                      data_blob_const(&hash, sizeof(hash)),
322                      data_blob_const(str, length+1));
323         SAFE_FREE(str);
324 }
325
326 /*
327   lookup an entry in the prefix cache. Return NULL if not found.
328 */
329 static char *cache_lookup(TALLOC_CTX *mem_ctx, unsigned int hash)
330 {
331         DATA_BLOB value;
332
333         if (!memcache_lookup(smbd_memcache(), MANGLE_HASH2_CACHE,
334                              data_blob_const(&hash, sizeof(hash)), &value)) {
335                 return NULL;
336         }
337
338         SMB_ASSERT((value.length > 0)
339                    && (value.data[value.length-1] == '\0'));
340
341         return talloc_strdup(mem_ctx, (char *)value.data);
342 }
343
344
345 /* 
346    determine if a string is possibly in a mangled format, ignoring
347    case 
348
349    In this algorithm, mangled names use only pure ascii characters (no
350    multi-byte) so we can avoid doing a UCS2 conversion 
351  */
352 static bool is_mangled_component(const char *name, size_t len)
353 {
354         unsigned int i;
355
356         M_DEBUG(10,("is_mangled_component %s (len %lu) ?\n", name, (unsigned long)len));
357
358         /* check the length */
359         if (len > 12 || len < 8)
360                 return False;
361
362         /* the best distinguishing characteristic is the ~ */
363         if (name[6] != '~')
364                 return False;
365
366         /* check extension */
367         if (len > 8) {
368                 if (name[8] != '.')
369                         return False;
370                 for (i=9; name[i] && i < len; i++) {
371                         if (! FLAG_CHECK(name[i], FLAG_ASCII)) {
372                                 return False;
373                         }
374                 }
375         }
376         
377         /* check lead characters */
378         for (i=0;i<mangle_prefix;i++) {
379                 if (! FLAG_CHECK(name[i], FLAG_ASCII)) {
380                         return False;
381                 }
382         }
383         
384         /* check rest of hash */
385         if (! FLAG_CHECK(name[7], FLAG_BASECHAR)) {
386                 return False;
387         }
388         for (i=mangle_prefix;i<6;i++) {
389                 if (! FLAG_CHECK(name[i], FLAG_BASECHAR)) {
390                         return False;
391                 }
392         }
393
394         M_DEBUG(10,("is_mangled_component %s (len %lu) -> yes\n", name, (unsigned long)len));
395
396         return True;
397 }
398
399
400
401 /* 
402    determine if a string is possibly in a mangled format, ignoring
403    case 
404
405    In this algorithm, mangled names use only pure ascii characters (no
406    multi-byte) so we can avoid doing a UCS2 conversion 
407
408    NOTE! This interface must be able to handle a path with unix
409    directory separators. It should return true if any component is
410    mangled
411  */
412 static bool is_mangled(const char *name, const struct share_params *parm)
413 {
414         const char *p;
415         const char *s;
416
417         M_DEBUG(10,("is_mangled %s ?\n", name));
418
419         for (s=name; (p=strchr(s, '/')); s=p+1) {
420                 if (is_mangled_component(s, PTR_DIFF(p, s))) {
421                         return True;
422                 }
423         }
424         
425         /* and the last part ... */
426         return is_mangled_component(s,strlen(s));
427 }
428
429
430 /* 
431    see if a filename is an allowable 8.3 name to return to the client.
432    Note this is not testing if this is a valid Samba mangled name, so
433    the rules are different for is_mangled.
434
435    we are only going to allow ascii characters in 8.3 names, as this
436    simplifies things greatly (it means that we know the string won't
437    get larger when converted from UNIX to DOS formats)
438 */
439
440 static char force_shortname_chars[] = " +,[];=";
441
442 static bool is_8_3(const char *name, bool check_case, bool allow_wildcards, const struct share_params *p)
443 {
444         int len, i;
445         char *dot_p;
446
447         /* as a special case, the names '.' and '..' are allowable 8.3 names */
448         if (name[0] == '.') {
449                 if (!name[1] || (name[1] == '.' && !name[2])) {
450                         return True;
451                 }
452         }
453
454         /* the simplest test is on the overall length of the
455          filename. Note that we deliberately use the ascii string
456          length (not the multi-byte one) as it is faster, and gives us
457          the result we need in this case. Using strlen_m would not
458          only be slower, it would be incorrect */
459         len = strlen(name);
460         if (len > 12)
461                 return False;
462
463         /* find the '.'. Note that once again we use the non-multibyte
464            function */
465         dot_p = strchr(name, '.');
466
467         if (!dot_p) {
468                 /* if the name doesn't contain a '.' then its length
469                    must be less than 8 */
470                 if (len > 8) {
471                         return False;
472                 }
473         } else {
474                 int prefix_len, suffix_len;
475
476                 /* if it does contain a dot then the prefix must be <=
477                    8 and the suffix <= 3 in length */
478                 prefix_len = PTR_DIFF(dot_p, name);
479                 suffix_len = len - (prefix_len+1);
480
481                 if (prefix_len > 8 || suffix_len > 3 || suffix_len == 0) {
482                         return False;
483                 }
484
485                 /* a 8.3 name cannot contain more than 1 '.' */
486                 if (strchr(dot_p+1, '.')) {
487                         return False;
488                 }
489         }
490
491         /* the length are all OK. Now check to see if the characters themselves are OK */
492         for (i=0; name[i]; i++) {
493                 if (FLAG_CHECK(name[i], FLAG_ILLEGAL)) {
494                         return false;
495                 }
496                 /* note that we may allow wildcard petterns! */
497                 if (!allow_wildcards && FLAG_CHECK(name[i], FLAG_WILDCARD)) {
498                         return false;
499                 }
500                 if (((unsigned char)name[i]) > 0x7e) {
501                         return false;
502                 }
503                 if (strchr(force_shortname_chars, name[i])) {
504                         return false;
505                 }
506         }
507
508         /* it is a good 8.3 name */
509         return True;
510 }
511
512
513 /*
514   reset the mangling cache on a smb.conf reload. This only really makes sense for
515   mangling backends that have parameters in smb.conf, and as this backend doesn't
516   this is a NULL operation
517 */
518 static void mangle_reset(void)
519 {
520         /* noop */
521 }
522
523
524 /*
525   try to find a 8.3 name in the cache, and if found then
526   replace the string with the original long name.
527 */
528 static bool lookup_name_from_8_3(TALLOC_CTX *ctx,
529                         const char *name,
530                         char **pp_out, /* talloced on the given context. */
531                         const struct share_params *p)
532 {
533         unsigned int hash, multiplier;
534         unsigned int i;
535         char *prefix;
536         char extension[4];
537
538         *pp_out = NULL;
539
540         /* make sure that this is a mangled name from this cache */
541         if (!is_mangled(name, p)) {
542                 M_DEBUG(10,("lookup_name_from_8_3: %s -> not mangled\n", name));
543                 return False;
544         }
545
546         /* we need to extract the hash from the 8.3 name */
547         hash = base_reverse[(unsigned char)name[7]];
548         for (multiplier=36, i=5;i>=mangle_prefix;i--) {
549                 unsigned int v = base_reverse[(unsigned char)name[i]];
550                 hash += multiplier * v;
551                 multiplier *= 36;
552         }
553
554         /* now look in the prefix cache for that hash */
555         prefix = cache_lookup(ctx, hash);
556         if (!prefix) {
557                 M_DEBUG(10,("lookup_name_from_8_3: %s -> %08X -> not found\n",
558                                         name, hash));
559                 return False;
560         }
561
562         /* we found it - construct the full name */
563         if (name[8] == '.') {
564                 strncpy(extension, name+9, 3);
565                 extension[3] = 0;
566         } else {
567                 extension[0] = 0;
568         }
569
570         if (extension[0]) {
571                 M_DEBUG(10,("lookup_name_from_8_3: %s -> %s.%s\n",
572                                         name, prefix, extension));
573                 *pp_out = talloc_asprintf(ctx, "%s.%s", prefix, extension);
574         } else {
575                 M_DEBUG(10,("lookup_name_from_8_3: %s -> %s\n", name, prefix));
576                 *pp_out = talloc_strdup(ctx, prefix);
577         }
578
579         TALLOC_FREE(prefix);
580
581         if (!*pp_out) {
582                 M_DEBUG(0,("talloc_fail"));
583                 return False;
584         }
585
586         return True;
587 }
588
589 /*
590   look for a DOS reserved name
591 */
592 static bool is_reserved_name(const char *name)
593 {
594         if (FLAG_CHECK(name[0], FLAG_POSSIBLE1) &&
595             FLAG_CHECK(name[1], FLAG_POSSIBLE2) &&
596             FLAG_CHECK(name[2], FLAG_POSSIBLE3) &&
597             FLAG_CHECK(name[3], FLAG_POSSIBLE4)) {
598                 /* a likely match, scan the lot */
599                 int i;
600                 for (i=0; reserved_names[i]; i++) {
601                         int len = strlen(reserved_names[i]);
602                         /* note that we match on COM1 as well as COM1.foo */
603                         if (strnequal(name, reserved_names[i], len) &&
604                             (name[len] == '.' || name[len] == 0)) {
605                                 return True;
606                         }
607                 }
608         }
609
610         return False;
611 }
612
613 /*
614  See if a filename is a legal long filename.
615  A filename ending in a '.' is not legal unless it's "." or "..". JRA.
616  A filename ending in ' ' is not legal either. See bug id #2769.
617 */
618
619 static bool is_legal_name(const char *name)
620 {
621         const char *dot_pos = NULL;
622         bool alldots = True;
623         size_t numdots = 0;
624
625         while (*name) {
626                 if (((unsigned int)name[0]) > 128 && (name[1] != 0)) {
627                         /* Possible start of mb character. */
628                         char mbc[2];
629                         /*
630                          * Note that if CH_UNIX is utf8 a string may be 3
631                          * bytes, but this is ok as mb utf8 characters don't
632                          * contain embedded ascii bytes. We are really checking
633                          * for mb UNIX asian characters like Japanese (SJIS) here.
634                          * JRA.
635                          */
636                         if (convert_string(CH_UNIX, CH_UTF16LE, name, 2, mbc, 2) == 2) {
637                                 /* Was a good mb string. */
638                                 name += 2;
639                                 continue;
640                         }
641                 }
642
643                 if (FLAG_CHECK(name[0], FLAG_ILLEGAL)) {
644                         return False;
645                 }
646                 if (name[0] == '.') {
647                         dot_pos = name;
648                         numdots++;
649                 } else {
650                         alldots = False;
651                 }
652                 if ((name[0] == ' ') && (name[1] == '\0')) {
653                         /* Can't end in ' ' */
654                         return False;
655                 }
656                 name++;
657         }
658
659         if (dot_pos) {
660                 if (alldots && (numdots == 1 || numdots == 2))
661                         return True; /* . or .. is a valid name */
662
663                 /* A valid long name cannot end in '.' */
664                 if (dot_pos[1] == '\0')
665                         return False;
666         }
667         return True;
668 }
669
670 static bool must_mangle(const char *name,
671                         const struct share_params *p)
672 {
673         if (is_reserved_name(name)) {
674                 return True;
675         }
676         return !is_legal_name(name);
677 }
678
679 /*
680   the main forward mapping function, which converts a long filename to 
681   a 8.3 name
682
683   if cache83 is not set then we don't cache the result
684
685 */
686 static bool hash2_name_to_8_3(const char *name,
687                         char new_name[13],
688                         bool cache83,
689                         int default_case,
690                         const struct share_params *p)
691 {
692         char *dot_p;
693         char lead_chars[7];
694         char extension[4];
695         unsigned int extension_length, i;
696         unsigned int prefix_len;
697         unsigned int hash, v;
698
699         /* reserved names are handled specially */
700         if (!is_reserved_name(name)) {
701                 /* if the name is already a valid 8.3 name then we don't need to
702                  * change anything */
703                 if (is_legal_name(name) && is_8_3(name, False, False, p)) {
704                         safe_strcpy(new_name, name, 12);
705                         return True;
706                 }
707         }
708
709         /* find the '.' if any */
710         dot_p = strrchr(name, '.');
711
712         if (dot_p) {
713                 /* if the extension contains any illegal characters or
714                    is too long or zero length then we treat it as part
715                    of the prefix */
716                 for (i=0; i<4 && dot_p[i+1]; i++) {
717                         if (! FLAG_CHECK(dot_p[i+1], FLAG_ASCII)) {
718                                 dot_p = NULL;
719                                 break;
720                         }
721                 }
722                 if (i == 0 || i == 4) {
723                         dot_p = NULL;
724                 }
725         }
726
727         /* the leading characters in the mangled name is taken from
728            the first characters of the name, if they are ascii otherwise
729            '_' is used
730         */
731         for (i=0;i<mangle_prefix && name[i];i++) {
732                 lead_chars[i] = name[i];
733                 if (! FLAG_CHECK(lead_chars[i], FLAG_ASCII)) {
734                         lead_chars[i] = '_';
735                 }
736                 lead_chars[i] = toupper_ascii(lead_chars[i]);
737         }
738         for (;i<mangle_prefix;i++) {
739                 lead_chars[i] = '_';
740         }
741
742         /* the prefix is anything up to the first dot */
743         if (dot_p) {
744                 prefix_len = PTR_DIFF(dot_p, name);
745         } else {
746                 prefix_len = strlen(name);
747         }
748
749         /* the extension of the mangled name is taken from the first 3
750            ascii chars after the dot */
751         extension_length = 0;
752         if (dot_p) {
753                 for (i=1; extension_length < 3 && dot_p[i]; i++) {
754                         char c = dot_p[i];
755                         if (FLAG_CHECK(c, FLAG_ASCII)) {
756                                 extension[extension_length++] =
757                                         toupper_ascii(c);
758                         }
759                 }
760         }
761
762         /* find the hash for this prefix */
763         v = hash = mangle_hash(name, prefix_len);
764
765         /* now form the mangled name. */
766         for (i=0;i<mangle_prefix;i++) {
767                 new_name[i] = lead_chars[i];
768         }
769         new_name[7] = base_forward(v % 36);
770         new_name[6] = '~';
771         for (i=5; i>=mangle_prefix; i--) {
772                 v = v / 36;
773                 new_name[i] = base_forward(v % 36);
774         }
775
776         /* add the extension */
777         if (extension_length) {
778                 new_name[8] = '.';
779                 memcpy(&new_name[9], extension, extension_length);
780                 new_name[9+extension_length] = 0;
781         } else {
782                 new_name[8] = 0;
783         }
784
785         if (cache83) {
786                 /* put it in the cache */
787                 cache_insert(name, prefix_len, hash);
788         }
789
790         M_DEBUG(10,("hash2_name_to_8_3: %s -> %08X -> %s (cache=%d)\n",
791                    name, hash, new_name, cache83));
792
793         return True;
794 }
795
796 /*
797   the following provides the abstraction layer to make it easier
798   to drop in an alternative mangling implementation */
799 static const struct mangle_fns mangle_hash2_fns = {
800         mangle_reset,
801         is_mangled,
802         must_mangle,
803         is_8_3,
804         lookup_name_from_8_3,
805         hash2_name_to_8_3
806 };
807
808 /* return the methods for this mangling implementation */
809 const struct mangle_fns *mangle_hash2_init(void)
810 {
811         /* the mangle prefix can only be in the mange 1 to 6 */
812         mangle_prefix = lp_mangle_prefix();
813         if (mangle_prefix > 6) {
814                 mangle_prefix = 6;
815         }
816         if (mangle_prefix < 1) {
817                 mangle_prefix = 1;
818         }
819
820 #if DYNAMIC_MANGLE_TABLES
821         init_tables();
822 #endif
823         mangle_reset();
824
825         return &mangle_hash2_fns;
826 }
827
828 static void posix_mangle_reset(void)
829 {;}
830
831 static bool posix_is_mangled(const char *s, const struct share_params *p)
832 {
833         return False;
834 }
835
836 static bool posix_must_mangle(const char *s, const struct share_params *p)
837 {
838         return False;
839 }
840
841 static bool posix_is_8_3(const char *fname,
842                         bool check_case,
843                         bool allow_wildcards,
844                         const struct share_params *p)
845 {
846         return False;
847 }
848
849 static bool posix_lookup_name_from_8_3(TALLOC_CTX *ctx,
850                                 const char *in,
851                                 char **out, /* talloced on the given context. */
852                                 const struct share_params *p)
853 {
854         return False;
855 }
856
857 static bool posix_name_to_8_3(const char *in,
858                                 char out[13],
859                                 bool cache83,
860                                 int default_case,
861                                 const struct share_params *p)
862 {
863         memset(out, '\0', 13);
864         return True;
865 }
866
867 /* POSIX paths backend - no mangle. */
868 static const struct mangle_fns posix_mangle_fns = {
869         posix_mangle_reset,
870         posix_is_mangled,
871         posix_must_mangle,
872         posix_is_8_3,
873         posix_lookup_name_from_8_3,
874         posix_name_to_8_3
875 };
876
877 const struct mangle_fns *posix_mangle_init(void)
878 {
879         return &posix_mangle_fns;
880 }