Andrew redefines the free() function to do some memory management testing.
[kai/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 #include "ubiqx/ubi_Cache.h"
50
51
52 /* -------------------------------------------------------------------------- **
53  * External Variables...
54  */
55
56 extern int DEBUGLEVEL;      /* Global debug level.                            */
57 extern int case_default;    /* Are conforming 8.3 names all upper or lower?   */
58 extern BOOL case_mangle;    /* If true, all chars in 8.3 should be same case. */
59
60 /* -------------------------------------------------------------------------- **
61  * Other stuff...
62  *
63  * magic_char     - This is the magic char used for mangling.  It's
64  *                  global.  There is a call to lp_magicchar() in server.c
65  *                  that is used to override the initial value.
66  *
67  * basechars      - The set of 36 characters used for name mangling.  This
68  *                  is static (scope is this file only).
69  *
70  * base36()       - Macro used to select a character from basechars (i.e.,
71  *                  base36(n) will return the nth digit, modulo 36).
72  *
73  * chartest       - array 0..255.  The index range is the set of all possible
74  *                  values of a byte.  For each byte value, the content is a
75  *                  two nibble pair.  See BASECHAR_MASK and ILLEGAL_MASK,
76  *                  below.
77  *
78  * ct_initialized - False until the chartest array has been initialized via
79  *                  a call to init_chartest().
80  *
81  * BASECHAR_MASK  - Masks the upper nibble of a one-byte value.
82  *
83  * ILLEGAL_MASK   - Masks the lower nibble of a one-byte value.
84  *
85  * isbasecahr()   - Given a character, check the chartest array to see
86  *                  if that character is in the basechars set.  This is
87  *                  faster than using strchr().
88  *
89  * isillegal()    - Given a character, check the chartest array to see
90  *                  if that character is in the illegal characters set.
91  *                  This is faster than using strchr().
92  *
93  * mangled_cache  - Cache header used for storing mangled -> original
94  *                  reverse maps.
95  *
96  * mc_initialized - False until the mangled_cache structure has been
97  *                  initialized via a call to reset_mangled_cache().
98  *
99  * MANGLED_CACHE_MAX_ENTRIES - Default maximum number of entries for the
100  *                  cache.  A value of 0 indicates "infinite".
101  *
102  * MANGLED_CACHE_MAX_MEMORY  - Default maximum amount of memory for the
103  *                  cache.  When the cache was kept as an array of 256
104  *                  byte strings, the default cache size was 50 entries.
105  *                  This required a fixed 12.5Kbytes of memory.  The
106  *                  mangled stack parameter is no longer used (though
107  *                  this might change).  We're now using a fixed 16Kbyte
108  *                  maximum cache size.  This will probably be much more
109  *                  than 50 entries.
110  */
111
112 char magic_char = '~';
113
114 static char basechars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
115
116 static unsigned char chartest[256]  = { 0 };
117 static BOOL          ct_initialized = False;
118
119 #define base36(V) ((char)(basechars[(V) % 36]))
120 #define BASECHAR_MASK 0xf0
121 #define ILLEGAL_MASK  0x0f
122 #define isbasechar(C) ( (chartest[ ((C) & 0xff) ]) & BASECHAR_MASK )
123 #define isillegal(C) ( (chartest[ ((C) & 0xff) ]) & ILLEGAL_MASK )
124
125 static ubi_cacheRoot mangled_cache[1] = { { { 0 }, 0, 0, 0, 0, 0, 0} };
126 static BOOL          mc_initialized   = False;
127 #define MANGLED_CACHE_MAX_ENTRIES 0
128 #define MANGLED_CACHE_MAX_MEMORY  16384
129
130
131 /* -------------------------------------------------------------------------- **
132  * Functions...
133  */
134
135 /* ************************************************************************** **
136  * Initialize the static character test array.
137  *
138  *  Input:  none
139  *
140  *  Output: none
141  *
142  *  Notes:  This function changes (loads) the contents of the <chartest>
143  *          array.  The scope of <chartest> is this file.
144  *
145  * ************************************************************************** **
146  */
147 static void init_chartest( void )
148   {
149   char          *illegalchars = "*\\/?<>|\":";
150   unsigned char *s;
151   
152   bzero( (char *)chartest, 256 );
153
154   for( s = (unsigned char *)illegalchars; *s; s++ )
155     chartest[*s] = ILLEGAL_MASK;
156
157   for( s = (unsigned char *)basechars; *s; s++ )
158     chartest[*s] |= BASECHAR_MASK;
159
160   ct_initialized = True;
161   } /* init_chartest */
162
163 /* ************************************************************************** **
164  * Return True if a name is a special msdos reserved name.
165  *
166  *  Input:  fname - String containing the name to be tested.
167  *
168  *  Output: True, if the name matches one of the list of reserved names.
169  *
170  *  Notes:  This is a static function called by is_8_3(), below.
171  *
172  * ************************************************************************** **
173  */
174 static BOOL is_reserved_msdos( char *fname )
175   {
176   char upperFname[13];
177   char *p;
178
179   StrnCpy (upperFname, fname, 12);
180
181   /* lpt1.txt and con.txt etc are also illegal */
182   p = strchr(upperFname,'.');
183   if( p )
184     *p = '\0';
185
186   strupper( upperFname );
187   p = upperFname + 1;
188   switch( upperFname[0] )
189     {
190     case 'A':
191       if( 0 == strcmp( p, "UX" ) )
192         return( True );
193       break;
194     case 'C':
195       if( (0 == strcmp( p, "LOCK$" ))
196        || (0 == strcmp( p, "ON" ))
197        || (0 == strcmp( p, "OM1" ))
198        || (0 == strcmp( p, "OM2" ))
199        || (0 == strcmp( p, "OM3" ))
200        || (0 == strcmp( p, "OM4" ))
201         )
202         return( True );
203       break;
204     case 'L':
205       if( (0 == strcmp( p, "PT1" ))
206        || (0 == strcmp( p, "PT2" ))
207        || (0 == strcmp( p, "PT3" ))
208         )
209         return( True );
210       break;
211     case 'N':
212       if( 0 == strcmp( p, "UL" ) )
213         return( True );
214       break;
215     case 'P':
216       if( 0 == strcmp( p, "RN" ) )
217         return( True );
218       break;
219     }
220
221   return( False );
222   } /* is_reserved_msdos */
223
224 /* ************************************************************************** **
225  * Determine whether or not a given name contains illegal characters, even
226  * long names.
227  *
228  *  Input:  name  - The name to be tested.
229  *
230  *  Output: True if an illegal character was found in <name>, else False.
231  *
232  *  Notes:  This is used to test a name on the host system, long or short,
233  *          for characters that would be illegal on most client systems,
234  *          particularly DOS and Windows systems.  Unix and AmigaOS, for
235  *          example, allow a filenames which contain such oddities as
236  *          quotes (").  If a name is found which does contain an illegal
237  *          character, it is mangled even if it conforms to the 8.3
238  *          format.
239  *
240  * ************************************************************************** **
241  */
242 static BOOL is_illegal_name( char *name )
243   {
244   unsigned char *s;
245   int            skip;
246
247   if( !name )
248     return( True );
249
250   if( !ct_initialized )
251     init_chartest();
252
253   s = (unsigned char *)name;
254   while( *s )
255     {
256     skip = skip_multibyte_char( *s );
257     if( skip != 0 )
258       {
259       s += skip;
260       }
261     else
262       {
263       if( isillegal( *s ) )
264         return( True );
265       else
266         s++;
267       }
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 file name.
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).
286  *
287  * ************************************************************************** **
288  */
289 BOOL is_mangled( char *s )
290   {
291   char *magic;
292
293   if( !ct_initialized )
294     init_chartest();
295
296   magic = strchr( s, magic_char );
297   while( magic && magic[1] && magic[2] )          /* 3 chars, 1st is magic. */
298     {
299     if( ('.' == magic[3] || !(magic[3]))          /* Ends with '.' or nul?  */
300      && isbasechar( toupper(magic[1]) )           /* is 2nd char basechar?  */
301      && isbasechar( toupper(magic[2]) ) )         /* is 3rd char basechar?  */
302       return( True );                           /* If all above, then true, */
303     magic = strchr( magic+1, magic_char );      /*    else seek next magic. */
304     }
305   return( False );
306   } /* is_mangled */
307
308 /* ************************************************************************** **
309  * Return True if the name is a valid DOS name in 8.3 DOS format.
310  *
311  *  Input:  fname       - File name to be checked.
312  *          check_case  - If True, and if case_mangle is True, then the
313  *                        name will be checked to see if all characters
314  *                        are the correct case.  See case_mangle and
315  *                        case_default above.
316  *
317  *  Output: True if the name is a valid DOS name, else FALSE.
318  *
319  * ************************************************************************** **
320  */
321 BOOL is_8_3( char *fname, BOOL check_case )
322   {
323   int   len;
324   int   l;
325   int   skip;
326   char *p;
327   char *dot_pos;
328   char *slash_pos = strrchr( 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( (skip = skip_multibyte_char( *p )) != 0 )
375       p += skip;
376     else 
377       {
378       if( *p == '.' && !dot_pos )
379         dot_pos = (char *)p;
380       else
381         if( !isdoschar( *p ) )
382           return( False );
383       p++;
384       }
385     }
386
387   /* no dot and less than 9 means OK */
388   if( !dot_pos )
389     return( len <= 8 );
390         
391   l = PTR_DIFF( dot_pos, fname );
392
393   /* base must be at least 1 char except special cases . and .. */
394   if( l == 0 )
395     return( 0 == strcmp( fname, "." ) || 0 == strcmp( fname, ".." ) );
396
397   /* base can't be greater than 8 */
398   if( l > 8 )
399     return( False );
400
401   /* see smb.conf(5) for a description of the 'strip dot' parameter. */
402   if( lp_strip_dot()
403    && len - l == 1
404    && !strchr( dot_pos + 1, '.' ) )
405     {
406     *dot_pos = 0;
407     return( True );
408     }
409
410   /* extension must be between 1 and 3 */
411   if( (len - l < 2 ) || (len - l > 4) )
412     return( False );
413
414   /* extensions may not have a dot */
415   if( strchr( dot_pos+1, '.' ) )
416     return( False );
417
418   /* must be in 8.3 format */
419   return( True );
420   } /* is_8_3 */
421
422 /* ************************************************************************** **
423  * Provide a checksum on a string
424  *
425  *  Input:  s - the nul-terminated character string for which the checksum
426  *              will be calculated.
427  *
428  *  Output: The checksum value calculated for s.
429  *
430  * ************************************************************************** **
431  */
432 int str_checksum( char *s )
433   {
434   int res = 0;
435   int c;
436   int i=0;
437
438   while( *s )
439     {
440     c = *s;
441     res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
442     s++;
443     i++;
444     }
445   return(res);
446   } /* str_checksum */
447
448 /* ************************************************************************** **
449  * Compare two cache keys and return a value indicating their ordinal
450  * relationship.
451  *
452  *  Input:  ItemPtr - Pointer to a comparison key.  In this case, this will
453  *                    be a mangled name string.
454  *          NodePtr - Pointer to a node in the cache.  The node structure
455  *                    will be followed in memory by a mangled name string.
456  *
457  *  Output: A signed integer, as follows:
458  *            (x < 0)  <==> Key1 less than Key2
459  *            (x == 0) <==> Key1 equals Key2
460  *            (x > 0)  <==> Key1 greater than Key2
461  *
462  *  Notes:  This is a ubiqx-style comparison routine.  See ubi_BinTree for
463  *          more info.
464  *
465  * ************************************************************************** **
466  */
467 static signed int cache_compare( ubi_btItemPtr ItemPtr, ubi_btNodePtr NodePtr )
468   {
469   char *Key1 = (char *)ItemPtr;
470   char *Key2 = (char *)(((ubi_cacheEntryPtr)NodePtr) + 1);
471
472   return( StrCaseCmp( Key1, Key2 ) );
473   } /* cache_compare */
474
475 /* ************************************************************************** **
476  * Free a cache entry.
477  *
478  *  Input:  WarrenZevon - Pointer to the entry that is to be returned to
479  *                        Nirvana.
480  *  Output: none.
481  *
482  *  Notes:  This function gets around the possibility that the standard
483  *          free() function may be implemented as a macro, or other evil
484  *          subversions (oh, so much fun).
485  *
486  * ************************************************************************** **
487  */
488 static void cache_free_entry( ubi_trNodePtr WarrenZevon )
489   {
490   free( WarrenZevon );
491   } /* cache_free_entry */
492
493 /* ************************************************************************** **
494  * Initializes or clears the mangled cache.
495  *
496  *  Input:  none.
497  *  Output: none.
498  *
499  *  Notes:  There is a section below that is commented out.  It shows how
500  *          one might use lp_ calls to set the maximum memory and entry size
501  *          of the cache.  You might also want to remove the constants used
502  *          in ubi_cacheInit() and replace them with lp_ calls.  If so, then
503  *          the calls to ubi_cacheSetMax*() would be moved into the else
504  *          clause.  Another option would be to pass in the max_entries and
505  *          max_memory values as parameters.  crh 09-Apr-1998.
506  *
507  * ************************************************************************** **
508  */
509 void reset_mangled_cache( void )
510   {
511   if( !mc_initialized )
512     {
513     (void)ubi_cacheInit( mangled_cache,
514                          cache_compare,
515                          cache_free_entry,
516                          MANGLED_CACHE_MAX_ENTRIES,
517                          MANGLED_CACHE_MAX_MEMORY );
518     mc_initialized = True;
519     }
520   else
521     {
522     (void)ubi_cacheClear( mangled_cache );
523     }
524
525   /*
526   (void)ubi_cacheSetMaxEntries( mangled_cache, lp_mangled_cache_entries() );
527   (void)ubi_cacheSetMaxMemory(  mangled_cache, lp_mangled_cache_memory() );
528   */
529   } /* reset_mangled_cache  */
530
531
532 /* ************************************************************************** **
533  * Add a mangled name into the cache.
534  *
535  *  Notes:  If the mangled cache has not been initialized, then the
536  *          function will simply fail.  It could initialize the cache,
537  *          but that's not the way it was done before I changed the
538  *          cache mechanism, so I'm sticking with the old method.
539  *
540  *          If the extension of the raw name maps directly to the
541  *          extension of the mangled name, then we'll store both names
542  *          *without* extensions.  That way, we can provide consistant
543  *          reverse mangling for all names that match.  The test here is
544  *          a bit more careful than the one done in earlier versions of
545  *          mangle.c:
546  *
547  *            - the extension must exist on the raw name,
548  *            - it must be all lower case
549  *            - it must match the mangled extension (to prove that no
550  *              mangling occurred).
551  *
552  *  crh 07-Apr-1998
553  *
554  * ************************************************************************** **
555  */
556 static void cache_mangled_name( char *mangled_name, char *raw_name )
557   {
558   ubi_cacheEntryPtr new_entry;
559   char             *s1;
560   char             *s2;
561   int               mangled_len;
562   int               raw_len;
563   int               i;
564
565   /* If the cache isn't initialized, give up. */
566   if( !mc_initialized )
567     return;
568
569   /* Init the string lengths. */
570   mangled_len = strlen( mangled_name );
571   raw_len     = strlen( raw_name );
572
573   /* See if the extensions are unmangled.  If so, store the entry
574    * without the extension, thus creating a "group" reverse map.
575    */
576   s1 = strrchr( mangled_name, '.' );
577   if( s1 && (s2 = strrchr( raw_name, '.' )) )
578     {
579     i = 1;
580     while( s1[i] && (tolower( s1[1] ) == s2[i]) )
581       i++;
582     if( !s1[i] && !s2[i] )
583       {
584       mangled_len -= i;
585       raw_len     -= i;
586       }
587     }
588
589   /* Allocate a new cache entry.  If the allcoation fails, just return. */
590   i = sizeof( ubi_cacheEntry ) + mangled_len + raw_len + 2;
591   new_entry = malloc( i );
592   if( !new_entry )
593     return;
594
595   /* Fill the new cache entry, and add it to the cache. */
596   s1 = (char *)(new_entry + 1);
597   s2 = (char *)&(s1[mangled_len + 1]);
598   (void)StrnCpy( s1, mangled_name, mangled_len );
599   (void)StrnCpy( s2, raw_name,     raw_len );
600   ubi_cachePut( mangled_cache, i, new_entry, s1 );
601   } /* cache_mangled_name */
602
603 /* ************************************************************************** **
604  * Check for a name on the mangled name stack
605  *
606  *  Input:  s - Input *and* output string buffer.
607  *
608  *  Output: True if the name was found in the cache, else False.
609  *
610  *  Notes:  If a reverse map is found, the function will overwrite the string
611  *          space indicated by the input pointer <s>.  This is frightening.
612  *          It should be rewritten to return NULL if the long name was not
613  *          found, and a pointer to the long name if it was found.
614  *
615  * ************************************************************************** **
616  */
617 BOOL check_mangled_cache( char *s )
618   {
619   ubi_cacheEntryPtr FoundPtr;
620   char             *ext_start = NULL;
621   char             *found_name;
622
623   /* If the cache isn't initialized, give up. */
624   if( !mc_initialized )
625     return( False );
626
627   FoundPtr = ubi_cacheGet( mangled_cache, (ubi_trItemPtr)s );
628
629   /* If we didn't find the name *with* the extension, try without. */
630   if( !FoundPtr )
631     {
632     ext_start = strrchr( s, '.' );
633     if( ext_start )
634       {
635       *ext_start = '\0';
636       FoundPtr = ubi_cacheGet( mangled_cache, (ubi_trItemPtr)s );
637       *ext_start = '.';
638       }
639     }
640
641   /* Okay, if we haven't found it we're done. */
642   if( !FoundPtr )
643     return( False );
644
645   /* If we *did* find it, we need to copy it into the string buffer. */
646   found_name = (char *)(FoundPtr + 1);
647   found_name += (strlen( found_name ) + 1);
648
649   DEBUG( 3, ("Found %s on mangled stack ", s) );
650
651   (void)strcpy( s, found_name );
652   if( ext_start )
653     (void)strcat( s, ext_start );
654
655   DEBUG( 3, ("as %s\n", s) );
656
657   return( True );
658   } /* check_mangled_cache */
659
660
661 /* ************************************************************************** **
662  * Used only in do_fwd_mangled_map(), below.
663  * ************************************************************************** **
664  */
665 static char *map_filename( char *s,         /* This is null terminated */
666                            char *pattern,   /* This isn't. */
667                            int len )        /* This is the length of pattern. */
668   {
669   static pstring matching_bit;  /* The bit of the string which matches */
670                                 /* a * in pattern if indeed there is a * */
671   char *sp;                     /* Pointer into s. */
672   char *pp;                     /* Pointer into p. */
673   char *match_start;            /* Where the matching bit starts. */
674   pstring pat;
675
676   StrnCpy( pat, pattern, len ); /* Get pattern into a proper string! */
677   pstrcpy( matching_bit, "" );  /* Match but no star gets this. */
678   pp = pat;                     /* Initialize the pointers. */
679   sp = s;
680   if( (len == 1) && (*pattern == '*') )
681     {
682     return NULL;                /* Impossible, too ambiguous for */
683     }                           /* words! */
684
685   while( (*sp)                  /* Not the end of the string. */
686       && (*pp)                  /* Not the end of the pattern. */
687       && (*sp == *pp)           /* The two match. */
688       && (*pp != '*') )         /* No wildcard. */
689     {
690     sp++;                       /* Keep looking. */
691     pp++;
692     }
693
694   if( !*sp && !*pp )            /* End of pattern. */
695     return( matching_bit );     /* Simple match.  Return empty string. */
696
697   if( *pp == '*' )
698     {
699     pp++;                       /* Always interrested in the chacter */
700                                 /* after the '*' */
701     if( !*pp )                  /* It is at the end of the pattern. */
702       {
703       StrnCpy( matching_bit, s, sp-s );
704       return( matching_bit );
705       }
706     else
707       {
708       /* The next character in pattern must match a character further */
709       /* along s than sp so look for that character. */
710       match_start = sp;
711       while( (*sp)              /* Not the end of s. */
712           && (*sp != *pp) )     /* Not the same  */
713         sp++;                   /* Keep looking. */
714       if( !*sp )                /* Got to the end without a match. */
715         {
716         return( NULL );
717         }                       /* Still hope for a match. */
718       else
719         {
720         /* Now sp should point to a matching character. */
721         StrnCpy(matching_bit, match_start, sp-match_start);
722         /* Back to needing a stright match again. */
723         while( (*sp)            /* Not the end of the string. */
724             && (*pp)            /* Not the end of the pattern. */
725             && (*sp == *pp) )   /* The two match. */
726           {
727           sp++;                 /* Keep looking. */
728           pp++;
729           }
730         if( !*sp && !*pp )      /* Both at end so it matched */
731           return( matching_bit );
732         else
733           return( NULL );
734         }
735       }
736     }
737   return( NULL );               /* No match. */
738   } /* map_filename */
739
740
741 /* ************************************************************************** **
742  * MangledMap is a series of name pairs in () separated by spaces.
743  * If s matches the first of the pair then the name given is the
744  * second of the pair.  A * means any number of any character and if
745  * present in the second of the pair as well as the first the
746  * matching part of the first string takes the place of the * in the
747  * second.
748  *
749  * I wanted this so that we could have RCS files which can be used
750  * by UNIX and DOS programs.  My mapping string is (RCS rcs) which
751  * converts the UNIX RCS file subdirectory to lowercase thus
752  * preventing mangling.
753  *
754  * (I think Andrew wrote the above, but I'm not sure. -- CRH)
755  *
756  * See 'mangled map' in smb.conf(5).
757  *
758  * ************************************************************************** **
759  */
760 static void do_fwd_mangled_map(char *s, char *MangledMap)
761   {
762   char *start=MangledMap;       /* Use this to search for mappings. */
763   char *end;                    /* Used to find the end of strings. */
764   char *match_string;
765   pstring new_string;           /* Make up the result here. */
766   char *np;                     /* Points into new_string. */
767
768   DEBUG( 5, ("Mangled Mapping '%s' map '%s'\n", s, MangledMap) );
769   while( *start )
770     {
771     while( (*start) && (*start != '(') )
772       start++;
773     if( !*start )
774       continue;                 /* Always check for the end. */
775     start++;                    /* Skip the ( */
776     end = start;                /* Search for the ' ' or a ')' */
777     DEBUG( 5, ("Start of first in pair '%s'\n", start) );
778     while( (*end) && !((*end == ' ') || (*end == ')')) )
779       end++;
780     if( !*end )
781       {
782       start = end;
783       continue;                 /* Always check for the end. */
784       }
785     DEBUG( 5, ("End of first in pair '%s'\n", end) );
786     if( (match_string = map_filename( s, start, end-start )) )
787       {
788       DEBUG( 5, ("Found a match\n") );
789       /* Found a match. */
790       start = end + 1;          /* Point to start of what it is to become. */
791       DEBUG( 5, ("Start of second in pair '%s'\n", start) );
792       end = start;
793       np = new_string;
794       while( (*end)             /* Not the end of string. */
795           && (*end != ')')      /* Not the end of the pattern. */
796           && (*end != '*') )    /* Not a wildcard. */
797         *np++ = *end++;
798       if( !*end )
799         {
800         start = end;
801         continue;               /* Always check for the end. */
802         }
803       if( *end == '*' )
804         {
805         pstrcpy( np, match_string );
806         np += strlen( match_string );
807         end++;                  /* Skip the '*' */
808         while( (*end)             /* Not the end of string. */
809             && (*end != ')')      /* Not the end of the pattern. */
810             && (*end != '*') )    /* Not a wildcard. */
811           *np++ = *end++;
812         }
813       if( !*end )
814         {
815         start = end;
816         continue;               /* Always check for the end. */
817         }
818       *np++ = '\0';             /* NULL terminate it. */
819       DEBUG(5,("End of second in pair '%s'\n", end));
820       pstrcpy( s, new_string );  /* Substitute with the new name. */
821       DEBUG( 5, ("s is now '%s'\n", s) );
822       }
823     start = end;              /* Skip a bit which cannot be wanted anymore. */
824     start++;
825     }
826   } /* do_fwd_mangled_map */
827
828 /* ************************************************************************** **
829  * do the actual mangling to 8.3 format
830  *
831  * ************************************************************************** **
832  */
833 void mangle_name_83( char *s )
834   {
835   int csum = str_checksum(s);
836   char *p;
837   char extension[4];
838   char base[9];
839   int baselen = 0;
840   int extlen = 0;
841   int skip;
842
843   extension[0] = 0;
844   base[0] = 0;
845
846   p = strrchr(s,'.');  
847   if( p && (strlen(p+1) < (size_t)4) )
848     {
849     BOOL all_normal = ( strisnormal(p+1) ); /* XXXXXXXXX */
850
851     if( all_normal && p[1] != 0 )
852       {
853       *p = 0;
854       csum = str_checksum( s );
855       *p = '.';
856       }
857     }
858
859   strupper( s );
860
861   DEBUG( 5, ("Mangling name %s to ",s) );
862
863   if( p )
864     {
865     if( p == s )
866       strcpy( extension, "___" );
867     else
868       {
869       *p++ = 0;
870       while( *p && extlen < 3 )
871         {
872         skip = skip_multibyte_char( *p );
873         switch( skip )
874           {
875           case 2: 
876             if( extlen < 2 )
877               {
878               extension[extlen++] = p[0];
879               extension[extlen++] = p[1];
880               }
881             else 
882               {
883               extension[extlen++] = base36( (unsigned char)*p );
884               }
885             p += 2;
886             break;
887           case 1:
888             extension[extlen++] = p[0];
889             p++;
890             break;
891           default:
892             if( isdoschar (*p) && *p != '.' )
893               extension[extlen++] = p[0];
894             p++;
895             break;
896           }
897         }
898       extension[extlen] = 0;
899       }
900     }
901
902   p = s;
903
904   while( *p && baselen < 5 )
905     {
906     skip = skip_multibyte_char(*p);
907     switch( skip )
908       {
909       case 2:
910         if( baselen < 4 )
911           {
912           base[baselen++] = p[0];
913           base[baselen++] = p[1];
914           }
915         else 
916           {
917           base[baselen++] = base36( (unsigned char)*p );
918           }
919         p += 2;
920         break;
921       case 1:
922         base[baselen++] = p[0];
923         p++;
924         break;
925       default:
926         if( isdoschar( *p ) && *p != '.' )
927           base[baselen++] = p[0];
928         p++;
929         break;
930       }
931     }
932   base[baselen] = 0;
933
934   csum = csum % (36*36);
935
936   (void)sprintf( s, "%s%c%c%c",
937                  base, magic_char, base36( csum/36 ), base36( csum ) );
938
939   if( *extension )
940     {
941     (void)strcat( s, "." );
942     (void)strcat( s, extension );
943     }
944
945   DEBUG( 5, ( "%s\n", s ) );
946   } /* mangle_name_83 */
947
948 /* ************************************************************************** **
949  * Convert a filename to DOS format.  Return True if successful.
950  *
951  *  Input:  OutName - Source *and* destination buffer.
952  *
953  *                    NOTE that OutName must point to a memory space that
954  *                    is at least 13 bytes in size!
955  *
956  *          need83  - If False, name mangling will be skipped unless the
957  *                    name contains illegal characters.  Mapping will still
958  *                    be done, if appropriate.  This is probably used to
959  *                    signal that a client does not require name mangling,
960  *                    thus skipping the name mangling even on shares which
961  *                    have name-mangling turned on.
962  *          snum    - Share number.  This identifies the share in which the
963  *                    name exists.
964  *
965  *  Output: Returns False only if the name wanted mangling but the share does
966  *          not have name mangling turned on.
967  *
968  * ************************************************************************** **
969  */
970 BOOL name_map_mangle( char *OutName, BOOL need83, int snum )
971   {
972   DEBUG(5,
973     ("name_map_mangle( %s, %s, %d )\n", OutName, need83?"TRUE":"FALSE", snum) );
974
975 #ifdef MANGLE_LONG_FILENAMES
976   if( !need83 && is_illegal_name(OutName) )
977     need83 = True;
978 #endif  
979
980   /* apply any name mappings */
981   {
982   char *map = lp_mangled_map( snum );
983
984   if( map && *map )
985     do_fwd_mangled_map( OutName, map );
986   }
987
988   /* check if it's already in 8.3 format */
989   if( need83 && !is_8_3( OutName, True ) )
990     {
991     char *tmp;  /* kludge -- mangle_name_83() overwrites the source string    */
992                 /* but cache_mangled_name() needs both.  crh 09-Apr-1998      */
993
994     if( !lp_manglednames( snum ) )
995       return( False );
996
997     /* mangle it into 8.3 */
998     tmp = strdup( OutName );
999     mangle_name_83( OutName );
1000     if( tmp )
1001       {
1002       cache_mangled_name( OutName, tmp );  
1003       free( tmp );
1004       }
1005     }
1006
1007   DEBUG( 5, ("name_map_mangle() ==> [%s]\n", OutName) );
1008   return( True );
1009   } /* name_map_mangle */
1010
1011 /* ========================================================================== */