s3-build: include mangle.h only where needed.
[amitay/samba.git] / source3 / smbd / mangle_hash.c
1 /*
2    Unix SMB/CIFS implementation.
3    Name mangling
4    Copyright (C) Andrew Tridgell 1992-2002
5    Copyright (C) Simo Sorce 2001
6    Copyright (C) Andrew Bartlett 2002
7    Copyright (C) Jeremy Allison 2007
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "smbd/globals.h"
25 #include "mangle.h"
26
27 /* -------------------------------------------------------------------------- **
28  * Other stuff...
29  *
30  * magic_char     - This is the magic char used for mangling.  It's
31  *                  global.  There is a call to lp_magicchar() in server.c
32  *                  that is used to override the initial value.
33  *
34  * MANGLE_BASE    - This is the number of characters we use for name mangling.
35  *
36  * basechars      - The set characters used for name mangling.  This
37  *                  is static (scope is this file only).
38  *
39  * mangle()       - Macro used to select a character from basechars (i.e.,
40  *                  mangle(n) will return the nth digit, modulo MANGLE_BASE).
41  *
42  * chartest       - array 0..255.  The index range is the set of all possible
43  *                  values of a byte.  For each byte value, the content is a
44  *                  two nibble pair.  See BASECHAR_MASK below.
45  *
46  * ct_initialized - False until the chartest array has been initialized via
47  *                  a call to init_chartest().
48  *
49  * BASECHAR_MASK  - Masks the upper nibble of a one-byte value.
50  *
51  * isbasecahr()   - Given a character, check the chartest array to see
52  *                  if that character is in the basechars set.  This is
53  *                  faster than using strchr_m().
54  *
55  */
56
57 static const char basechars[43]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_-!@#$%";
58 #define MANGLE_BASE       (sizeof(basechars)/sizeof(char)-1)
59
60 #define mangle(V) ((char)(basechars[(V) % MANGLE_BASE]))
61 #define BASECHAR_MASK 0xf0
62 #define isbasechar(C) ( (chartest[ ((C) & 0xff) ]) & BASECHAR_MASK )
63
64 /* -------------------------------------------------------------------- */
65
66 static NTSTATUS has_valid_83_chars(const smb_ucs2_t *s, bool allow_wildcards)
67 {
68         if (!*s) {
69                 return NT_STATUS_INVALID_PARAMETER;
70         }
71
72         if (!allow_wildcards && ms_has_wild_w(s)) {
73                 return NT_STATUS_UNSUCCESSFUL;
74         }
75
76         while (*s) {
77                 if(!isvalid83_w(*s)) {
78                         return NT_STATUS_UNSUCCESSFUL;
79                 }
80                 s++;
81         }
82
83         return NT_STATUS_OK;
84 }
85
86 static NTSTATUS has_illegal_chars(const smb_ucs2_t *s, bool allow_wildcards)
87 {
88         if (!allow_wildcards && ms_has_wild_w(s)) {
89                 return NT_STATUS_UNSUCCESSFUL;
90         }
91
92         while (*s) {
93                 if (*s <= 0x1f) {
94                         /* Control characters. */
95                         return NT_STATUS_UNSUCCESSFUL;
96                 }
97                 switch(*s) {
98                         case UCS2_CHAR('\\'):
99                         case UCS2_CHAR('/'):
100                         case UCS2_CHAR('|'):
101                         case UCS2_CHAR(':'):
102                                 return NT_STATUS_UNSUCCESSFUL;
103                 }
104                 s++;
105         }
106
107         return NT_STATUS_OK;
108 }
109
110 /* return False if something fail and
111  * return 2 alloced unicode strings that contain prefix and extension
112  */
113
114 static NTSTATUS mangle_get_prefix(const smb_ucs2_t *ucs2_string, smb_ucs2_t **prefix,
115                 smb_ucs2_t **extension, bool allow_wildcards)
116 {
117         size_t ext_len;
118         smb_ucs2_t *p;
119
120         *extension = 0;
121         *prefix = strdup_w(ucs2_string);
122         if (!*prefix) {
123                 return NT_STATUS_NO_MEMORY;
124         }
125         if ((p = strrchr_w(*prefix, UCS2_CHAR('.')))) {
126                 ext_len = strlen_w(p+1);
127                 if ((ext_len > 0) && (ext_len < 4) && (p != *prefix) &&
128                     (NT_STATUS_IS_OK(has_valid_83_chars(p+1,allow_wildcards)))) /* check extension */ {
129                         *p = 0;
130                         *extension = strdup_w(p+1);
131                         if (!*extension) {
132                                 SAFE_FREE(*prefix);
133                                 return NT_STATUS_NO_MEMORY;
134                         }
135                 }
136         }
137         return NT_STATUS_OK;
138 }
139
140 /* ************************************************************************** **
141  * Return NT_STATUS_UNSUCCESSFUL if a name is a special msdos reserved name.
142  * or contains illegal characters.
143  *
144  *  Input:  fname - String containing the name to be tested.
145  *
146  *  Output: NT_STATUS_UNSUCCESSFUL, if the condition above is true.
147  *
148  *  Notes:  This is a static function called by is_8_3(), below.
149  *
150  * ************************************************************************** **
151  */
152
153 static NTSTATUS is_valid_name(const smb_ucs2_t *fname, bool allow_wildcards, bool only_8_3)
154 {
155         smb_ucs2_t *str, *p;
156         size_t num_ucs2_chars;
157         NTSTATUS ret = NT_STATUS_OK;
158
159         if (!fname || !*fname)
160                 return NT_STATUS_INVALID_PARAMETER;
161
162         /* . and .. are valid names. */
163         if (strcmp_wa(fname, ".")==0 || strcmp_wa(fname, "..")==0)
164                 return NT_STATUS_OK;
165
166         if (only_8_3) {
167                 ret = has_valid_83_chars(fname, allow_wildcards);
168                 if (!NT_STATUS_IS_OK(ret))
169                         return ret;
170         }
171
172         ret = has_illegal_chars(fname, allow_wildcards);
173         if (!NT_STATUS_IS_OK(ret))
174                 return ret;
175
176         /* Name can't end in '.' or ' ' */
177         num_ucs2_chars = strlen_w(fname);
178         if (fname[num_ucs2_chars-1] == UCS2_CHAR('.') || fname[num_ucs2_chars-1] == UCS2_CHAR(' ')) {
179                 return NT_STATUS_UNSUCCESSFUL;
180         }
181
182         str = strdup_w(fname);
183
184         /* Truncate copy after the first dot. */
185         p = strchr_w(str, UCS2_CHAR('.'));
186         if (p) {
187                 *p = 0;
188         }
189
190         strupper_w(str);
191         p = &str[1];
192
193         switch(str[0])
194         {
195         case UCS2_CHAR('A'):
196                 if(strcmp_wa(p, "UX") == 0)
197                         ret = NT_STATUS_UNSUCCESSFUL;
198                 break;
199         case UCS2_CHAR('C'):
200                 if((strcmp_wa(p, "LOCK$") == 0)
201                 || (strcmp_wa(p, "ON") == 0)
202                 || (strcmp_wa(p, "OM1") == 0)
203                 || (strcmp_wa(p, "OM2") == 0)
204                 || (strcmp_wa(p, "OM3") == 0)
205                 || (strcmp_wa(p, "OM4") == 0)
206                 )
207                         ret = NT_STATUS_UNSUCCESSFUL;
208                 break;
209         case UCS2_CHAR('L'):
210                 if((strcmp_wa(p, "PT1") == 0)
211                 || (strcmp_wa(p, "PT2") == 0)
212                 || (strcmp_wa(p, "PT3") == 0)
213                 )
214                         ret = NT_STATUS_UNSUCCESSFUL;
215                 break;
216         case UCS2_CHAR('N'):
217                 if(strcmp_wa(p, "UL") == 0)
218                         ret = NT_STATUS_UNSUCCESSFUL;
219                 break;
220         case UCS2_CHAR('P'):
221                 if(strcmp_wa(p, "RN") == 0)
222                         ret = NT_STATUS_UNSUCCESSFUL;
223                 break;
224         default:
225                 break;
226         }
227
228         SAFE_FREE(str);
229         return ret;
230 }
231
232 static NTSTATUS is_8_3_w(const smb_ucs2_t *fname, bool allow_wildcards)
233 {
234         smb_ucs2_t *pref = 0, *ext = 0;
235         size_t plen;
236         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
237
238         if (!fname || !*fname)
239                 return NT_STATUS_INVALID_PARAMETER;
240
241         if (strlen_w(fname) > 12)
242                 return NT_STATUS_UNSUCCESSFUL;
243
244         if (strcmp_wa(fname, ".") == 0 || strcmp_wa(fname, "..") == 0)
245                 return NT_STATUS_OK;
246
247         /* Name cannot start with '.' */
248         if (*fname == UCS2_CHAR('.'))
249                 return NT_STATUS_UNSUCCESSFUL;
250
251         if (!NT_STATUS_IS_OK(is_valid_name(fname, allow_wildcards, True)))
252                 goto done;
253
254         if (!NT_STATUS_IS_OK(mangle_get_prefix(fname, &pref, &ext, allow_wildcards)))
255                 goto done;
256         plen = strlen_w(pref);
257
258         if (strchr_wa(pref, '.'))
259                 goto done;
260         if (plen < 1 || plen > 8)
261                 goto done;
262         if (ext && (strlen_w(ext) > 3))
263                 goto done;
264
265         ret = NT_STATUS_OK;
266
267 done:
268         SAFE_FREE(pref);
269         SAFE_FREE(ext);
270         return ret;
271 }
272
273 static bool is_8_3(const char *fname, bool check_case, bool allow_wildcards,
274                    const struct share_params *p)
275 {
276         const char *f;
277         smb_ucs2_t *ucs2name;
278         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
279         size_t size;
280         char magic_char;
281
282         magic_char = lp_magicchar(p);
283
284         if (!fname || !*fname)
285                 return False;
286         if ((f = strrchr(fname, '/')) == NULL)
287                 f = fname;
288         else
289                 f++;
290
291         if (strlen(f) > 12)
292                 return False;
293
294         if (!push_ucs2_talloc(NULL, &ucs2name, f, &size)) {
295                 DEBUG(0,("is_8_3: internal error push_ucs2_talloc() failed!\n"));
296                 goto done;
297         }
298
299         ret = is_8_3_w(ucs2name, allow_wildcards);
300
301 done:
302         TALLOC_FREE(ucs2name);
303
304         if (!NT_STATUS_IS_OK(ret)) {
305                 return False;
306         }
307
308         return True;
309 }
310
311 /* -------------------------------------------------------------------------- **
312  * Functions...
313  */
314
315 /* ************************************************************************** **
316  * Initialize the static character test array.
317  *
318  *  Input:  none
319  *
320  *  Output: none
321  *
322  *  Notes:  This function changes (loads) the contents of the <chartest>
323  *          array.  The scope of <chartest> is this file.
324  *
325  * ************************************************************************** **
326  */
327
328 static void init_chartest( void )
329 {
330         const unsigned char *s;
331
332         chartest = SMB_MALLOC_ARRAY(unsigned char, 256);
333
334         SMB_ASSERT(chartest != NULL);
335         memset(chartest, '\0', 256);
336
337         for( s = (const unsigned char *)basechars; *s; s++ ) {
338                 chartest[*s] |= BASECHAR_MASK;
339         }
340 }
341
342 /* ************************************************************************** **
343  * Return True if the name *could be* a mangled name.
344  *
345  *  Input:  s - A path name - in UNIX pathname format.
346  *
347  *  Output: True if the name matches the pattern described below in the
348  *          notes, else False.
349  *
350  *  Notes:  The input name is *not* tested for 8.3 compliance.  This must be
351  *          done separately.  This function returns true if the name contains
352  *          a magic character followed by excactly two characters from the
353  *          basechars list (above), which in turn are followed either by the
354  *          nul (end of string) byte or a dot (extension) or by a '/' (end of
355  *          a directory name).
356  *
357  * ************************************************************************** **
358  */
359
360 static bool is_mangled(const char *s, const struct share_params *p)
361 {
362         char *magic;
363         char magic_char;
364
365         magic_char = lp_magicchar(p);
366
367         if (chartest == NULL) {
368                 init_chartest();
369         }
370
371         magic = strchr_m( s, magic_char );
372         while( magic && magic[1] && magic[2] ) {         /* 3 chars, 1st is magic. */
373                 if( ('.' == magic[3] || '/' == magic[3] || !(magic[3]))          /* Ends with '.' or nul or '/' ?  */
374                                 && isbasechar( toupper_ascii(magic[1]) )           /* is 2nd char basechar?  */
375                                 && isbasechar( toupper_ascii(magic[2]) ) )         /* is 3rd char basechar?  */
376                         return( True );                           /* If all above, then true, */
377                 magic = strchr_m( magic+1, magic_char );      /*    else seek next magic. */
378         }
379         return( False );
380 }
381
382 /***************************************************************************
383  Initializes or clears the mangled cache.
384 ***************************************************************************/
385
386 static void mangle_reset( void )
387 {
388         /* We could close and re-open the tdb here... should we ? The old code did
389            the equivalent... JRA. */
390 }
391
392 /***************************************************************************
393  Add a mangled name into the cache.
394  If the extension of the raw name maps directly to the
395  extension of the mangled name, then we'll store both names
396  *without* extensions.  That way, we can provide consistent
397  reverse mangling for all names that match.  The test here is
398  a bit more careful than the one done in earlier versions of
399  mangle.c:
400
401     - the extension must exist on the raw name,
402     - it must be all lower case
403     - it must match the mangled extension (to prove that no
404       mangling occurred).
405   crh 07-Apr-1998
406 **************************************************************************/
407
408 static void cache_mangled_name( const char mangled_name[13],
409                                 const char *raw_name )
410 {
411         TDB_DATA data_val;
412         char mangled_name_key[13];
413         char *s1 = NULL;
414         char *s2 = NULL;
415
416         /* If the cache isn't initialized, give up. */
417         if( !tdb_mangled_cache )
418                 return;
419
420         /* Init the string lengths. */
421         safe_strcpy(mangled_name_key, mangled_name, sizeof(mangled_name_key)-1);
422
423         /* See if the extensions are unmangled.  If so, store the entry
424          * without the extension, thus creating a "group" reverse map.
425          */
426         s1 = strrchr( mangled_name_key, '.' );
427         if( s1 && (s2 = strrchr( raw_name, '.' )) ) {
428                 size_t i = 1;
429                 while( s1[i] && (tolower_ascii( s1[i] ) == s2[i]) )
430                         i++;
431                 if( !s1[i] && !s2[i] ) {
432                         /* Truncate at the '.' */
433                         *s1 = '\0';
434                         /*
435                          * DANGER WILL ROBINSON - this
436                          * is changing a const string via
437                          * an aliased pointer ! Remember to
438                          * put it back once we've used it.
439                          * JRA
440                          */
441                         *s2 = '\0';
442                 }
443         }
444
445         /* Allocate a new cache entry.  If the allocation fails, just return. */
446         data_val = string_term_tdb_data(raw_name);
447         if (tdb_store_bystring(tdb_mangled_cache, mangled_name_key, data_val, TDB_REPLACE) != 0) {
448                 DEBUG(0,("cache_mangled_name: Error storing entry %s -> %s\n", mangled_name_key, raw_name));
449         } else {
450                 DEBUG(5,("cache_mangled_name: Stored entry %s -> %s\n", mangled_name_key, raw_name));
451         }
452         /* Restore the change we made to the const string. */
453         if (s2) {
454                 *s2 = '.';
455         }
456 }
457
458 /* ************************************************************************** **
459  * Check for a name on the mangled name stack
460  *
461  *  Input:  s - Input *and* output string buffer.
462  *          maxlen - space in i/o string buffer.
463  *  Output: True if the name was found in the cache, else False.
464  *
465  *  Notes:  If a reverse map is found, the function will overwrite the string
466  *          space indicated by the input pointer <s>.  This is frightening.
467  *          It should be rewritten to return NULL if the long name was not
468  *          found, and a pointer to the long name if it was found.
469  *
470  * ************************************************************************** **
471  */
472
473 static bool lookup_name_from_8_3(TALLOC_CTX *ctx,
474                                 const char *in,
475                                 char **out, /* talloced on the given context. */
476                                 const struct share_params *p)
477 {
478         TDB_DATA data_val;
479         char *saved_ext = NULL;
480         char *s = talloc_strdup(ctx, in);
481         char magic_char;
482
483         magic_char = lp_magicchar(p);
484
485         /* If the cache isn't initialized, give up. */
486         if(!s || !tdb_mangled_cache ) {
487                 TALLOC_FREE(s);
488                 return False;
489         }
490
491         data_val = tdb_fetch_bystring(tdb_mangled_cache, s);
492
493         /* If we didn't find the name *with* the extension, try without. */
494         if(data_val.dptr == NULL || data_val.dsize == 0) {
495                 char *ext_start = strrchr( s, '.' );
496                 if( ext_start ) {
497                         if((saved_ext = talloc_strdup(ctx,ext_start)) == NULL) {
498                                 TALLOC_FREE(s);
499                                 return False;
500                         }
501
502                         *ext_start = '\0';
503                         data_val = tdb_fetch_bystring(tdb_mangled_cache, s);
504                         /*
505                          * At this point s is the name without the
506                          * extension. We re-add the extension if saved_ext
507                          * is not null, before freeing saved_ext.
508                          */
509                 }
510         }
511
512         /* Okay, if we haven't found it we're done. */
513         if(data_val.dptr == NULL || data_val.dsize == 0) {
514                 TALLOC_FREE(saved_ext);
515                 TALLOC_FREE(s);
516                 return False;
517         }
518
519         /* If we *did* find it, we need to talloc it on the given ctx. */
520         if (saved_ext) {
521                 *out = talloc_asprintf(ctx, "%s%s",
522                                         (char *)data_val.dptr,
523                                         saved_ext);
524         } else {
525                 *out = talloc_strdup(ctx, (char *)data_val.dptr);
526         }
527
528         TALLOC_FREE(s);
529         TALLOC_FREE(saved_ext);
530         SAFE_FREE(data_val.dptr);
531
532         return *out ? True : False;
533 }
534
535 /*****************************************************************************
536  Do the actual mangling to 8.3 format.
537 *****************************************************************************/
538
539 static bool to_8_3(char magic_char, const char *in, char out[13], int default_case)
540 {
541         int csum;
542         char *p;
543         char extension[4];
544         char base[9];
545         int baselen = 0;
546         int extlen = 0;
547         char *s = SMB_STRDUP(in);
548
549         extension[0] = 0;
550         base[0] = 0;
551
552         if (!s) {
553                 return False;
554         }
555
556         p = strrchr(s,'.');
557         if( p && (strlen(p+1) < (size_t)4) ) {
558                 bool all_normal = ( strisnormal(p+1, default_case) ); /* XXXXXXXXX */
559
560                 if( all_normal && p[1] != 0 ) {
561                         *p = 0;
562                         csum = str_checksum( s );
563                         *p = '.';
564                 } else
565                         csum = str_checksum(s);
566         } else
567                 csum = str_checksum(s);
568
569         strupper_m( s );
570
571         if( p ) {
572                 if( p == s )
573                         safe_strcpy( extension, "___", 3 );
574                 else {
575                         *p++ = 0;
576                         while( *p && extlen < 3 ) {
577                                 if ( *p != '.') {
578                                         extension[extlen++] = p[0];
579                                 }
580                                 p++;
581                         }
582                         extension[extlen] = 0;
583                 }
584         }
585
586         p = s;
587
588         while( *p && baselen < 5 ) {
589                 if (isbasechar(*p)) {
590                         base[baselen++] = p[0];
591                 }
592                 p++;
593         }
594         base[baselen] = 0;
595
596         csum = csum % (MANGLE_BASE*MANGLE_BASE);
597
598         memcpy(out, base, baselen);
599         out[baselen] = magic_char;
600         out[baselen+1] = mangle( csum/MANGLE_BASE );
601         out[baselen+2] = mangle( csum );
602
603         if( *extension ) {
604                 out[baselen+3] = '.';
605                 safe_strcpy(&out[baselen+4], extension, 3);
606         }
607
608         SAFE_FREE(s);
609         return True;
610 }
611
612 static bool must_mangle(const char *name,
613                         const struct share_params *p)
614 {
615         smb_ucs2_t *name_ucs2 = NULL;
616         NTSTATUS status;
617         size_t converted_size;
618         char magic_char;
619
620         magic_char = lp_magicchar(p);
621
622         if (!push_ucs2_talloc(NULL, &name_ucs2, name, &converted_size)) {
623                 DEBUG(0, ("push_ucs2_talloc failed!\n"));
624                 return False;
625         }
626         status = is_valid_name(name_ucs2, False, False);
627         TALLOC_FREE(name_ucs2);
628         /* We return true if we *must* mangle, so if it's
629          * a valid name (status == OK) then we must return
630          * false. Bug #6939. */
631         return !NT_STATUS_IS_OK(status);
632 }
633
634 /*****************************************************************************
635  * Convert a filename to DOS format.  Return True if successful.
636  *  Input:  in        Incoming name.
637  *
638  *          out       8.3 DOS name.
639  *
640  *          cache83 - If False, the mangled name cache will not be updated.
641  *                    This is usually used to prevent that we overwrite
642  *                    a conflicting cache entry prematurely, i.e. before
643  *                    we know whether the client is really interested in the
644  *                    current name.  (See PR#13758).  UKD.
645  *
646  * ****************************************************************************
647  */
648
649 static bool hash_name_to_8_3(const char *in,
650                         char out[13],
651                         bool cache83,
652                         int default_case,
653                         const struct share_params *p)
654 {
655         smb_ucs2_t *in_ucs2 = NULL;
656         size_t converted_size;
657         char magic_char;
658
659         magic_char = lp_magicchar(p);
660
661         DEBUG(5,("hash_name_to_8_3( %s, cache83 = %s)\n", in,
662                  cache83 ? "True" : "False"));
663
664         if (!push_ucs2_talloc(NULL, &in_ucs2, in, &converted_size)) {
665                 DEBUG(0, ("push_ucs2_talloc failed!\n"));
666                 return False;
667         }
668
669         /* If it's already 8.3, just copy. */
670         if (NT_STATUS_IS_OK(is_valid_name(in_ucs2, False, False)) &&
671                                 NT_STATUS_IS_OK(is_8_3_w(in_ucs2, False))) {
672                 TALLOC_FREE(in_ucs2);
673                 safe_strcpy(out, in, 12);
674                 return True;
675         }
676
677         TALLOC_FREE(in_ucs2);
678         if (!to_8_3(magic_char, in, out, default_case)) {
679                 return False;
680         }
681
682         cache_mangled_name(out, in);
683
684         DEBUG(5,("hash_name_to_8_3(%s) ==> [%s]\n", in, out));
685         return True;
686 }
687
688 /*
689   the following provides the abstraction layer to make it easier
690   to drop in an alternative mangling implementation
691 */
692 static const struct mangle_fns mangle_hash_fns = {
693         mangle_reset,
694         is_mangled,
695         must_mangle,
696         is_8_3,
697         lookup_name_from_8_3,
698         hash_name_to_8_3
699 };
700
701 /* return the methods for this mangling implementation */
702 const struct mangle_fns *mangle_hash_init(void)
703 {
704         mangle_reset();
705
706         /* Create the in-memory tdb using our custom hash function. */
707         tdb_mangled_cache = tdb_open_ex("mangled_cache", 1031, TDB_INTERNAL,
708                                 (O_RDWR|O_CREAT), 0644, NULL, fast_string_hash);
709
710         return &mangle_hash_fns;
711 }