introduce mangle backward compatibility functions
[kamenim/samba.git] / source3 / smbd / mangle.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Name mangling
5    Copyright (C) Andrew Tridgell 1992-1998
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 2 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, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 /* -------------------------------------------------------------------------- **
23  * Notable problems...
24  *
25  *  March/April 1998  CRH
26  *  - Many of the functions in this module overwrite string buffers passed to
27  *    them.  This causes a variety of problems and is, generally speaking,
28  *    dangerous and scarry.  See the kludge notes in name_map_mangle()
29  *    below.
30  *  - It seems that something is calling name_map_mangle() twice.  The
31  *    first call is probably some sort of test.  Names which contain
32  *    illegal characters are being doubly mangled.  I'm not sure, but
33  *    I'm guessing the problem is in server.c.
34  *
35  * -------------------------------------------------------------------------- **
36  */
37
38 /* -------------------------------------------------------------------------- **
39  * History...
40  *
41  *  March/April 1998  CRH
42  *  Updated a bit.  Rewrote is_mangled() to be a bit more selective.
43  *  Rewrote the mangled name cache.  Added comments here and there.
44  *  &c.
45  * -------------------------------------------------------------------------- **
46  */
47
48 #include "includes.h"
49
50
51 /* -------------------------------------------------------------------------- **
52  * External Variables...
53  */
54
55 extern int case_default;    /* Are conforming 8.3 names all upper or lower?   */
56 extern BOOL case_mangle;    /* If true, all chars in 8.3 should be same case. */
57
58
59 /* -------------------------------------------------------------------------- **
60  * Other stuff...
61  *
62  * magic_char     - This is the magic char used for mangling.  It's
63  *                  global.  There is a call to lp_magicchar() in server.c
64  *                  that is used to override the initial value.
65  *
66  * MANGLE_BASE    - This is the number of characters we use for name mangling.
67  *
68  * basechars      - The set characters used for name mangling.  This
69  *                  is static (scope is this file only).
70  *
71  * mangle()       - Macro used to select a character from basechars (i.e.,
72  *                  mangle(n) will return the nth digit, modulo MANGLE_BASE).
73  *
74  * chartest       - array 0..255.  The index range is the set of all possible
75  *                  values of a byte.  For each byte value, the content is a
76  *                  two nibble pair.  See BASECHAR_MASK and ILLEGAL_MASK,
77  *                  below.
78  *
79  * ct_initialized - False until the chartest array has been initialized via
80  *                  a call to init_chartest().
81  *
82  * BASECHAR_MASK  - Masks the upper nibble of a one-byte value.
83  *
84  * ILLEGAL_MASK   - Masks the lower nibble of a one-byte value.
85  *
86  * isbasecahr()   - Given a character, check the chartest array to see
87  *                  if that character is in the basechars set.  This is
88  *                  faster than using strchr_m().
89  *
90  * isillegal()    - Given a character, check the chartest array to see
91  *                  if that character is in the illegal characters set.
92  *                  This is faster than using strchr_m().
93  *
94  * mangled_cache  - Cache header used for storing mangled -> original
95  *                  reverse maps.
96  *
97  * mc_initialized - False until the mangled_cache structure has been
98  *                  initialized via a call to reset_mangled_cache().
99  *
100  * MANGLED_CACHE_MAX_ENTRIES - Default maximum number of entries for the
101  *                  cache.  A value of 0 indicates "infinite".
102  *
103  * MANGLED_CACHE_MAX_MEMORY  - Default maximum amount of memory for the
104  *                  cache.  When the cache was kept as an array of 256
105  *                  byte strings, the default cache size was 50 entries.
106  *                  This required a fixed 12.5Kbytes of memory.  The
107  *                  mangled stack parameter is no longer used (though
108  *                  this might change).  We're now using a fixed 16Kbyte
109  *                  maximum cache size.  This will probably be much more
110  *                  than 50 entries.
111  */
112
113 char magic_char = '~';
114
115
116 #if 1
117
118
119
120
121
122 static char basechars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_-!@#$%";
123 #define MANGLE_BASE       ( (sizeof(basechars)/sizeof(char)) - 1 )
124
125 static unsigned char chartest[256]  = { 0 };
126 static BOOL          ct_initialized = False;
127
128 #define mangle(V) ((char)(basechars[(V) % MANGLE_BASE]))
129 #define BASECHAR_MASK 0xf0
130 #define ILLEGAL_MASK  0x0f
131 #define isbasechar(C) ( (chartest[ ((C) & 0xff) ]) & BASECHAR_MASK )
132 #define isillegal(C) ( (chartest[ ((C) & 0xff) ]) & ILLEGAL_MASK )
133
134 static ubi_cacheRoot mangled_cache[1] = {{ { 0, 0, 0, 0 }, 0, 0, 0, 0, 0, 0 }};
135 static BOOL          mc_initialized   = False;
136 #define MANGLED_CACHE_MAX_ENTRIES 0
137 #define MANGLED_CACHE_MAX_MEMORY  16384
138
139
140 /* -------------------------------------------------------------------------- **
141  * Functions...
142  */
143
144 /* ************************************************************************** **
145  * Initialize the static character test array.
146  *
147  *  Input:  none
148  *
149  *  Output: none
150  *
151  *  Notes:  This function changes (loads) the contents of the <chartest>
152  *          array.  The scope of <chartest> is this file.
153  *
154  * ************************************************************************** **
155  */
156 static void init_chartest( void )
157   {
158   char          *illegalchars = "*\\/?<>|\":";
159   unsigned char *s;
160   
161   memset( (char *)chartest, '\0', 256 );
162
163   for( s = (unsigned char *)illegalchars; *s; s++ )
164     chartest[*s] = ILLEGAL_MASK;
165
166   for( s = (unsigned char *)basechars; *s; s++ )
167     chartest[*s] |= BASECHAR_MASK;
168
169   ct_initialized = True;
170   } /* init_chartest */
171
172 /* ************************************************************************** **
173  * Return True if a name is a special msdos reserved name.
174  *
175  *  Input:  fname - String containing the name to be tested.
176  *
177  *  Output: True, if the name matches one of the list of reserved names.
178  *
179  *  Notes:  This is a static function called by is_8_3(), below.
180  *
181  * ************************************************************************** **
182  */
183 static BOOL is_reserved_msdos( char *fname )
184   {
185   char upperFname[13];
186   char *p;
187
188   StrnCpy (upperFname, fname, 12);
189
190   /* lpt1.txt and con.txt etc are also illegal */
191   p = strchr_m(upperFname,'.');
192   if( p )
193     *p = '\0';
194
195   strupper( upperFname );
196   p = upperFname + 1;
197   switch( upperFname[0] )
198     {
199     case 'A':
200       if( 0 == strcmp( p, "UX" ) )
201         return( True );
202       break;
203     case 'C':
204       if( (0 == strcmp( p, "LOCK$" ))
205        || (0 == strcmp( p, "ON" ))
206        || (0 == strcmp( p, "OM1" ))
207        || (0 == strcmp( p, "OM2" ))
208        || (0 == strcmp( p, "OM3" ))
209        || (0 == strcmp( p, "OM4" ))
210         )
211         return( True );
212       break;
213     case 'L':
214       if( (0 == strcmp( p, "PT1" ))
215        || (0 == strcmp( p, "PT2" ))
216        || (0 == strcmp( p, "PT3" ))
217         )
218         return( True );
219       break;
220     case 'N':
221       if( 0 == strcmp( p, "UL" ) )
222         return( True );
223       break;
224     case 'P':
225       if( 0 == strcmp( p, "RN" ) )
226         return( True );
227       break;
228     }
229
230   return( False );
231   } /* is_reserved_msdos */
232
233 /* ************************************************************************** **
234  * Determine whether or not a given name contains illegal characters, even
235  * long names.
236  *
237  *  Input:  name  - The name to be tested.
238  *
239  *  Output: True if an illegal character was found in <name>, else False.
240  *
241  *  Notes:  This is used to test a name on the host system, long or short,
242  *          for characters that would be illegal on most client systems,
243  *          particularly DOS and Windows systems.  Unix and AmigaOS, for
244  *          example, allow a filenames which contain such oddities as
245  *          quotes (").  If a name is found which does contain an illegal
246  *          character, it is mangled even if it conforms to the 8.3
247  *          format.
248  *
249  * ************************************************************************** **
250  */
251 static BOOL is_illegal_name( char *name )
252   {
253   unsigned char *s;
254
255   if( !name )
256     return( True );
257
258   if( !ct_initialized )
259     init_chartest();
260
261   s = (unsigned char *)name;
262   while( *s )
263     {
264       if( *s>0x7F && isillegal( *s ) )
265         return( True );
266       else
267         s++;
268     }
269
270   return( False );
271   } /* is_illegal_name */
272
273 /* ************************************************************************** **
274  * Return True if the name *could be* a mangled name.
275  *
276  *  Input:  s - A path name - in UNIX pathname format.
277  *
278  *  Output: True if the name matches the pattern described below in the
279  *          notes, else False.
280  *
281  *  Notes:  The input name is *not* tested for 8.3 compliance.  This must be
282  *          done separately.  This function returns true if the name contains
283  *          a magic character followed by excactly two characters from the
284  *          basechars list (above), which in turn are followed either by the
285  *          nul (end of string) byte or a dot (extension) or by a '/' (end of
286  *          a directory name).
287  *
288  * ************************************************************************** **
289  */
290 BOOL is_mangled( char *s )
291   {
292   char *magic;
293
294   if( !ct_initialized )
295     init_chartest();
296
297   magic = strchr_m( s, magic_char );
298   while( magic && magic[1] && magic[2] )          /* 3 chars, 1st is magic. */
299     {
300     if( ('.' == magic[3] || '/' == magic[3] || !(magic[3]))          /* Ends with '.' or nul or '/' ?  */
301      && isbasechar( toupper(magic[1]) )           /* is 2nd char basechar?  */
302      && isbasechar( toupper(magic[2]) ) )         /* is 3rd char basechar?  */
303       return( True );                           /* If all above, then true, */
304     magic = strchr_m( magic+1, magic_char );      /*    else seek next magic. */
305     }
306   return( False );
307   } /* is_mangled */
308
309 /* ************************************************************************** **
310  * Return True if the name is a valid DOS name in 8.3 DOS format.
311  *
312  *  Input:  fname       - File name to be checked.
313  *          check_case  - If True, and if case_mangle is True, then the
314  *                        name will be checked to see if all characters
315  *                        are the correct case.  See case_mangle and
316  *                        case_default above.
317  *
318  *  Output: True if the name is a valid DOS name, else FALSE.
319  *
320  * ************************************************************************** **
321  */
322 BOOL is_8_3( char *fname, BOOL check_case )
323   {
324   int   len;
325   int   l;
326   char *p;
327   char *dot_pos;
328   char *slash_pos = strrchr_m( fname, '/' );
329
330   /* If there is a directory path, skip it. */
331   if( slash_pos )
332     fname = slash_pos + 1;
333   len = strlen( fname );
334
335   DEBUG( 5, ( "Checking %s for 8.3\n", fname ) );
336
337   /* Can't be 0 chars or longer than 12 chars */
338   if( (len == 0) || (len > 12) )
339     return( False );
340
341   /* Mustn't be an MS-DOS Special file such as lpt1 or even lpt1.txt */
342   if( is_reserved_msdos( fname ) )
343     return( False );
344
345   /* Check that all characters are the correct case, if asked to do so. */
346   if( check_case && case_mangle )
347     {
348     switch( case_default )
349       {
350       case CASE_LOWER:
351         if( strhasupper( fname ) )
352           return(False);
353         break;
354       case CASE_UPPER:
355         if( strhaslower( fname ) )
356           return(False);
357         break;
358       }
359     }
360
361   /* Can't contain invalid dos chars */
362   /* Windows use the ANSI charset.
363      But filenames are translated in the PC charset.
364      This Translation may be more or less relaxed depending
365      the Windows application. */
366
367   /* %%% A nice improvment to name mangling would be to translate
368      filename to ANSI charset on the smb server host */
369
370   p       = fname;
371   dot_pos = NULL;
372   while( *p )
373     {
374       if( *p == '.' && !dot_pos )
375         dot_pos = (char *)p;
376       /*else
377         if( !isdoschar( *p ) )
378           return( False );*/
379       p++;
380     }
381
382   /* no dot and less than 9 means OK */
383   if( !dot_pos )
384     return( len <= 8 );
385         
386   l = PTR_DIFF( dot_pos, fname );
387
388   /* base must be at least 1 char except special cases . and .. */
389   if( l == 0 )
390     return( 0 == strcmp( fname, "." ) || 0 == strcmp( fname, ".." ) );
391
392   /* base can't be greater than 8 */
393   if( l > 8 )
394     return( False );
395
396   /* see smb.conf(5) for a description of the 'strip dot' parameter. */
397   if( lp_strip_dot()
398    && len - l == 1
399    && !strchr_m( dot_pos + 1, '.' ) )
400     {
401     *dot_pos = 0;
402     return( True );
403     }
404
405   /* extension must be between 1 and 3 */
406   if( (len - l < 2 ) || (len - l > 4) )
407     return( False );
408
409   /* extensions may not have a dot */
410   if( strchr_m( dot_pos+1, '.' ) )
411     return( False );
412
413   /* must be in 8.3 format */
414   return( True );
415   } /* is_8_3 */
416
417
418 /* ************************************************************************** **
419  * Compare two cache keys and return a value indicating their ordinal
420  * relationship.
421  *
422  *  Input:  ItemPtr - Pointer to a comparison key.  In this case, this will
423  *                    be a mangled name string.
424  *          NodePtr - Pointer to a node in the cache.  The node structure
425  *                    will be followed in memory by a mangled name string.
426  *
427  *  Output: A signed integer, as follows:
428  *            (x < 0)  <==> Key1 less than Key2
429  *            (x == 0) <==> Key1 equals Key2
430  *            (x > 0)  <==> Key1 greater than Key2
431  *
432  *  Notes:  This is a ubiqx-style comparison routine.  See ubi_BinTree for
433  *          more info.
434  *
435  * ************************************************************************** **
436  */
437 static signed int cache_compare( ubi_btItemPtr ItemPtr, ubi_btNodePtr NodePtr )
438   {
439   char *Key1 = (char *)ItemPtr;
440   char *Key2 = (char *)(((ubi_cacheEntryPtr)NodePtr) + 1);
441
442   return( StrCaseCmp( Key1, Key2 ) );
443   } /* cache_compare */
444
445 /* ************************************************************************** **
446  * Free a cache entry.
447  *
448  *  Input:  WarrenZevon - Pointer to the entry that is to be returned to
449  *                        Nirvana.
450  *  Output: none.
451  *
452  *  Notes:  This function gets around the possibility that the standard
453  *          free() function may be implemented as a macro, or other evil
454  *          subversions (oh, so much fun).
455  *
456  * ************************************************************************** **
457  */
458 static void cache_free_entry( ubi_trNodePtr WarrenZevon )
459   {
460           ZERO_STRUCTP(WarrenZevon);
461           SAFE_FREE( WarrenZevon );
462   } /* cache_free_entry */
463
464 /* ************************************************************************** **
465  * Initializes or clears the mangled cache.
466  *
467  *  Input:  none.
468  *  Output: none.
469  *
470  *  Notes:  There is a section below that is commented out.  It shows how
471  *          one might use lp_ calls to set the maximum memory and entry size
472  *          of the cache.  You might also want to remove the constants used
473  *          in ubi_cacheInit() and replace them with lp_ calls.  If so, then
474  *          the calls to ubi_cacheSetMax*() would be moved into the else
475  *          clause.  Another option would be to pass in the max_entries and
476  *          max_memory values as parameters.  crh 09-Apr-1998.
477  *
478  * ************************************************************************** **
479  */
480 void reset_mangled_cache( void )
481   {
482   if( !mc_initialized )
483     {
484     (void)ubi_cacheInit( mangled_cache,
485                          cache_compare,
486                          cache_free_entry,
487                          MANGLED_CACHE_MAX_ENTRIES,
488                          MANGLED_CACHE_MAX_MEMORY );
489     mc_initialized = True;
490     }
491   else
492     {
493     (void)ubi_cacheClear( mangled_cache );
494     }
495
496   /*
497   (void)ubi_cacheSetMaxEntries( mangled_cache, lp_mangled_cache_entries() );
498   (void)ubi_cacheSetMaxMemory(  mangled_cache, lp_mangled_cache_memory() );
499   */
500   } /* reset_mangled_cache  */
501
502
503 /* ************************************************************************** **
504  * Add a mangled name into the cache.
505  *
506  *  Notes:  If the mangled cache has not been initialized, then the
507  *          function will simply fail.  It could initialize the cache,
508  *          but that's not the way it was done before I changed the
509  *          cache mechanism, so I'm sticking with the old method.
510  *
511  *          If the extension of the raw name maps directly to the
512  *          extension of the mangled name, then we'll store both names
513  *          *without* extensions.  That way, we can provide consistent
514  *          reverse mangling for all names that match.  The test here is
515  *          a bit more careful than the one done in earlier versions of
516  *          mangle.c:
517  *
518  *            - the extension must exist on the raw name,
519  *            - it must be all lower case
520  *            - it must match the mangled extension (to prove that no
521  *              mangling occurred).
522  *
523  *  crh 07-Apr-1998
524  *
525  * ************************************************************************** **
526  */
527 static void cache_mangled_name( char *mangled_name, char *raw_name )
528   {
529   ubi_cacheEntryPtr new_entry;
530   char             *s1;
531   char             *s2;
532   size_t               mangled_len;
533   size_t               raw_len;
534   size_t               i;
535
536   /* If the cache isn't initialized, give up. */
537   if( !mc_initialized )
538     return;
539
540   /* Init the string lengths. */
541   mangled_len = strlen( mangled_name );
542   raw_len     = strlen( raw_name );
543
544   /* See if the extensions are unmangled.  If so, store the entry
545    * without the extension, thus creating a "group" reverse map.
546    */
547   s1 = strrchr_m( mangled_name, '.' );
548   if( s1 && (s2 = strrchr_m( raw_name, '.' )) )
549     {
550     i = 1;
551     while( s1[i] && (tolower( s1[1] ) == s2[i]) )
552       i++;
553     if( !s1[i] && !s2[i] )
554       {
555       mangled_len -= i;
556       raw_len     -= i;
557       }
558     }
559
560   /* Allocate a new cache entry.  If the allocation fails, just return. */
561   i = sizeof( ubi_cacheEntry ) + mangled_len + raw_len + 2;
562   new_entry = malloc( i );
563   if( !new_entry )
564     return;
565
566   /* Fill the new cache entry, and add it to the cache. */
567   s1 = (char *)(new_entry + 1);
568   s2 = (char *)&(s1[mangled_len + 1]);
569   (void)StrnCpy( s1, mangled_name, mangled_len );
570   (void)StrnCpy( s2, raw_name,     raw_len );
571   ubi_cachePut( mangled_cache, i, new_entry, s1 );
572   } /* cache_mangled_name */
573
574 /* ************************************************************************** **
575  * Check for a name on the mangled name stack
576  *
577  *  Input:  s - Input *and* output string buffer.
578  *
579  *  Output: True if the name was found in the cache, else False.
580  *
581  *  Notes:  If a reverse map is found, the function will overwrite the string
582  *          space indicated by the input pointer <s>.  This is frightening.
583  *          It should be rewritten to return NULL if the long name was not
584  *          found, and a pointer to the long name if it was found.
585  *
586  * ************************************************************************** **
587  */
588
589 BOOL check_mangled_cache( char *s )
590 {
591   ubi_cacheEntryPtr FoundPtr;
592   char             *ext_start = NULL;
593   char             *found_name;
594   char             *saved_ext = NULL;
595
596   /* If the cache isn't initialized, give up. */
597   if( !mc_initialized )
598     return( False );
599
600   FoundPtr = ubi_cacheGet( mangled_cache, (ubi_trItemPtr)s );
601
602   /* If we didn't find the name *with* the extension, try without. */
603   if( !FoundPtr )
604   {
605     ext_start = strrchr_m( s, '.' );
606     if( ext_start )
607     {
608       if((saved_ext = strdup(ext_start)) == NULL)
609         return False;
610
611       *ext_start = '\0';
612       FoundPtr = ubi_cacheGet( mangled_cache, (ubi_trItemPtr)s );
613       /* 
614        * At this point s is the name without the
615        * extension. We re-add the extension if saved_ext
616        * is not null, before freeing saved_ext.
617        */
618     }
619   }
620
621   /* Okay, if we haven't found it we're done. */
622   if( !FoundPtr )
623   {
624     if(saved_ext)
625     {
626       /* Replace the saved_ext as it was truncated. */
627       (void)pstrcat( s, saved_ext );
628       SAFE_FREE(saved_ext);
629     }
630     return( False );
631   }
632
633   /* If we *did* find it, we need to copy it into the string buffer. */
634   found_name = (char *)(FoundPtr + 1);
635   found_name += (strlen( found_name ) + 1);
636
637   DEBUG( 3, ("Found %s on mangled stack ", s) );
638
639   (void)pstrcpy( s, found_name );
640   if( saved_ext )
641   {
642     /* Replace the saved_ext as it was truncated. */
643     (void)pstrcat( s, saved_ext );
644     SAFE_FREE(saved_ext);
645   }
646
647   DEBUG( 3, ("as %s\n", s) );
648
649   return( True );
650 } /* check_mangled_cache */
651
652
653 /* ************************************************************************** **
654  * Used only in do_fwd_mangled_map(), below.
655  * ************************************************************************** **
656  */
657 static char *map_filename( char *s,         /* This is null terminated */
658                            char *pattern,   /* This isn't. */
659                            int len )        /* This is the length of pattern. */
660   {
661   static pstring matching_bit;  /* The bit of the string which matches */
662                                 /* a * in pattern if indeed there is a * */
663   char *sp;                     /* Pointer into s. */
664   char *pp;                     /* Pointer into p. */
665   char *match_start;            /* Where the matching bit starts. */
666   pstring pat;
667
668   StrnCpy( pat, pattern, len ); /* Get pattern into a proper string! */
669   pstrcpy( matching_bit, "" );  /* Match but no star gets this. */
670   pp = pat;                     /* Initialize the pointers. */
671   sp = s;
672
673   if( strequal(s, ".") || strequal(s, ".."))
674     {
675     return NULL;                /* Do not map '.' and '..' */
676     }
677
678   if( (len == 1) && (*pattern == '*') )
679     {
680     return NULL;                /* Impossible, too ambiguous for */
681     }                           /* words! */
682
683   while( (*sp)                  /* Not the end of the string. */
684       && (*pp)                  /* Not the end of the pattern. */
685       && (*sp == *pp)           /* The two match. */
686       && (*pp != '*') )         /* No wildcard. */
687     {
688     sp++;                       /* Keep looking. */
689     pp++;
690     }
691
692   if( !*sp && !*pp )            /* End of pattern. */
693     return( matching_bit );     /* Simple match.  Return empty string. */
694
695   if( *pp == '*' )
696     {
697     pp++;                       /* Always interrested in the chacter */
698                                 /* after the '*' */
699     if( !*pp )                  /* It is at the end of the pattern. */
700       {
701       StrnCpy( matching_bit, s, sp-s );
702       return( matching_bit );
703       }
704     else
705       {
706       /* The next character in pattern must match a character further */
707       /* along s than sp so look for that character. */
708       match_start = sp;
709       while( (*sp)              /* Not the end of s. */
710           && (*sp != *pp) )     /* Not the same  */
711         sp++;                   /* Keep looking. */
712       if( !*sp )                /* Got to the end without a match. */
713         {
714         return( NULL );
715         }                       /* Still hope for a match. */
716       else
717         {
718         /* Now sp should point to a matching character. */
719         StrnCpy(matching_bit, match_start, sp-match_start);
720         /* Back to needing a stright match again. */
721         while( (*sp)            /* Not the end of the string. */
722             && (*pp)            /* Not the end of the pattern. */
723             && (*sp == *pp) )   /* The two match. */
724           {
725           sp++;                 /* Keep looking. */
726           pp++;
727           }
728         if( !*sp && !*pp )      /* Both at end so it matched */
729           return( matching_bit );
730         else
731           return( NULL );
732         }
733       }
734     }
735   return( NULL );               /* No match. */
736   } /* map_filename */
737
738
739 /* ************************************************************************** **
740  * MangledMap is a series of name pairs in () separated by spaces.
741  * If s matches the first of the pair then the name given is the
742  * second of the pair.  A * means any number of any character and if
743  * present in the second of the pair as well as the first the
744  * matching part of the first string takes the place of the * in the
745  * second.
746  *
747  * I wanted this so that we could have RCS files which can be used
748  * by UNIX and DOS programs.  My mapping string is (RCS rcs) which
749  * converts the UNIX RCS file subdirectory to lowercase thus
750  * preventing mangling.
751  *
752  * (I think Andrew wrote the above, but I'm not sure. -- CRH)
753  *
754  * See 'mangled map' in smb.conf(5).
755  *
756  * ************************************************************************** **
757  */
758 static void do_fwd_mangled_map(char *s, char *MangledMap)
759   {
760   char *start=MangledMap;       /* Use this to search for mappings. */
761   char *end;                    /* Used to find the end of strings. */
762   char *match_string;
763   pstring new_string;           /* Make up the result here. */
764   char *np;                     /* Points into new_string. */
765
766   DEBUG( 5, ("Mangled Mapping '%s' map '%s'\n", s, MangledMap) );
767   while( *start )
768     {
769     while( (*start) && (*start != '(') )
770       start++;
771     if( !*start )
772       continue;                 /* Always check for the end. */
773     start++;                    /* Skip the ( */
774     end = start;                /* Search for the ' ' or a ')' */
775     DEBUG( 5, ("Start of first in pair '%s'\n", start) );
776     while( (*end) && !((*end == ' ') || (*end == ')')) )
777       end++;
778     if( !*end )
779       {
780       start = end;
781       continue;                 /* Always check for the end. */
782       }
783     DEBUG( 5, ("End of first in pair '%s'\n", end) );
784     if( (match_string = map_filename( s, start, end-start )) )
785       {
786       DEBUG( 5, ("Found a match\n") );
787       /* Found a match. */
788       start = end + 1;          /* Point to start of what it is to become. */
789       DEBUG( 5, ("Start of second in pair '%s'\n", start) );
790       end = start;
791       np = new_string;
792       while( (*end)             /* Not the end of string. */
793           && (*end != ')')      /* Not the end of the pattern. */
794           && (*end != '*') )    /* Not a wildcard. */
795         *np++ = *end++;
796       if( !*end )
797         {
798         start = end;
799         continue;               /* Always check for the end. */
800         }
801       if( *end == '*' )
802         {
803         pstrcpy( np, match_string );
804         np += strlen( match_string );
805         end++;                  /* Skip the '*' */
806         while( (*end)             /* Not the end of string. */
807             && (*end != ')')      /* Not the end of the pattern. */
808             && (*end != '*') )    /* Not a wildcard. */
809           *np++ = *end++;
810         }
811       if( !*end )
812         {
813         start = end;
814         continue;               /* Always check for the end. */
815         }
816       *np++ = '\0';             /* NULL terminate it. */
817       DEBUG(5,("End of second in pair '%s'\n", end));
818       pstrcpy( s, new_string );  /* Substitute with the new name. */
819       DEBUG( 5, ("s is now '%s'\n", s) );
820       }
821     start = end;              /* Skip a bit which cannot be wanted anymore. */
822     start++;
823     }
824   } /* do_fwd_mangled_map */
825
826 /*****************************************************************************
827  * do the actual mangling to 8.3 format
828  * the buffer must be able to hold 13 characters (including the null)
829  *****************************************************************************
830  */
831 void mangle_name_83( char *s)
832   {
833   int csum;
834   char *p;
835   char extension[4];
836   char base[9];
837   int baselen = 0;
838   int extlen = 0;
839
840   extension[0] = 0;
841   base[0] = 0;
842
843   p = strrchr_m(s,'.');  
844   if( p && (strlen(p+1) < (size_t)4) )
845     {
846     BOOL all_normal = ( strisnormal(p+1) ); /* XXXXXXXXX */
847
848     if( all_normal && p[1] != 0 )
849       {
850       *p = 0;
851       csum = str_checksum( s );
852       *p = '.';
853       }
854     else
855       csum = str_checksum(s);
856     }
857   else
858     csum = str_checksum(s);
859
860   strupper( s );
861
862   DEBUG( 5, ("Mangling name %s to ",s) );
863
864   if( p )
865     {
866     if( p == s )
867       safe_strcpy( extension, "___", 3 );
868     else
869       {
870       *p++ = 0;
871       while( *p && extlen < 3 )
872         {
873             if( /*isdoschar (*p) &&*/ *p != '.' )
874               extension[extlen++] = p[0];
875             p++;
876         }
877       extension[extlen] = 0;
878       }
879     }
880
881   p = s;
882
883   while( *p && baselen < 5 )
884     {
885         if( /*isdoschar( *p ) &&*/ *p != '.' )
886           base[baselen++] = p[0];
887         p++;
888     }
889   base[baselen] = 0;
890
891   csum = csum % (MANGLE_BASE*MANGLE_BASE);
892
893   (void)slprintf(s, 12, "%s%c%c%c",
894                  base, magic_char, mangle( csum/MANGLE_BASE ), mangle( csum ) );
895
896   if( *extension )
897     {
898     (void)pstrcat( s, "." );
899     (void)pstrcat( s, extension );
900     }
901
902   DEBUG( 5, ( "%s\n", s ) );
903
904   } /* mangle_name_83 */
905
906 /*****************************************************************************
907  * Convert a filename to DOS format.  Return True if successful.
908  *
909  *  Input:  OutName - Source *and* destination buffer. 
910  *
911  *                    NOTE that OutName must point to a memory space that
912  *                    is at least 13 bytes in size!
913  *
914  *          need83  - If False, name mangling will be skipped unless the
915  *                    name contains illegal characters.  Mapping will still
916  *                    be done, if appropriate.  This is probably used to
917  *                    signal that a client does not require name mangling,
918  *                    thus skipping the name mangling even on shares which
919  *                    have name-mangling turned on.
920  *          cache83 - If False, the mangled name cache will not be updated.
921  *                    This is usually used to prevent that we overwrite
922  *                    a conflicting cache entry prematurely, i.e. before
923  *                    we know whether the client is really interested in the
924  *                    current name.  (See PR#13758).  UKD.
925  *          snum    - Share number.  This identifies the share in which the
926  *                    name exists.
927  *
928  *  Output: Returns False only if the name wanted mangling but the share does
929  *          not have name mangling turned on.
930  *
931  * ****************************************************************************
932  */
933 BOOL name_map_mangle(char *OutName, BOOL need83, BOOL cache83, int snum)
934 {
935         char *map;
936         DEBUG(5,("name_map_mangle( %s, need83 = %s, cache83 = %s, %d )\n", OutName,
937                 need83 ? "TRUE" : "FALSE", cache83 ? "TRUE" : "FALSE", snum));
938
939 #ifdef MANGLE_LONG_FILENAMES
940         if( !need83 && is_illegal_name(OutName) )
941                 need83 = True;
942 #endif  
943
944         /* apply any name mappings */
945         map = lp_mangled_map(snum);
946
947         if (map && *map) {
948                 do_fwd_mangled_map( OutName, map );
949         }
950
951         /* check if it's already in 8.3 format */
952         if (need83 && !is_8_3(OutName, True)) {
953                 char *tmp = NULL; 
954
955                 if (!lp_manglednames(snum)) {
956                         return(False);
957                 }
958
959                 /* mangle it into 8.3 */
960                 if (cache83)
961                         tmp = strdup(OutName);
962
963                 mangle_name_83(OutName);
964
965                 if(tmp != NULL) {
966                         cache_mangled_name(OutName, tmp);
967                         SAFE_FREE(tmp);
968                 }
969         }
970
971         DEBUG(5,("name_map_mangle() ==> [%s]\n", OutName));
972         return(True);
973 } /* name_map_mangle */
974
975 #endif
976
977
978
979
980 /* -------------------------------------------------------------------- */
981 /* 
982    Unix SMB/Netbios implementation.
983    Version 3.0
984    Name mangling with persistent tdb
985    Copyright (C) Simo Sorce <idra@samba.org> 2001
986    
987    This program is free software; you can redistribute it and/or modify
988    it under the terms of the GNU General Public License as published by
989    the Free Software Foundation; either version 2 of the License, or
990    (at your option) any later version.
991    
992    This program is distributed in the hope that it will be useful,
993    but WITHOUT ANY WARRANTY; without even the implied warranty of
994    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
995    GNU General Public License for more details.
996    
997    You should have received a copy of the GNU General Public License
998    along with this program; if not, write to the Free Software
999    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
1000 */
1001
1002 #if 0
1003
1004 #define MANGLE_TDB_VERSION              "20010927"
1005 #define MANGLE_TDB_FILE_NAME            "mangle.tdb"
1006 #define MANGLED_PREFIX                  "MANGLED_"
1007 #define LONG_PREFIX                     "LONG_"
1008 #define COUNTER_PREFIX                  "COUNTER_"
1009 #define MANGLE_COUNTER_MAX              99
1010 #define MANGLE_SUFFIX_SIZE              2
1011
1012
1013 static TDB_CONTEXT      *mangle_tdb;
1014
1015 BOOL init_mangle_tdb(void)
1016 {
1017         char *tdbfile;
1018         
1019         tdbfile = lock_path(MANGLE_TDB_FILE_NAME); /* this return a static pstring do not try to free it */
1020
1021         /* Open tdb */
1022         if (!(mangle_tdb = tdb_open_log(tdbfile, 0, TDB_DEFAULT, O_RDWR | O_CREAT, 0600)))
1023         {
1024                 DEBUG(0, ("Unable to open Mangle TDB\n"));
1025                 return False;
1026         }
1027
1028         return True;
1029 }
1030
1031 /* trasform a dos charset string in a terminated unicode string */
1032 static int dos_to_ucs2(void *dest, const char *src, int dest_len)
1033 {
1034         int len=0;
1035         int src_len = strlen(src) + 1;
1036
1037         /* treat a pstring as "unlimited" length */
1038         if (dest_len == -1) {
1039                 dest_len = sizeof(pstring);
1040         }
1041
1042         /* ucs2 is always a multiple of 2 bytes */
1043         dest_len &= ~1;
1044
1045         len = convert_string(CH_DOS, CH_UCS2, src, src_len, dest, dest_len);
1046         return len;
1047 }
1048
1049 /* trasform a unicode string into a dos charset string */
1050 static int ucs2_to_dos(char *dest, const smb_ucs2_t *src, int dest_len)
1051 {
1052         int src_len, ret;
1053
1054         if (dest_len == -1) {
1055                 dest_len = sizeof(pstring);
1056         }
1057
1058         src_len = strlen_w(src) * sizeof(smb_ucs2_t);
1059         
1060         ret = convert_string(CH_UCS2, CH_DOS, src, src_len, dest, dest_len);
1061         if (dest_len) dest[MIN(ret, dest_len-1)] = 0;
1062
1063         return ret;
1064 }
1065
1066 /* trasform a ucs2 string in a dos charset string that contain only valid chars for 8.3 filenames */
1067 static int ucs2_to_dos83(char *dest, const smb_ucs2_t *src, int dest_len)
1068 {
1069         int src_len, ret;
1070         smb_ucs2_t *u2s;
1071
1072         u2s = (smb_ucs2_t *)malloc((strlen_w(src) + 1) * sizeof(smb_ucs2_t));
1073         if (!u2s) {
1074                 DEBUG(0, ("ucs2_to_dos83: out of memory!\n"));
1075                 return 0;
1076         }
1077         
1078         src_len = strlen_w(src);
1079         
1080         u2s[src_len] = 0;
1081         while (src_len--)
1082         {
1083                 smb_ucs2_t c;
1084                 
1085                 c = src[src_len];
1086                 if (isvalid83_w(c)) u2s[src_len] = c;
1087                 else u2s[src_len] = UCS2_CHAR('_');
1088         }
1089         
1090         ret = ucs2_to_dos(dest, u2s, dest_len);
1091         
1092         SAFE_FREE(u2s);
1093
1094         return ret;
1095 }
1096
1097
1098 /* return False if something fail and
1099  * return 2 alloced unicode strings that contain prefix and extension
1100  */
1101 static BOOL mangle_get_prefix(const smb_ucs2_t *ucs2_string, smb_ucs2_t **prefix, smb_ucs2_t **extension)
1102 {
1103         size_t str_len;
1104         smb_ucs2_t *p;
1105         fstring ext;
1106
1107         *extension = 0;
1108         *prefix = strdup_w(ucs2_string);
1109         if (!*prefix)
1110         {
1111                 DEBUG(0,("mangle_get_prefix: out of memory!\n"));
1112                 return False;
1113         }
1114         if ((p = strrchr_wa(*prefix, '.')))
1115         {
1116                 p++;
1117                 str_len = ucs2_to_dos83(ext, p, sizeof(ext));
1118                 if (str_len > 0 && str_len < 4) /* check extension */
1119                 {
1120                         *(p - 1) = 0;
1121                         *extension = strdup_w(p);
1122                         if (!*extension)
1123                         {
1124                                 DEBUG(0,("mangle_get_prefix: out of memory!\n"));
1125                                 SAFE_FREE(*prefix);
1126                                 return False;
1127                         }
1128                 }
1129         }
1130
1131         return True;
1132 }
1133
1134
1135 /* mangled must contain only the file name, not a path.
1136    and MUST be ZERO terminated */
1137 smb_ucs2_t *unmangle(const smb_ucs2_t *mangled)
1138 {
1139         TDB_DATA data, key;
1140         fstring keystr;
1141         fstring mufname;
1142         smb_ucs2_t *pref, *ext, *retstr;
1143         size_t long_len, ext_len, muf_len;
1144         BOOL ret;
1145
1146         if (strlen_w(mangled) > 12) return NULL;
1147         if (!strchr_wa(mangled, '~')) return NULL;
1148         
1149         ret = mangle_get_prefix(mangled, &pref, &ext);
1150         if (!ret) return NULL;
1151         
1152         /* TODO: get out extension */
1153         strlower_w(pref);
1154         /* set search key */
1155         muf_len = ucs2_to_dos(mufname, pref, sizeof(mufname));
1156         SAFE_FREE(pref);
1157         if (!muf_len) return NULL;
1158         
1159         slprintf(keystr, sizeof(keystr) - 1, "%s%s", MANGLED_PREFIX, mufname);
1160         key.dptr = keystr;
1161         key.dsize = strlen (keystr) + 1;
1162         
1163         /* get the record */
1164         data = tdb_fetch(mangle_tdb, key);
1165         
1166         if (!data.dptr) /* not found */
1167         {
1168                 DEBUG(5,("unmangle: failed retrieve from db %s\n", tdb_errorstr(mangle_tdb)));
1169                 retstr = NULL;
1170                 goto done;
1171         }
1172
1173         if (ext)
1174         {
1175                 long_len = (data.dsize / 2) - 1;
1176                 ext_len = strlen_w(ext);
1177                 retstr = (smb_ucs2_t *)malloc((long_len + ext_len + 2)*sizeof(smb_ucs2_t));
1178                 if (!retstr)
1179                 {
1180                         DEBUG(0, ("unamngle: out of memory!\n"));
1181                         goto done;
1182                 }
1183                 strncpy_w(retstr, (smb_ucs2_t *)data.dptr, long_len);
1184                 retstr[long_len] = UCS2_CHAR('.');
1185                 retstr[long_len + 1] = 0;
1186                 strncat_w(retstr, ext, ext_len);
1187         }
1188         else
1189         {
1190                 retstr = strdup_w((smb_ucs2_t *)data.dptr);
1191                 if (!retstr)
1192                 {
1193                         DEBUG(0, ("unamngle: out of memory!\n"));
1194                         goto done;
1195                 }
1196
1197         }
1198
1199 done:
1200         SAFE_FREE(data.dptr);
1201         SAFE_FREE(pref);
1202         SAFE_FREE(ext);
1203
1204         return retstr;
1205 }
1206
1207 /* unmangled must contain only the file name, not a path.
1208    and MUST be ZERO terminated */
1209 smb_ucs2_t *_mangle(const smb_ucs2_t *unmangled)
1210 {
1211         TDB_DATA data, key, klock;
1212         pstring keystr;
1213         pstring longname;
1214         fstring keylock;
1215         fstring mufname;
1216         fstring prefix;
1217         BOOL tclock = False;
1218         char suffix[7];
1219         smb_ucs2_t *mangled = NULL;
1220         smb_ucs2_t *um, *ext, *p = NULL;
1221         smb_ucs2_t temp[9];
1222         size_t pref_len, ext_len, ud83_len;
1223         uint32 n, c, pos;
1224
1225         /* TODO: if it is a path return a failure ?? */
1226         if (!mangle_get_prefix(unmangled, &um, &ext)) return NULL;
1227
1228         /* test if the same is yet mangled */
1229
1230         /* set search key */
1231         pull_ucs2(NULL, longname, um, sizeof(longname), 0, STR_TERMINATE);
1232         slprintf(keystr, sizeof(keystr)-1, "%s%s", LONG_PREFIX, longname);
1233         key.dptr = keystr;
1234         key.dsize = strlen(keystr) + 1;
1235
1236         /* get the record */
1237         data = tdb_fetch (mangle_tdb, key);
1238         if (!data.dptr) /* not found */
1239         {
1240                 if (tdb_error(mangle_tdb) != TDB_ERR_NOEXIST)
1241                 {
1242                         DEBUG(0, ("mangle: database retrieval error: %s\n",
1243                                         tdb_errorstr(mangle_tdb)));
1244                         goto done;
1245                 }
1246
1247                 /* if not find the first free possibile mangled name */
1248
1249                 n = 0;
1250                 do
1251                 {
1252                         n++;
1253                         pos = 8 - n - MANGLE_SUFFIX_SIZE;
1254                         if (pos == 0)
1255                         {
1256                                 DEBUG(0, ("mangle: unable to mangle file name!\n"));
1257                                 goto done;
1258                         }
1259                         strncpy_w(temp, um, pos);
1260                         temp[pos] = 0;
1261                         strlower_w(temp);
1262
1263                         ud83_len = ucs2_to_dos83(prefix, temp, sizeof(prefix));
1264                         if (!ud83_len) goto done;
1265                 }
1266                 while (ud83_len > 8 - (MANGLE_SUFFIX_SIZE + 1));
1267
1268                 slprintf(keylock, sizeof(keylock)-1, "%s%s", COUNTER_PREFIX, prefix);
1269                 klock.dptr = keylock;
1270                 klock.dsize = strlen(keylock) + 1;
1271
1272                 c = 0;
1273                 data.dptr = (char *)&c;
1274                 data.dsize = sizeof(uint32);
1275                 /* try to insert a new counter prefix, if it exist the call will
1276                    fail (correct) otherwise it will create a new entry with counter set
1277                    to 0
1278                  */
1279                 if(tdb_store(mangle_tdb, klock, data, TDB_INSERT) != TDB_SUCCESS)
1280                 {
1281                         if (tdb_error(mangle_tdb) != TDB_ERR_EXISTS)
1282                         {
1283                                 DEBUG(0, ("mangle: database store error: %s\n",
1284                                         tdb_errorstr(mangle_tdb)));
1285                                 goto done;
1286                         }
1287                 }
1288
1289                 /* lock the mangle counter for this prefix */           
1290                 if (tdb_chainlock(mangle_tdb, klock))
1291                 {
1292                         DEBUG(0,("mangle: failed to lock database\n!"));
1293                         goto done;
1294                 }
1295                 tclock = True;
1296
1297                 data = tdb_fetch(mangle_tdb, klock);
1298                 if (!data.dptr)
1299                 {
1300                         DEBUG(0, ("mangle: database retrieval error: %s\n",
1301                                         tdb_errorstr(mangle_tdb)));
1302                         goto done;
1303                 }
1304                 c = *((uint32 *)data.dptr);
1305                 c++;
1306                 
1307                 if (c > MANGLE_COUNTER_MAX)
1308                 {
1309                         DEBUG(0, ("mangle: error, counter overflow!\n"));
1310                         goto done;
1311                 }
1312                         
1313                 temp[pos] = UCS2_CHAR('~');
1314                 temp[pos+1] = 0;
1315                 snprintf(suffix, 7, "%.6d", c);
1316                 strncat_wa(temp, &suffix[6 - MANGLE_SUFFIX_SIZE], MANGLE_SUFFIX_SIZE + 1);
1317
1318                 ud83_len = ucs2_to_dos(mufname, temp, sizeof(mufname));
1319                 if (!ud83_len) goto done;
1320                 if (ud83_len > 8)
1321                 {
1322                         DEBUG(0, ("mangle: darn, logic error aborting!\n"));
1323                         goto done;
1324                 }
1325                         
1326                 /* store the long entry with mangled key */
1327                 slprintf(keystr, sizeof(keystr)-1, "%s%s", MANGLED_PREFIX, mufname);
1328                 key.dptr = keystr;
1329                 key.dsize = strlen (keystr) + 1;
1330                 data.dsize = (strlen_w(um) + 1) * sizeof (smb_ucs2_t);
1331                 data.dptr = (void *)um;
1332
1333                 if (tdb_store(mangle_tdb, key, data, TDB_INSERT) != TDB_SUCCESS)
1334                 {
1335                         DEBUG(0, ("mangle: database store error: %s\n",
1336                                         tdb_errorstr(mangle_tdb)));
1337                         goto done;
1338                 }
1339
1340                 /* store the mangled entry with long key*/
1341                 pull_ucs2(NULL, longname, um, sizeof(longname), 0, STR_TERMINATE);
1342                 slprintf(keystr, sizeof(keystr)-1, "%s%s", LONG_PREFIX, longname);
1343                 key.dptr = keystr;
1344                 key.dsize = strlen (keystr) + 1;
1345                 data.dsize = strlen(mufname) + 1;
1346                 data.dptr = mufname;
1347                 if (tdb_store(mangle_tdb, key, data, TDB_INSERT) != TDB_SUCCESS)
1348                 {
1349                         DEBUG(0, ("mangle: database store failed: %s\n",
1350                                         tdb_errorstr(mangle_tdb)));
1351
1352                         /* try to delete the mangled key entry to avoid later inconsistency */
1353                         slprintf(keystr, sizeof(keystr)-1, "%s%s", MANGLED_PREFIX, mufname);
1354                         key.dptr = keystr;
1355                         key.dsize = strlen (keystr) + 1;
1356                         if (!tdb_delete(mangle_tdb, key))
1357                         {
1358                                 DEBUG(0, ("mangle: severe error, mangled tdb may be inconsistent!\n"));
1359                         }
1360                         goto done;
1361                 }
1362
1363                 p = strdup_w(temp);
1364                 if (!p)
1365                 {
1366                         DEBUG(0,("mangle: out of memory!\n"));
1367                         goto done;
1368                 }
1369                 
1370                 data.dptr = (char *)&c;
1371                 data.dsize = sizeof(uint32);
1372                 /* store the counter */
1373                 if(tdb_store(mangle_tdb, klock, data, TDB_REPLACE) != TDB_SUCCESS)
1374                 {
1375                         DEBUG(0, ("mangle: database store failed: %s\n",
1376                                         tdb_errorstr(mangle_tdb)));
1377                         /* try to delete the mangled and long key entry to avoid later inconsistency */
1378                         slprintf(keystr, sizeof(keystr)-1, "%s%s", MANGLED_PREFIX, mufname);
1379                         key.dptr = keystr;
1380                         key.dsize = strlen (keystr) + 1;
1381                         if (!tdb_delete(mangle_tdb, key))
1382                         {
1383                                 DEBUG(0, ("mangle: severe error, mangled tdb may be inconsistent!\n"));
1384                         }
1385                         slprintf(keystr, sizeof(keystr)-1, "%s%s", LONG_PREFIX, longname);
1386                         key.dptr = keystr;
1387                         key.dsize = strlen (keystr) + 1;
1388                         if (!tdb_delete(mangle_tdb, key))
1389                         {
1390                                 DEBUG(0, ("mangle: severe error, mangled tdb may be inconsistent!\n"));
1391                         }
1392                         goto done;
1393                 }
1394
1395                 tclock = False;
1396                 tdb_chainunlock(mangle_tdb, klock);
1397         }
1398         else /* FOUND */
1399         {
1400                 p = (smb_ucs2_t *)malloc(data.dsize*sizeof(smb_ucs2_t));
1401                 if (!p)
1402                 {
1403                         DEBUG(0,("mangle: out of memory!\n"));
1404                         goto done;
1405                 }
1406                 dos_to_ucs2(p, data.dptr, data.dsize*sizeof(smb_ucs2_t));
1407         }
1408                 
1409         if (ext)
1410         {
1411                 pref_len = strlen_w(p);
1412                 ext_len = strlen_w(ext);
1413                 mangled = (smb_ucs2_t *)malloc((pref_len + ext_len + 2)*sizeof(smb_ucs2_t));
1414                 if (!mangled)
1415                 {
1416                         DEBUG(0,("mangle: out of memory!\n"));
1417                         goto done;
1418                 }
1419                 strncpy_w (mangled, p, pref_len);
1420                 mangled[pref_len] = UCS2_CHAR('.');
1421                 mangled[pref_len + 1] = 0;
1422                 strncat_w (mangled, ext, ext_len);
1423         }
1424         else
1425         {
1426                 mangled = strdup_w(p);
1427                 if (!mangled)
1428                 {
1429                         DEBUG(0,("mangle: out of memory!\n"));
1430                         goto done;
1431                 }
1432         }
1433
1434 done:
1435         if (tclock) tdb_chainunlock(mangle_tdb, klock);
1436         SAFE_FREE(p);
1437         SAFE_FREE(um);
1438         SAFE_FREE(ext);
1439
1440         return mangled;
1441 }
1442
1443
1444
1445
1446 /* backward compatibility functions */
1447
1448 BOOL is_mangled(char *s)
1449 {
1450         smb_ucs2_t *u2, *res;
1451         size_t u2len;
1452         BOOL ret = False;
1453         
1454         u2len = (strlen(s) + 1) * sizeof(smb_ucs2_t);
1455         u2 = (smb_ucs2_t *)malloc(u2len);
1456         if (!u2)
1457         {
1458                 DEBUG(0,("is_mangled: out of memory!\n"));
1459                 return ret;
1460         }
1461         dos_to_ucs2(u2, s, u2len);
1462         
1463         res = unmangle(u2);
1464         if (res) ret = True;
1465         SAFE_FREE(res);
1466         SAFE_FREE(u2);
1467         return ret;
1468 }
1469
1470 BOOL is_8_3(char *fname, BOOL check_case)
1471 {
1472         smb_ucs2_t *u2, *pref = 0, *ext = 0;
1473         char *s1 = 0, *s2;
1474         size_t u2len;
1475         BOOL ret = False;
1476
1477         u2len = (strlen(fname) + 1) * sizeof(smb_ucs2_t);
1478         u2 = (smb_ucs2_t *)malloc(u2len);
1479         if (!u2)
1480         {
1481                 DEBUG(0,("is_8_3: out of memory!\n"));
1482                 goto done;
1483         }
1484         s1 = (char *) malloc(u2len * 2);
1485         if (!s1)
1486         {
1487                 DEBUG(0,("is_8_3: out of memory!\n"));
1488                 goto done;
1489         }
1490         s2 = s1 + u2len;
1491         dos_to_ucs2(u2, fname, u2len);
1492         
1493
1494         if (!mangle_get_prefix(u2, &pref, &ext)) goto done;
1495         if (strlen_w(pref) > 8) goto done;
1496
1497         ucs2_to_dos(s1, u2, u2len);
1498         ucs2_to_dos83(s2, u2, u2len);
1499         
1500         if (strncmp(s1, s2, u2len)) goto done;
1501         else ret = True;
1502         
1503 done:
1504         SAFE_FREE(u2);
1505         SAFE_FREE(s1);
1506         SAFE_FREE(pref);
1507         SAFE_FREE(ext);
1508 }
1509
1510 void reset_mangled_cache(void)
1511 {
1512         DEBUG(10,("reset_mangled_cache: compatibility function, remove me!\n"));
1513 }
1514
1515 BOOL check_mangled_cache(char *s)
1516 {
1517         smb_ucs2_t *u2, *res;
1518         size_t slen, u2len;
1519         BOOL ret = False;
1520         
1521         DEBUG(10,("check_mangled_cache: I'm so ugly, please remove me!\n"));
1522
1523         slen = strlen(s);
1524         u2len = (slen + 1) * sizeof(smb_ucs2_t);
1525         u2 = (smb_ucs2_t *)malloc(u2len);
1526         if (!u2)
1527         {
1528                 DEBUG(0,("check_mangled_cache: out of memory!\n"));
1529                 return ret;
1530         }
1531         dos_to_ucs2(u2, s, u2len);
1532         
1533         res = unmangle(u2);
1534         if (res)
1535         {
1536                 ucs2_to_dos (s, res, slen); /* ugly, but must be done this way */
1537                 ret = True;
1538         }
1539         SAFE_FREE(res);
1540         SAFE_FREE(u2);
1541         return ret;
1542 }
1543
1544 void mangle_name_83(char *s)
1545 {
1546         smb_ucs2_t *u2, *res;
1547         size_t slen, u2len;
1548         BOOL ret = False;
1549         
1550         DEBUG(10,("mangle_name_83: I'm so ugly, please remove me!\n"));
1551
1552         slen = strlen(s);
1553         u2len = (slen + 1) * sizeof(smb_ucs2_t);
1554         u2 = (smb_ucs2_t *)malloc(u2len);
1555         if (!u2)
1556         {
1557                 DEBUG(0,("mangle_name_83: out of memory!\n"));
1558                 return;
1559         }
1560         dos_to_ucs2(u2, s, u2len);
1561         
1562         res = _mangle(u2);
1563         if (res) ucs2_to_dos (s, res, slen); /* ugly, but must be done this way */
1564         SAFE_FREE(res);
1565         SAFE_FREE(u2);
1566 }
1567
1568 BOOL name_map_mangle(char *OutName, BOOL need83, BOOL cache83, int snum)
1569 {
1570         DEBUG(10,("name_map_mangle: I'm so ugly, please remove me!\n"));
1571
1572         mangle_name_83(OutName);
1573         return True;
1574 }
1575
1576 #endif /* 0 */
1577
1578 #if 0 /* TEST_MANGLE_CODE */
1579
1580 #define LONG            "this_is_a_long_file_name"
1581 #define LONGM           "this_~01"
1582 #define SHORT           "short"
1583 #define SHORTM          "short~01"
1584 #define EXT1            "ex1"
1585 #define EXT2            "e2"
1586 #define EXT3            "3"
1587 #define EXTFAIL         "longext"
1588 #define EXTNULL         ""
1589
1590 static void unmangle_test (char *name, char *ext)
1591 {
1592         smb_ucs2_t ucs2_name[2048];
1593         smb_ucs2_t *retstr;
1594         pstring unix_name;      
1595
1596         push_ucs2(NULL, ucs2_name, name, sizeof(ucs2_name), STR_TERMINATE);
1597         if (ext)
1598         {
1599                 strncat_wa(ucs2_name, ".", 1);
1600                 strncat_wa(ucs2_name, ext, strlen(ext) + 1);
1601         }
1602         retstr = unmangle(ucs2_name);
1603         if(retstr) pull_ucs2(NULL, unix_name, retstr, sizeof(unix_name), 0, STR_TERMINATE);
1604         else unix_name[0] = 0;
1605         if (ext) printf ("[%s.%s] ---> [%s]\n", name, ext, unix_name);
1606         else printf ("[%s] ---> [%s]\n", name, unix_name);
1607         SAFE_FREE(retstr);
1608 }
1609
1610 static void mangle_test (char *name, char *ext)
1611 {
1612         smb_ucs2_t ucs2_name[2048];
1613         smb_ucs2_t *retstr;
1614         pstring unix_name;      
1615
1616         push_ucs2(NULL, ucs2_name, name, sizeof(ucs2_name), STR_TERMINATE);
1617         if (ext)
1618         {
1619                 strncat_wa(ucs2_name, ".", 1);
1620                 strncat_wa(ucs2_name, ext, strlen(ext) + 1);
1621         }
1622         retstr = _mangle(ucs2_name);
1623         if(retstr) pull_ucs2(NULL, unix_name, retstr, sizeof(unix_name), 0, STR_TERMINATE);
1624         else unix_name[0] = 0;
1625         if (ext) printf ("[%s.%s] ---> [%s]\n", name, ext, unix_name);
1626         else printf ("[%s] ---> [%s]\n", name, unix_name);
1627         SAFE_FREE(retstr);
1628 }
1629
1630 void mangle_test_code(void)
1631 {
1632         init_mangle_tdb();
1633
1634         /* unmangle every */
1635         printf("Unmangle test 1:\n");
1636         
1637         unmangle_test (LONG, NULL);
1638         unmangle_test (LONG, EXT1);
1639         unmangle_test (LONG, EXT2);
1640         unmangle_test (LONG, EXT3);
1641         unmangle_test (LONG, EXTFAIL);
1642         unmangle_test (LONG, EXTNULL);
1643
1644         unmangle_test (LONGM, NULL);
1645         unmangle_test (LONGM, EXT1);
1646         unmangle_test (LONGM, EXT2);
1647         unmangle_test (LONGM, EXT3);
1648         unmangle_test (LONGM, EXTFAIL);
1649         unmangle_test (LONGM, EXTNULL);
1650
1651         unmangle_test (SHORT, NULL);
1652         unmangle_test (SHORT, EXT1);
1653         unmangle_test (SHORT, EXT2);
1654         unmangle_test (SHORT, EXT3);
1655         unmangle_test (SHORT, EXTFAIL);
1656         unmangle_test (SHORT, EXTNULL);
1657
1658         unmangle_test (SHORTM, NULL);
1659         unmangle_test (SHORTM, EXT1);
1660         unmangle_test (SHORTM, EXT2);
1661         unmangle_test (SHORTM, EXT3);
1662         unmangle_test (SHORTM, EXTFAIL);
1663         unmangle_test (SHORTM, EXTNULL);
1664
1665         /* mangle every */
1666         printf("Mangle test\n");
1667         
1668         mangle_test (LONG, NULL);
1669         mangle_test (LONG, EXT1);
1670         mangle_test (LONG, EXT2);
1671         mangle_test (LONG, EXT3);
1672         mangle_test (LONG, EXTFAIL);
1673         mangle_test (LONG, EXTNULL);
1674
1675         mangle_test (LONGM, NULL);
1676         mangle_test (LONGM, EXT1);
1677         mangle_test (LONGM, EXT2);
1678         mangle_test (LONGM, EXT3);
1679         mangle_test (LONGM, EXTFAIL);
1680         mangle_test (LONGM, EXTNULL);
1681
1682         mangle_test (SHORT, NULL);
1683         mangle_test (SHORT, EXT1);
1684         mangle_test (SHORT, EXT2);
1685         mangle_test (SHORT, EXT3);
1686         mangle_test (SHORT, EXTFAIL);
1687         mangle_test (SHORT, EXTNULL);
1688
1689         mangle_test (SHORTM, NULL);
1690         mangle_test (SHORTM, EXT1);
1691         mangle_test (SHORTM, EXT2);
1692         mangle_test (SHORTM, EXT3);
1693         mangle_test (SHORTM, EXTFAIL);
1694         mangle_test (SHORTM, EXTNULL);
1695
1696         /* unmangle again every */
1697         printf("Unmangle test 2:\n");
1698         
1699         unmangle_test (LONG, NULL);
1700         unmangle_test (LONG, EXT1);
1701         unmangle_test (LONG, EXT2);
1702         unmangle_test (LONG, EXT3);
1703         unmangle_test (LONG, EXTFAIL);
1704         unmangle_test (LONG, EXTNULL);
1705
1706         unmangle_test (LONGM, NULL);
1707         unmangle_test (LONGM, EXT1);
1708         unmangle_test (LONGM, EXT2);
1709         unmangle_test (LONGM, EXT3);
1710         unmangle_test (LONGM, EXTFAIL);
1711         unmangle_test (LONGM, EXTNULL);
1712
1713         unmangle_test (SHORT, NULL);
1714         unmangle_test (SHORT, EXT1);
1715         unmangle_test (SHORT, EXT2);
1716         unmangle_test (SHORT, EXT3);
1717         unmangle_test (SHORT, EXTFAIL);
1718         unmangle_test (SHORT, EXTNULL);
1719
1720         unmangle_test (SHORTM, NULL);
1721         unmangle_test (SHORTM, EXT1);
1722         unmangle_test (SHORTM, EXT2);
1723         unmangle_test (SHORTM, EXT3);
1724         unmangle_test (SHORTM, EXTFAIL);
1725         unmangle_test (SHORTM, EXTNULL);
1726 }
1727
1728 #endif /* TEST_MANGLE_CODE */