2 Unix SMB/Netbios implementation.
5 Copyright (C) Andrew Tridgell 1992-1998
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.
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.
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.
22 /* -------------------------------------------------------------------------- **
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()
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.
35 * -------------------------------------------------------------------------- **
38 /* -------------------------------------------------------------------------- **
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.
45 * -------------------------------------------------------------------------- **
51 /* -------------------------------------------------------------------------- **
52 * External Variables...
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. */
58 /* -------------------------------------------------------------------------- **
61 * magic_char - This is the magic char used for mangling. It's
62 * global. There is a call to lp_magicchar() in server.c
63 * that is used to override the initial value.
65 * MANGLE_BASE - This is the number of characters we use for name mangling.
67 * basechars - The set characters used for name mangling. This
68 * is static (scope is this file only).
70 * mangle() - Macro used to select a character from basechars (i.e.,
71 * mangle(n) will return the nth digit, modulo MANGLE_BASE).
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,
78 * ct_initialized - False until the chartest array has been initialized via
79 * a call to init_chartest().
81 * BASECHAR_MASK - Masks the upper nibble of a one-byte value.
83 * ILLEGAL_MASK - Masks the lower nibble of a one-byte value.
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_m().
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_m().
93 * mangled_cache - Cache header used for storing mangled -> original
96 * mc_initialized - False until the mangled_cache structure has been
97 * initialized via a call to reset_mangled_cache().
99 * MANGLED_CACHE_MAX_ENTRIES - Default maximum number of entries for the
100 * cache. A value of 0 indicates "infinite".
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
112 char magic_char = '~';
114 static char basechars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_-!@#$%";
115 #define MANGLE_BASE ( (sizeof(basechars)/sizeof(char)) - 1 )
117 static unsigned char chartest[256] = { 0 };
118 static BOOL ct_initialized = False;
120 #define mangle(V) ((char)(basechars[(V) % MANGLE_BASE]))
121 #define BASECHAR_MASK 0xf0
122 #define ILLEGAL_MASK 0x0f
123 #define isbasechar(C) ( (chartest[ ((C) & 0xff) ]) & BASECHAR_MASK )
124 #define isillegal(C) ( (chartest[ ((C) & 0xff) ]) & ILLEGAL_MASK )
126 static ubi_cacheRoot mangled_cache[1] = {{ { 0, 0, 0, 0 }, 0, 0, 0, 0, 0, 0 }};
127 static BOOL mc_initialized = False;
128 #define MANGLED_CACHE_MAX_ENTRIES 0
129 #define MANGLED_CACHE_MAX_MEMORY 16384
132 /* -------------------------------------------------------------------------- **
136 /* ************************************************************************** **
137 * Initialize the static character test array.
143 * Notes: This function changes (loads) the contents of the <chartest>
144 * array. The scope of <chartest> is this file.
146 * ************************************************************************** **
148 static void init_chartest( void )
150 char *illegalchars = "*\\/?<>|\":";
153 memset( (char *)chartest, '\0', 256 );
155 for( s = (unsigned char *)illegalchars; *s; s++ )
156 chartest[*s] = ILLEGAL_MASK;
158 for( s = (unsigned char *)basechars; *s; s++ )
159 chartest[*s] |= BASECHAR_MASK;
161 ct_initialized = True;
162 } /* init_chartest */
164 /* ************************************************************************** **
165 * Return True if a name is a special msdos reserved name.
167 * Input: fname - String containing the name to be tested.
169 * Output: True, if the name matches one of the list of reserved names.
171 * Notes: This is a static function called by is_8_3(), below.
173 * ************************************************************************** **
175 static BOOL is_reserved_msdos( char *fname )
180 StrnCpy (upperFname, fname, 12);
182 /* lpt1.txt and con.txt etc are also illegal */
183 p = strchr_m(upperFname,'.');
187 strupper( upperFname );
189 switch( upperFname[0] )
192 if( 0 == strcmp( p, "UX" ) )
196 if( (0 == strcmp( p, "LOCK$" ))
197 || (0 == strcmp( p, "ON" ))
198 || (0 == strcmp( p, "OM1" ))
199 || (0 == strcmp( p, "OM2" ))
200 || (0 == strcmp( p, "OM3" ))
201 || (0 == strcmp( p, "OM4" ))
206 if( (0 == strcmp( p, "PT1" ))
207 || (0 == strcmp( p, "PT2" ))
208 || (0 == strcmp( p, "PT3" ))
213 if( 0 == strcmp( p, "UL" ) )
217 if( 0 == strcmp( p, "RN" ) )
223 } /* is_reserved_msdos */
225 /* ************************************************************************** **
226 * Determine whether or not a given name contains illegal characters, even
229 * Input: name - The name to be tested.
231 * Output: True if an illegal character was found in <name>, else False.
233 * Notes: This is used to test a name on the host system, long or short,
234 * for characters that would be illegal on most client systems,
235 * particularly DOS and Windows systems. Unix and AmigaOS, for
236 * example, allow a filenames which contain such oddities as
237 * quotes ("). If a name is found which does contain an illegal
238 * character, it is mangled even if it conforms to the 8.3
241 * ************************************************************************** **
243 static BOOL is_illegal_name( char *name )
250 if( !ct_initialized )
253 s = (unsigned char *)name;
256 if( *s>0x7F && isillegal( *s ) )
263 } /* is_illegal_name */
265 /* ************************************************************************** **
266 * Return True if the name *could be* a mangled name.
268 * Input: s - A path name - in UNIX pathname format.
270 * Output: True if the name matches the pattern described below in the
273 * Notes: The input name is *not* tested for 8.3 compliance. This must be
274 * done separately. This function returns true if the name contains
275 * a magic character followed by excactly two characters from the
276 * basechars list (above), which in turn are followed either by the
277 * nul (end of string) byte or a dot (extension) or by a '/' (end of
280 * ************************************************************************** **
282 BOOL is_mangled( char *s )
286 if( !ct_initialized )
289 magic = strchr_m( s, magic_char );
290 while( magic && magic[1] && magic[2] ) /* 3 chars, 1st is magic. */
292 if( ('.' == magic[3] || '/' == magic[3] || !(magic[3])) /* Ends with '.' or nul or '/' ? */
293 && isbasechar( toupper(magic[1]) ) /* is 2nd char basechar? */
294 && isbasechar( toupper(magic[2]) ) ) /* is 3rd char basechar? */
295 return( True ); /* If all above, then true, */
296 magic = strchr_m( magic+1, magic_char ); /* else seek next magic. */
301 /* ************************************************************************** **
302 * Return True if the name is a valid DOS name in 8.3 DOS format.
304 * Input: fname - File name to be checked.
305 * check_case - If True, and if case_mangle is True, then the
306 * name will be checked to see if all characters
307 * are the correct case. See case_mangle and
308 * case_default above.
310 * Output: True if the name is a valid DOS name, else FALSE.
312 * ************************************************************************** **
314 BOOL is_8_3( char *fname, BOOL check_case )
320 char *slash_pos = strrchr_m( fname, '/' );
322 /* If there is a directory path, skip it. */
324 fname = slash_pos + 1;
325 len = strlen( fname );
327 DEBUG( 5, ( "Checking %s for 8.3\n", fname ) );
329 /* Can't be 0 chars or longer than 12 chars */
330 if( (len == 0) || (len > 12) )
333 /* Mustn't be an MS-DOS Special file such as lpt1 or even lpt1.txt */
334 if( is_reserved_msdos( fname ) )
337 /* Check that all characters are the correct case, if asked to do so. */
338 if( check_case && case_mangle )
340 switch( case_default )
343 if( strhasupper( fname ) )
347 if( strhaslower( fname ) )
353 /* Can't contain invalid dos chars */
354 /* Windows use the ANSI charset.
355 But filenames are translated in the PC charset.
356 This Translation may be more or less relaxed depending
357 the Windows application. */
359 /* %%% A nice improvment to name mangling would be to translate
360 filename to ANSI charset on the smb server host */
366 if( *p == '.' && !dot_pos )
369 if( !isdoschar( *p ) )
374 /* no dot and less than 9 means OK */
378 l = PTR_DIFF( dot_pos, fname );
380 /* base must be at least 1 char except special cases . and .. */
382 return( 0 == strcmp( fname, "." ) || 0 == strcmp( fname, ".." ) );
384 /* base can't be greater than 8 */
388 /* see smb.conf(5) for a description of the 'strip dot' parameter. */
391 && !strchr_m( dot_pos + 1, '.' ) )
397 /* extension must be between 1 and 3 */
398 if( (len - l < 2 ) || (len - l > 4) )
401 /* extensions may not have a dot */
402 if( strchr_m( dot_pos+1, '.' ) )
405 /* must be in 8.3 format */
410 /* ************************************************************************** **
411 * Compare two cache keys and return a value indicating their ordinal
414 * Input: ItemPtr - Pointer to a comparison key. In this case, this will
415 * be a mangled name string.
416 * NodePtr - Pointer to a node in the cache. The node structure
417 * will be followed in memory by a mangled name string.
419 * Output: A signed integer, as follows:
420 * (x < 0) <==> Key1 less than Key2
421 * (x == 0) <==> Key1 equals Key2
422 * (x > 0) <==> Key1 greater than Key2
424 * Notes: This is a ubiqx-style comparison routine. See ubi_BinTree for
427 * ************************************************************************** **
429 static signed int cache_compare( ubi_btItemPtr ItemPtr, ubi_btNodePtr NodePtr )
431 char *Key1 = (char *)ItemPtr;
432 char *Key2 = (char *)(((ubi_cacheEntryPtr)NodePtr) + 1);
434 return( StrCaseCmp( Key1, Key2 ) );
435 } /* cache_compare */
437 /* ************************************************************************** **
438 * Free a cache entry.
440 * Input: WarrenZevon - Pointer to the entry that is to be returned to
444 * Notes: This function gets around the possibility that the standard
445 * free() function may be implemented as a macro, or other evil
446 * subversions (oh, so much fun).
448 * ************************************************************************** **
450 static void cache_free_entry( ubi_trNodePtr WarrenZevon )
452 ZERO_STRUCTP(WarrenZevon);
453 SAFE_FREE( WarrenZevon );
454 } /* cache_free_entry */
456 /* ************************************************************************** **
457 * Initializes or clears the mangled cache.
462 * Notes: There is a section below that is commented out. It shows how
463 * one might use lp_ calls to set the maximum memory and entry size
464 * of the cache. You might also want to remove the constants used
465 * in ubi_cacheInit() and replace them with lp_ calls. If so, then
466 * the calls to ubi_cacheSetMax*() would be moved into the else
467 * clause. Another option would be to pass in the max_entries and
468 * max_memory values as parameters. crh 09-Apr-1998.
470 * ************************************************************************** **
472 void reset_mangled_cache( void )
474 if( !mc_initialized )
476 (void)ubi_cacheInit( mangled_cache,
479 MANGLED_CACHE_MAX_ENTRIES,
480 MANGLED_CACHE_MAX_MEMORY );
481 mc_initialized = True;
485 (void)ubi_cacheClear( mangled_cache );
489 (void)ubi_cacheSetMaxEntries( mangled_cache, lp_mangled_cache_entries() );
490 (void)ubi_cacheSetMaxMemory( mangled_cache, lp_mangled_cache_memory() );
492 } /* reset_mangled_cache */
495 /* ************************************************************************** **
496 * Add a mangled name into the cache.
498 * Notes: If the mangled cache has not been initialized, then the
499 * function will simply fail. It could initialize the cache,
500 * but that's not the way it was done before I changed the
501 * cache mechanism, so I'm sticking with the old method.
503 * If the extension of the raw name maps directly to the
504 * extension of the mangled name, then we'll store both names
505 * *without* extensions. That way, we can provide consistent
506 * reverse mangling for all names that match. The test here is
507 * a bit more careful than the one done in earlier versions of
510 * - the extension must exist on the raw name,
511 * - it must be all lower case
512 * - it must match the mangled extension (to prove that no
513 * mangling occurred).
517 * ************************************************************************** **
519 static void cache_mangled_name( char *mangled_name, char *raw_name )
521 ubi_cacheEntryPtr new_entry;
528 /* If the cache isn't initialized, give up. */
529 if( !mc_initialized )
532 /* Init the string lengths. */
533 mangled_len = strlen( mangled_name );
534 raw_len = strlen( raw_name );
536 /* See if the extensions are unmangled. If so, store the entry
537 * without the extension, thus creating a "group" reverse map.
539 s1 = strrchr_m( mangled_name, '.' );
540 if( s1 && (s2 = strrchr_m( raw_name, '.' )) )
543 while( s1[i] && (tolower( s1[1] ) == s2[i]) )
545 if( !s1[i] && !s2[i] )
552 /* Allocate a new cache entry. If the allocation fails, just return. */
553 i = sizeof( ubi_cacheEntry ) + mangled_len + raw_len + 2;
554 new_entry = malloc( i );
558 /* Fill the new cache entry, and add it to the cache. */
559 s1 = (char *)(new_entry + 1);
560 s2 = (char *)&(s1[mangled_len + 1]);
561 (void)StrnCpy( s1, mangled_name, mangled_len );
562 (void)StrnCpy( s2, raw_name, raw_len );
563 ubi_cachePut( mangled_cache, i, new_entry, s1 );
564 } /* cache_mangled_name */
566 /* ************************************************************************** **
567 * Check for a name on the mangled name stack
569 * Input: s - Input *and* output string buffer.
571 * Output: True if the name was found in the cache, else False.
573 * Notes: If a reverse map is found, the function will overwrite the string
574 * space indicated by the input pointer <s>. This is frightening.
575 * It should be rewritten to return NULL if the long name was not
576 * found, and a pointer to the long name if it was found.
578 * ************************************************************************** **
581 BOOL check_mangled_cache( char *s )
583 ubi_cacheEntryPtr FoundPtr;
584 char *ext_start = NULL;
586 char *saved_ext = NULL;
588 /* If the cache isn't initialized, give up. */
589 if( !mc_initialized )
592 FoundPtr = ubi_cacheGet( mangled_cache, (ubi_trItemPtr)s );
594 /* If we didn't find the name *with* the extension, try without. */
597 ext_start = strrchr_m( s, '.' );
600 if((saved_ext = strdup(ext_start)) == NULL)
604 FoundPtr = ubi_cacheGet( mangled_cache, (ubi_trItemPtr)s );
606 * At this point s is the name without the
607 * extension. We re-add the extension if saved_ext
608 * is not null, before freeing saved_ext.
613 /* Okay, if we haven't found it we're done. */
618 /* Replace the saved_ext as it was truncated. */
619 (void)pstrcat( s, saved_ext );
620 SAFE_FREE(saved_ext);
625 /* If we *did* find it, we need to copy it into the string buffer. */
626 found_name = (char *)(FoundPtr + 1);
627 found_name += (strlen( found_name ) + 1);
629 DEBUG( 3, ("Found %s on mangled stack ", s) );
631 (void)pstrcpy( s, found_name );
634 /* Replace the saved_ext as it was truncated. */
635 (void)pstrcat( s, saved_ext );
636 SAFE_FREE(saved_ext);
639 DEBUG( 3, ("as %s\n", s) );
642 } /* check_mangled_cache */
645 /* ************************************************************************** **
646 * Used only in do_fwd_mangled_map(), below.
647 * ************************************************************************** **
649 static char *map_filename( char *s, /* This is null terminated */
650 char *pattern, /* This isn't. */
651 int len ) /* This is the length of pattern. */
653 static pstring matching_bit; /* The bit of the string which matches */
654 /* a * in pattern if indeed there is a * */
655 char *sp; /* Pointer into s. */
656 char *pp; /* Pointer into p. */
657 char *match_start; /* Where the matching bit starts. */
660 StrnCpy( pat, pattern, len ); /* Get pattern into a proper string! */
661 pstrcpy( matching_bit, "" ); /* Match but no star gets this. */
662 pp = pat; /* Initialize the pointers. */
665 if( strequal(s, ".") || strequal(s, ".."))
667 return NULL; /* Do not map '.' and '..' */
670 if( (len == 1) && (*pattern == '*') )
672 return NULL; /* Impossible, too ambiguous for */
675 while( (*sp) /* Not the end of the string. */
676 && (*pp) /* Not the end of the pattern. */
677 && (*sp == *pp) /* The two match. */
678 && (*pp != '*') ) /* No wildcard. */
680 sp++; /* Keep looking. */
684 if( !*sp && !*pp ) /* End of pattern. */
685 return( matching_bit ); /* Simple match. Return empty string. */
689 pp++; /* Always interrested in the chacter */
691 if( !*pp ) /* It is at the end of the pattern. */
693 StrnCpy( matching_bit, s, sp-s );
694 return( matching_bit );
698 /* The next character in pattern must match a character further */
699 /* along s than sp so look for that character. */
701 while( (*sp) /* Not the end of s. */
702 && (*sp != *pp) ) /* Not the same */
703 sp++; /* Keep looking. */
704 if( !*sp ) /* Got to the end without a match. */
707 } /* Still hope for a match. */
710 /* Now sp should point to a matching character. */
711 StrnCpy(matching_bit, match_start, sp-match_start);
712 /* Back to needing a stright match again. */
713 while( (*sp) /* Not the end of the string. */
714 && (*pp) /* Not the end of the pattern. */
715 && (*sp == *pp) ) /* The two match. */
717 sp++; /* Keep looking. */
720 if( !*sp && !*pp ) /* Both at end so it matched */
721 return( matching_bit );
727 return( NULL ); /* No match. */
731 /* ************************************************************************** **
732 * MangledMap is a series of name pairs in () separated by spaces.
733 * If s matches the first of the pair then the name given is the
734 * second of the pair. A * means any number of any character and if
735 * present in the second of the pair as well as the first the
736 * matching part of the first string takes the place of the * in the
739 * I wanted this so that we could have RCS files which can be used
740 * by UNIX and DOS programs. My mapping string is (RCS rcs) which
741 * converts the UNIX RCS file subdirectory to lowercase thus
742 * preventing mangling.
744 * (I think Andrew wrote the above, but I'm not sure. -- CRH)
746 * See 'mangled map' in smb.conf(5).
748 * ************************************************************************** **
750 static void do_fwd_mangled_map(char *s, char *MangledMap)
752 char *start=MangledMap; /* Use this to search for mappings. */
753 char *end; /* Used to find the end of strings. */
755 pstring new_string; /* Make up the result here. */
756 char *np; /* Points into new_string. */
758 DEBUG( 5, ("Mangled Mapping '%s' map '%s'\n", s, MangledMap) );
761 while( (*start) && (*start != '(') )
764 continue; /* Always check for the end. */
765 start++; /* Skip the ( */
766 end = start; /* Search for the ' ' or a ')' */
767 DEBUG( 5, ("Start of first in pair '%s'\n", start) );
768 while( (*end) && !((*end == ' ') || (*end == ')')) )
773 continue; /* Always check for the end. */
775 DEBUG( 5, ("End of first in pair '%s'\n", end) );
776 if( (match_string = map_filename( s, start, end-start )) )
778 DEBUG( 5, ("Found a match\n") );
780 start = end + 1; /* Point to start of what it is to become. */
781 DEBUG( 5, ("Start of second in pair '%s'\n", start) );
784 while( (*end) /* Not the end of string. */
785 && (*end != ')') /* Not the end of the pattern. */
786 && (*end != '*') ) /* Not a wildcard. */
791 continue; /* Always check for the end. */
795 pstrcpy( np, match_string );
796 np += strlen( match_string );
797 end++; /* Skip the '*' */
798 while( (*end) /* Not the end of string. */
799 && (*end != ')') /* Not the end of the pattern. */
800 && (*end != '*') ) /* Not a wildcard. */
806 continue; /* Always check for the end. */
808 *np++ = '\0'; /* NULL terminate it. */
809 DEBUG(5,("End of second in pair '%s'\n", end));
810 pstrcpy( s, new_string ); /* Substitute with the new name. */
811 DEBUG( 5, ("s is now '%s'\n", s) );
813 start = end; /* Skip a bit which cannot be wanted anymore. */
816 } /* do_fwd_mangled_map */
818 /*****************************************************************************
819 * do the actual mangling to 8.3 format
820 * the buffer must be able to hold 13 characters (including the null)
821 *****************************************************************************
823 void mangle_name_83( char *s)
835 p = strrchr_m(s,'.');
836 if( p && (strlen(p+1) < (size_t)4) )
838 BOOL all_normal = ( strisnormal(p+1) ); /* XXXXXXXXX */
840 if( all_normal && p[1] != 0 )
843 csum = str_checksum( s );
847 csum = str_checksum(s);
850 csum = str_checksum(s);
854 DEBUG( 5, ("Mangling name %s to ",s) );
859 safe_strcpy( extension, "___", 3 );
863 while( *p && extlen < 3 )
865 if( /*isdoschar (*p) &&*/ *p != '.' )
866 extension[extlen++] = p[0];
869 extension[extlen] = 0;
875 while( *p && baselen < 5 )
877 if( /*isdoschar( *p ) &&*/ *p != '.' )
878 base[baselen++] = p[0];
883 csum = csum % (MANGLE_BASE*MANGLE_BASE);
885 (void)slprintf(s, 12, "%s%c%c%c",
886 base, magic_char, mangle( csum/MANGLE_BASE ), mangle( csum ) );
890 (void)pstrcat( s, "." );
891 (void)pstrcat( s, extension );
894 DEBUG( 5, ( "%s\n", s ) );
896 } /* mangle_name_83 */
898 /*****************************************************************************
899 * Convert a filename to DOS format. Return True if successful.
901 * Input: OutName - Source *and* destination buffer.
903 * NOTE that OutName must point to a memory space that
904 * is at least 13 bytes in size!
906 * need83 - If False, name mangling will be skipped unless the
907 * name contains illegal characters. Mapping will still
908 * be done, if appropriate. This is probably used to
909 * signal that a client does not require name mangling,
910 * thus skipping the name mangling even on shares which
911 * have name-mangling turned on.
912 * cache83 - If False, the mangled name cache will not be updated.
913 * This is usually used to prevent that we overwrite
914 * a conflicting cache entry prematurely, i.e. before
915 * we know whether the client is really interested in the
916 * current name. (See PR#13758). UKD.
917 * snum - Share number. This identifies the share in which the
920 * Output: Returns False only if the name wanted mangling but the share does
921 * not have name mangling turned on.
923 * ****************************************************************************
925 BOOL name_map_mangle(char *OutName, BOOL need83, BOOL cache83, int snum)
928 DEBUG(5,("name_map_mangle( %s, need83 = %s, cache83 = %s, %d )\n", OutName,
929 need83 ? "TRUE" : "FALSE", cache83 ? "TRUE" : "FALSE", snum));
931 #ifdef MANGLE_LONG_FILENAMES
932 if( !need83 && is_illegal_name(OutName) )
936 /* apply any name mappings */
937 map = lp_mangled_map(snum);
940 do_fwd_mangled_map( OutName, map );
943 /* check if it's already in 8.3 format */
944 if (need83 && !is_8_3(OutName, True)) {
947 if (!lp_manglednames(snum)) {
951 /* mangle it into 8.3 */
953 tmp = strdup(OutName);
955 mangle_name_83(OutName);
958 cache_mangled_name(OutName, tmp);
963 DEBUG(5,("name_map_mangle() ==> [%s]\n", OutName));
965 } /* name_map_mangle */
972 #define MANGLE_TDB_VERSION "20010927"
973 #define MANGLE_TDB_FILE_NAME "mangle.tdb"
974 #define MANGLED_PREFIX "MANGLED_"
975 #define LONG_PREFIX "LONG_"
976 #define COUNTER_PREFIX "COUNTER_"
977 #define MANGLE_COUNTER_MAX 99
978 #define MANGLE_SUFFIX_SIZE 2
981 struct mt_enum_info {
982 TDB_CONTEXT *mangle_tdb;
987 static struct mt_enum_info global_mt_ent = {0, 0};
989 static int POW10(unsigned int exp)
1001 static BOOL init_mangle_tdb(void)
1005 if (global_mt_ent.mangle_tdb == 0)
1007 tdbfile = lock_path(MANGLE_TDB_FILE_NAME); /* this return a static pstring do not try to free it */
1010 if (!(global_mt_ent.mangle_tdb = tdb_open_log(tdbfile, 0, TDB_DEFAULT, O_RDWR | O_CREAT, 0600)))
1012 DEBUG(0, ("Unable to open Mangle TDB\n"));
1021 int dos_to_ucs2(const void *base_ptr, void *dest, const char *src, int dest_len, int flags)
1024 int src_len = strlen(src);
1027 /* treat a pstring as "unlimited" length */
1028 if (dest_len == -1) {
1029 dest_len = sizeof(pstring);
1032 if (flags & STR_UPPER) {
1033 pstrcpy(tmpbuf, src);
1038 if (flags & STR_TERMINATE) {
1042 if (ucs2_align(base_ptr, dest, flags)) {
1044 dest = (void *)((char *)dest + 1);
1045 if (dest_len) dest_len--;
1049 /* ucs2 is always a multiple of 2 bytes */
1052 len += convert_string(CH_DOS, CH_UCS2, src, src_len, dest, dest_len);
1057 int ucs2_to_dos(const void *base_ptr, char *dest, const void *src, int dest_len, int src_len, int flags)
1061 if (dest_len == -1) {
1062 dest_len = sizeof(pstring);
1065 if (ucs2_align(base_ptr, src, flags)) {
1066 src = (const void *)((char *)src + 1);
1067 if (src_len > 0) src_len--;
1070 if (flags & STR_TERMINATE) src_len = strlen_w(src)*2+2;
1072 /* ucs2 is always a multiple of 2 bytes */
1075 ret = convert_string(CH_UCS2, CH_DOS, src, src_len, dest, dest_len);
1076 if (dest_len) dest[MIN(ret, dest_len-1)] = 0;
1081 /* return False if something fail and
1082 * return 2 alloced unicode strings that contain prefix and extension
1084 static BOOL mangle_get_prefix(const smb_ucs2_t *ucs2_string, smb_ucs2_t **prefix, smb_ucs2_t **extension)
1090 *prefix = strdup_w(ucs2_string);
1093 DEBUG(0,("mangle_get_prefix: out of memory!\n"));
1096 str_len = strlen_w(*prefix);
1097 if (p = strrchr_wa(*prefix, '.'))
1099 /* TODO: check it is <4 in dos charset */
1100 if ((str_len - ((p - *prefix) / sizeof(smb_ucs2_t))) < 4) /* check extension */
1104 *extension = strdup_w(p);
1107 DEBUG(0,("mangle_get_prefix: out of memory!\n"));
1118 /* mangled must contain only the file name, not a path.
1119 and MUST be ZERO terminated */
1120 smb_ucs2_t *unmangle(const smb_ucs2_t *mangled)
1125 smb_ucs2_t *pref, *ext, *retstr;
1126 size_t long_len, ext_len;
1129 if (strlen_w(mangled) > 12) return NULL;
1130 if (!strchr_wa(mangled, '~')) return NULL;
1131 if (!init_mangle_tdb()) return NULL;
1133 ret = mangle_get_prefix(mangled, &pref, &ext);
1134 if (!ret) return NULL;
1136 /* TODO: get out extension */
1138 /* set search key */
1139 ucs2_to_dos(NULL, mufname, pref, sizeof(mufname), 0, STR_TERMINATE);
1141 slprintf(keystr, sizeof(keystr) - 1, "%s%s", MANGLED_PREFIX, mufname);
1143 key.dsize = strlen (keystr) + 1;
1145 /* get the record */
1146 data = tdb_fetch(global_mt_ent.mangle_tdb, key);
1148 if (!data.dptr) /* not found */
1150 DEBUG(5,("unmangle: failed retrieve from db %s\n", tdb_errorstr(global_mt_ent.mangle_tdb)));
1157 long_len = data.dsize / 2; /* terminator counted on purpose, will contain '.' */
1158 ext_len = strlen_w(ext);
1159 retstr = (smb_ucs2_t *)malloc((long_len + ext_len + 1)*sizeof(smb_ucs2_t));
1162 DEBUG(0, ("unamngle: out of memory!\n"));
1165 strncpy_w(retstr, (smb_ucs2_t *)data.dptr, long_len);
1166 retstr[long_len] = UCS2_CHAR('.');
1167 retstr[long_len + 1] = 0;
1168 strncat_w(retstr, ext, ext_len);
1172 retstr = strdup_w((smb_ucs2_t *)data.dptr);
1175 DEBUG(0, ("unamngle: out of memory!\n"));
1182 SAFE_FREE(data.dptr);
1189 /* unmangled must contain only the file name, not a path.
1190 and MUST be ZERO terminated */
1191 smb_ucs2_t *_mangle(const smb_ucs2_t *unmangled)
1193 TDB_DATA data, key, klock;
1199 BOOL tclock = False;
1200 char suffix[MANGLE_SUFFIX_SIZE + 1];
1201 smb_ucs2_t *mangled = NULL;
1202 smb_ucs2_t *um, *ext, *p = NULL;
1204 size_t pref_len, ext_len;
1208 if (!init_mangle_tdb()) return NULL;
1210 /* TODO: if it is a path return a failure ?? */
1211 if (!mangle_get_prefix(unmangled, &um, &ext)) return NULL;
1213 /* test if the same is yet mangled */
1215 /* set search key */
1216 pull_ucs2(NULL, longname, um, sizeof(longname), 0, STR_TERMINATE);
1217 slprintf(keystr, sizeof(keystr)-1, "%s%s", LONG_PREFIX, longname);
1219 key.dsize = strlen(keystr) + 1;
1221 /* get the record */
1222 data = tdb_fetch (global_mt_ent.mangle_tdb, key);
1223 if (!data.dptr) /* not found */
1225 if (tdb_error(global_mt_ent.mangle_tdb) != TDB_ERR_NOEXIST)
1227 DEBUG(0, ("mangle: database retrieval error: %s\n",
1228 tdb_errorstr(global_mt_ent.mangle_tdb)));
1232 /* if not find the first free possibile mangled name */
1238 pos = 8 - n - MANGLE_SUFFIX_SIZE;
1241 DEBUG(0, ("mangle: unable to mangle file name!\n"));
1244 strncpy_w(temp, um, pos);
1247 ucs2_to_dos(NULL, prefix, temp, sizeof(prefix), 0, STR_TERMINATE);
1249 while (strlen(prefix) > 8 - (MANGLE_SUFFIX_SIZE + 1));
1251 slprintf(keylock, sizeof(keylock)-1, "%s%s", COUNTER_PREFIX, prefix);
1252 klock.dptr = keylock;
1253 klock.dsize = strlen(keylock) + 1;
1256 data.dptr = (char *)&c;
1257 data.dsize = sizeof(uint32);
1258 /* try to insert a new counter prefix, if it exist the call will
1259 fail (correct) otherwise it will create a new entry with counter set
1262 tdb_store(global_mt_ent.mangle_tdb, klock, data, TDB_INSERT);
1264 /* lock the mangle counter for this prefix */
1265 if (!tdb_chainlock(global_mt_ent.mangle_tdb, klock))
1267 DEBUG(0,("mangle: failed to lock database\n!"));
1272 data = tdb_fetch(global_mt_ent.mangle_tdb, klock);
1275 DEBUG(0, ("mangle: database retrieval error: %s\n",
1276 tdb_errorstr(global_mt_ent.mangle_tdb)));
1279 c = *((uint32 *)data.dptr);
1282 temp[pos] = UCS2_CHAR('~');
1284 snprintf(suffix, MANGLE_SUFFIX_SIZE + 1, "%.6d", c);
1285 strncat_wa(temp, &suffix[6 - MANGLE_SUFFIX_SIZE], MANGLE_SUFFIX_SIZE + 1);
1287 ucs2_to_dos(NULL, mufname, temp, sizeof(mufname), 0, STR_TERMINATE);
1288 if (strlen(mufname) > 8)
1290 DEBUG(0, ("mangle: darn, logic error aborting!\n"));
1294 /* store the long entry with mangled key */
1295 slprintf(keystr, sizeof(keystr)-1, "%s%s", MANGLED_PREFIX, mufname);
1297 key.dsize = strlen (keystr) + 1;
1298 data.dsize = (strlen_w(um) + 1) * sizeof (smb_ucs2_t);
1299 data.dptr = (void *)um;
1301 if (tdb_store(global_mt_ent.mangle_tdb, key, data, TDB_INSERT) != TDB_SUCCESS)
1303 DEBUG(0, ("mangle: database store error: %s\n",
1304 tdb_errorstr(global_mt_ent.mangle_tdb)));
1308 /* store the mangled entry with long key*/
1309 pull_ucs2(NULL, longname, um, sizeof(longname), 0, STR_TERMINATE);
1310 slprintf(keystr, sizeof(keystr)-1, "%s%s", LONG_PREFIX, longname);
1312 key.dsize = strlen (keystr) + 1;
1313 data.dsize = strlen(mufname +1);
1314 data.dptr = mufname;
1315 if (tdb_store(global_mt_ent.mangle_tdb, key, data, TDB_INSERT) != TDB_SUCCESS)
1317 DEBUG(0, ("mangle: store failed: %s\n",
1318 tdb_errorstr(global_mt_ent.mangle_tdb)));
1320 /* try to delete the mangled key entry to avoid later inconsistency */
1321 slprintf(keystr, sizeof(keystr)-1, "%s%s", MANGLED_PREFIX, mufname);
1323 key.dsize = strlen (keystr) + 1;
1324 if (!tdb_delete(global_mt_ent.mangle_tdb, key))
1326 DEBUG(0, ("mangle: severe error, mangled tdb may be inconsistent!\n"));
1334 DEBUG(0,("mangle: out of memory!\n"));
1338 data.dptr = (char *)&c;
1339 data.dsize = sizeof(uint32);
1340 if(!tdb_store(global_mt_ent.mangle_tdb, klock, data, TDB_INSERT))
1342 DEBUG(0, ("mangle: store failed: %s\n",
1343 tdb_errorstr(global_mt_ent.mangle_tdb)));
1344 /* try to delete the mangled and long key entry to avoid later inconsistency */
1345 slprintf(keystr, sizeof(keystr)-1, "%s%s", MANGLED_PREFIX, mufname);
1347 key.dsize = strlen (keystr) + 1;
1348 if (!tdb_delete(global_mt_ent.mangle_tdb, key))
1350 DEBUG(0, ("mangle: severe error, mangled tdb may be inconsistent!\n"));
1352 slprintf(keystr, sizeof(keystr)-1, "%s%s", LONG_PREFIX, longname);
1354 key.dsize = strlen (keystr) + 1;
1355 if (!tdb_delete(global_mt_ent.mangle_tdb, key))
1357 DEBUG(0, ("mangle: severe error, mangled tdb may be inconsistent!\n"));
1363 tdb_chainunlock(global_mt_ent.mangle_tdb, klock);
1367 p = (smb_ucs2_t *)malloc(data.dsize*sizeof(smb_ucs2_t));
1370 DEBUG(0,("mangle: out of memory!\n"));
1373 dos_to_ucs2(NULL, p, data.dptr, data.dsize*sizeof(smb_ucs2_t), STR_TERMINATE);
1378 pref_len = strlen_w(p) + 1; /* terminator counted on purpose, will contain '.' */
1379 ext_len = strlen_w(ext);
1380 mangled = (smb_ucs2_t *)malloc((pref_len + ext_len + 1)*sizeof(smb_ucs2_t));
1383 DEBUG(0,("mangle: out of memory!\n"));
1386 strncpy_w (mangled, p, pref_len);
1387 mangled[pref_len] = UCS2_CHAR('.');
1388 mangled[pref_len + 1] = 0;
1389 strncat_w (mangled, ext, ext_len);
1393 mangled = strdup_w(p);
1396 DEBUG(0,("mangle: out of memory!\n"));
1402 if (tclock) tdb_chainunlock(global_mt_ent.mangle_tdb, klock);
1412 #ifdef TEST_MANGLE_CODE
1414 #define LONG "this_is_a_long_file_name"
1415 #define LONGM "this_~01"
1416 #define SHORT "short"
1417 #define SHORTM "short~01"
1421 #define EXTFAIL "longext"
1423 static void unmangle_test (char *name, char *ext)
1425 smb_ucs2_t ucs2_name[2048];
1429 push_ucs2(NULL, ucs2_name, name, sizeof(ucs2_name), STR_TERMINATE);
1432 strncat_wa(ucs2_name, ".", 1);
1433 strncat_wa(ucs2_name, ext, strlen(ext));
1435 retstr = unmangle(ucs2_name);
1436 if(retstr) pull_ucs2(NULL, unix_name, retstr, sizeof(unix_name), 0, STR_TERMINATE);
1437 else unix_name[0] = 0;
1438 if (ext) printf ("[%s.%s] ---> [%s]\n", name, ext, unix_name);
1439 else printf ("[%s] ---> [%s]\n", name, unix_name);
1443 static void mangle_test (char *name, char *ext)
1445 smb_ucs2_t ucs2_name[2048];
1449 push_ucs2(NULL, ucs2_name, name, sizeof(ucs2_name), STR_TERMINATE);
1452 strncat_wa(ucs2_name, ".", 1);
1453 strncat_wa(ucs2_name, ext, strlen(ext));
1455 retstr = _mangle(ucs2_name);
1456 if(retstr) pull_ucs2(NULL, unix_name, retstr, sizeof(unix_name), 0, STR_TERMINATE);
1457 else unix_name[0] = 0;
1458 if (ext) printf ("[%s.%s] ---> [%s]\n", name, ext, unix_name);
1459 else printf ("[%s] ---> [%s]\n", name, unix_name);
1463 void mangle_test_code(void)
1465 /* unmangle every */
1466 unmangle_test (LONG, NULL);
1467 unmangle_test (LONG, EXT1);
1468 unmangle_test (LONG, EXT2);
1469 unmangle_test (LONG, EXT3);
1470 unmangle_test (LONG, EXTFAIL);
1472 unmangle_test (LONGM, NULL);
1473 unmangle_test (LONGM, EXT1);
1474 unmangle_test (LONGM, EXT2);
1475 unmangle_test (LONGM, EXT3);
1476 unmangle_test (LONGM, EXTFAIL);
1478 unmangle_test (SHORT, NULL);
1479 unmangle_test (SHORT, EXT1);
1480 unmangle_test (SHORT, EXT2);
1481 unmangle_test (SHORT, EXT3);
1482 unmangle_test (SHORT, EXTFAIL);
1484 unmangle_test (SHORTM, NULL);
1485 unmangle_test (SHORTM, EXT1);
1486 unmangle_test (SHORTM, EXT2);
1487 unmangle_test (SHORTM, EXT3);
1488 unmangle_test (SHORTM, EXTFAIL);
1491 mangle_test (LONG, NULL);
1492 mangle_test (LONG, EXT1);
1493 mangle_test (LONG, EXT2);
1494 mangle_test (LONG, EXT3);
1495 mangle_test (LONG, EXTFAIL);
1497 mangle_test (LONGM, NULL);
1498 mangle_test (LONGM, EXT1);
1499 mangle_test (LONGM, EXT2);
1500 mangle_test (LONGM, EXT3);
1501 mangle_test (LONGM, EXTFAIL);
1503 mangle_test (SHORT, NULL);
1504 mangle_test (SHORT, EXT1);
1505 mangle_test (SHORT, EXT2);
1506 mangle_test (SHORT, EXT3);
1507 mangle_test (SHORT, EXTFAIL);
1509 mangle_test (SHORTM, NULL);
1510 mangle_test (SHORTM, EXT1);
1511 mangle_test (SHORTM, EXT2);
1512 mangle_test (SHORTM, EXT3);
1513 mangle_test (SHORTM, EXTFAIL);
1515 /* unmangle again every */
1516 unmangle_test (LONG, NULL);
1517 unmangle_test (LONG, EXT1);
1518 unmangle_test (LONG, EXT2);
1519 unmangle_test (LONG, EXT3);
1520 unmangle_test (LONG, EXTFAIL);
1522 unmangle_test (LONGM, NULL);
1523 unmangle_test (LONGM, EXT1);
1524 unmangle_test (LONGM, EXT2);
1525 unmangle_test (LONGM, EXT3);
1526 unmangle_test (LONGM, EXTFAIL);
1528 unmangle_test (SHORT, NULL);
1529 unmangle_test (SHORT, EXT1);
1530 unmangle_test (SHORT, EXT2);
1531 unmangle_test (SHORT, EXT3);
1532 unmangle_test (SHORT, EXTFAIL);
1534 unmangle_test (SHORTM, NULL);
1535 unmangle_test (SHORTM, EXT1);
1536 unmangle_test (SHORTM, EXT2);
1537 unmangle_test (SHORTM, EXT3);
1538 unmangle_test (SHORTM, EXTFAIL);
1541 #endif /* TEST_MANGLE_CODE */