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