This split the mangling code up to allow for the possibility of multiple
authorAndrew Tridgell <tridge@samba.org>
Thu, 11 Apr 2002 02:20:56 +0000 (02:20 +0000)
committerAndrew Tridgell <tridge@samba.org>
Thu, 11 Apr 2002 02:20:56 +0000 (02:20 +0000)
mangling implementation, selectable using "mangling method = " in smb.conf

It also tidies the interface a little, although it is still nasty.

14 files changed:
source/Makefile.in
source/include/includes.h
source/include/local.h
source/include/mangle.h [new file with mode: 0644]
source/param/loadparm.c
source/smbd/dir.c
source/smbd/filename.c
source/smbd/mangle.c
source/smbd/mangle_hash.c [new file with mode: 0644]
source/smbd/mangle_map.c [new file with mode: 0644]
source/smbd/oplock.c
source/smbd/reply.c
source/smbd/server.c
source/smbd/trans2.c

index 24e3fe29f9352c6cf7f727eadb9f1da350acc9f4..c5982d8edd9419487f7c42b5349d4a299aeb81f7 100644 (file)
@@ -212,11 +212,12 @@ AUTH_OBJ = auth/auth.o auth/auth_sam.o auth/auth_server.o auth/auth_domain.o \
           auth/auth_rhosts.o auth/auth_unix.o auth/auth_util.o auth/auth_winbind.o \
           auth/auth_builtin.o auth/auth_compat.o $(PLAINTEXT_AUTH_OBJ) $(UNIGRP_OBJ)
 
+MANGLE_OBJ = smbd/mangle.o smbd/mangle_hash.o smbd/mangle_map.o
 
 SMBD_OBJ1 = smbd/server.o smbd/files.o smbd/chgpasswd.o smbd/connection.o \
            smbd/utmp.o smbd/session.o \
             smbd/dfree.o smbd/dir.o smbd/password.o smbd/conn.o smbd/fileio.o \
-            smbd/ipc.o smbd/lanman.o smbd/mangle.o smbd/negprot.o \
+            smbd/ipc.o smbd/lanman.o smbd/negprot.o \
             smbd/message.o smbd/nttrans.o smbd/pipes.o \
             smbd/reply.o smbd/sesssetup.o smbd/trans2.o smbd/uid.o \
            smbd/dosmode.o smbd/filename.o smbd/open.o smbd/close.o \
@@ -227,13 +228,14 @@ SMBD_OBJ1 = smbd/server.o smbd/files.o smbd/chgpasswd.o smbd/connection.o \
            printing/printfsp.o lib/util_seaccess.o smbd/srvstr.o \
             smbd/build_options.o \
            smbd/change_trust_pw.o \
-           rpc_client/cli_spoolss_notify.o
+           rpc_client/cli_spoolss_notify.o \
+           $(MANGLE_OBJ)
 
 
 PRINTING_OBJ = printing/pcap.o printing/print_svid.o \
                                printing/print_cups.o printing/print_generic.o \
                                printing/lpq_parse.o printing/load.o
+
 PRINTBACKEND_OBJ = printing/printing.o printing/nt_printing.o
 
 MSDFS_OBJ = msdfs/msdfs.o 
index e19961b57578ae625607c0b283d679b9f2a9437f..5da1c1d9972a7353261680ac9c117ef18d039c8a 100644 (file)
@@ -746,6 +746,8 @@ extern int errno;
 
 #include "popt.h"
 
+#include "mangle.h"
+
 #ifndef MAXCODEPAGELINES
 #define MAXCODEPAGELINES 256
 #endif
index c7abe207c8938dc01cb1b05d3ded2b66896059a3..1ecd63738ecfdbeeb617fa80da5e5db186e04e8c 100644 (file)
 /* Allocation roundup. */
 #define SMB_ROUNDUP_ALLOCATION_SIZE 0x100000
 
+/* shall we deny oplocks to clients that get timeouts? */
+#define FASCIST_OPLOCK_BACKOFF 1
+
+/* this enables the "rabbit pellet" fix for SMBwritebraw */
+#define RABBIT_PELLET_FIX 1
+
 #endif
diff --git a/source/include/mangle.h b/source/include/mangle.h
new file mode 100644 (file)
index 0000000..d321851
--- /dev/null
@@ -0,0 +1,11 @@
+/*
+  header for 8.3 name mangling interface 
+*/
+
+struct mangle_fns {
+       BOOL (*is_mangled)(const char *s);
+       BOOL (*is_8_3)(const char *fname, BOOL check_case);
+       void (*reset)(void);
+       BOOL (*check_cache)(char *s);
+       BOOL (*name_map)(char *OutName, BOOL need83, BOOL cache83);
+};
index 11c8f2c44b9b1a5ccd50d964c765e8524f07b443..bdd710f5fec72143a5ece892059e8342b245a5d4 100644 (file)
@@ -161,6 +161,7 @@ typedef struct
        char *szChangeShareCommand;
        char *szDeleteShareCommand;
        char *szGuestaccount;
+       char *szManglingMethod;
        int max_log_size;
        int mangled_stack;
        int max_xmit;
@@ -911,6 +912,7 @@ static struct parm_struct parm_table[] = {
 
        {"Filename Handling", P_SEP, P_SEPARATOR},
        {"strip dot", P_BOOL, P_GLOBAL, &Globals.bStripDot, NULL, NULL, 0},
+       {"mangling method", P_STRING, P_GLOBAL, &Globals.szManglingMethod, NULL, NULL, 0},
        
        {"mangled stack", P_INTEGER, P_GLOBAL, &Globals.mangled_stack, NULL, NULL, 0},
        {"default case", P_ENUM, P_LOCAL, &sDefault.iDefaultCase, NULL, enum_case, FLAG_SHARE},
@@ -1519,6 +1521,7 @@ FN_GLOBAL_STRING(lp_addprinter_cmd, &Globals.szAddPrinterCommand)
 FN_GLOBAL_STRING(lp_deleteprinter_cmd, &Globals.szDeletePrinterCommand)
 FN_GLOBAL_STRING(lp_os2_driver_map, &Globals.szOs2DriverMap)
 FN_GLOBAL_STRING(lp_lockdir, &Globals.szLockDir)
+FN_GLOBAL_STRING(lp_mangling_method, &Globals.szManglingMethod)
 #ifdef WITH_UTMP
 FN_GLOBAL_STRING(lp_utmpdir, &Globals.szUtmpDir)
 FN_GLOBAL_STRING(lp_wtmpdir, &Globals.szWtmpDir)
index 0bf234dd3e01e9a3a3df1010157172356f3dd920..f56e0e9ef00a000df96c0cad0a1c2aaff0be9ae4 100644 (file)
@@ -603,14 +603,14 @@ BOOL get_dir_entry(connection_struct *conn,char *mask,int dirtype,char *fname,
     */
     if ((strcmp(mask,"*.*") == 0) ||
        mask_match(filename,mask,False) ||
-        (name_map_mangle(filename,True,False,SNUM(conn)) &&
+        (mangle_map(filename,True,False,SNUM(conn)) &&
          mask_match(filename,mask,False)))
     {
       if (isrootdir && (strequal(filename,"..") || strequal(filename,".")))
         continue;
 
-      if (!is_8_3(filename, False)) {
-             name_map_mangle(filename,True,False,SNUM(conn));
+      if (!mangle_is_8_3(filename, False)) {
+             mangle_map(filename,True,False,SNUM(conn));
       }
 
       pstrcpy(fname,filename);
index 8bd09691e4f994c07a39b6c2146b5240f7683db0..cb6a6d31a40191676e3d57798435d6da79df237e 100644 (file)
@@ -73,32 +73,16 @@ static BOOL fname_equal(char *name1, char *name2)
 /****************************************************************************
  Mangle the 2nd name and check if it is then equal to the first name.
 ****************************************************************************/
-static BOOL mangled_equal(char *name1, char *name2)
+static BOOL mangled_equal(char *name1, char *name2, int snum)
 {
-#if 1
        pstring tmpname;
-       if (is_8_3(name2, True)) {
+       if (mangle_is_8_3(name2, True)) {
                return False;
        }
        
        pstrcpy(tmpname, name2);
-       mangle_name_83(tmpname);
-
-       return strequal(name1, tmpname);
-#else  
-       char *tmpname;
-       BOOL ret = False;
-
-       if (is_8_3(name2, True))
-       {
-               tmpname = dos_mangle(name2);
-               if(tmpname)
-                       ret = strequal(name1,tmpname);
-               SAFE_FREE(tmpname);
-       }
-       return ret;
-#endif
-       
+       return mangle_map(tmpname, True, False, snum) && 
+               strequal(name1, tmpname);
 }
 
 
@@ -193,7 +177,7 @@ BOOL unix_convert(pstring name,connection_struct *conn,char *saved_last_componen
   }
 
   if (!case_sensitive && 
-      (!case_preserve || (is_8_3(name, False) && !short_case_preserve)))
+      (!case_preserve || (mangle_is_8_3(name, False) && !short_case_preserve)))
     strnorm(name);
 
   /*
@@ -220,7 +204,7 @@ BOOL unix_convert(pstring name,connection_struct *conn,char *saved_last_componen
    * stat the name - if it exists then we are all done!
    */
 
-  if (vfs_stat(conn,name,&st) == 0) {
+/* ZZZ: stat1 */  if (vfs_stat(conn,name,&st) == 0) {
     stat_cache_add(orig_path, name);
     DEBUG(5,("conversion finished %s -> %s\n",orig_path, name));
     *pst = st;
@@ -235,7 +219,7 @@ BOOL unix_convert(pstring name,connection_struct *conn,char *saved_last_componen
    * sensitive then searching won't help.
    */
 
-  if (case_sensitive && !is_mangled(name) && 
+  if (case_sensitive && !mangle_is_mangled(name) && 
       !lp_strip_dot() && !use_mangled_map)
     return(False);
 
@@ -246,7 +230,7 @@ BOOL unix_convert(pstring name,connection_struct *conn,char *saved_last_componen
    * just a component. JRA.
    */
 
-  if(is_mangled(start))
+  if (mangle_is_mangled(start))
     component_was_mangled = True;
 
   /* 
@@ -346,8 +330,8 @@ BOOL unix_convert(pstring name,connection_struct *conn,char *saved_last_componen
            * base of the filename.
            */
 
-          if (is_mangled(start)) {
-            check_mangled_cache( start );
+          if (mangle_is_mangled(start)) {
+                 mangle_check_cache( start );
           }
 
           DEBUG(5,("New file %s\n",start));
@@ -468,7 +452,7 @@ static BOOL scan_directory(char *path, char *name,connection_struct *conn,BOOL d
   BOOL mangled;
   pstring name2;
 
-  mangled = is_mangled(name);
+  mangled = mangle_is_mangled(name);
 
   /* handle null paths */
   if (*path == 0)
@@ -482,12 +466,12 @@ static BOOL scan_directory(char *path, char *name,connection_struct *conn,BOOL d
   /*
    * The incoming name can be mangled, and if we de-mangle it
    * here it will not compare correctly against the filename (name2)
-   * read from the directory and then mangled by the name_map_mangle()
+   * read from the directory and then mangled by the mangle_map()
    * call. We need to mangle both names or neither.
    * (JRA).
    */
   if (mangled)
-    mangled = !check_mangled_cache( name );
+    mangled = !mangle_check_cache( name );
 
   /* open the directory */
   if (!(cur_dir = OpenDir(conn, path, True))) {
@@ -501,10 +485,10 @@ static BOOL scan_directory(char *path, char *name,connection_struct *conn,BOOL d
         continue;
 
       pstrcpy(name2,dname);
-      if (!name_map_mangle(name2,False,True,SNUM(conn)))
+      if (!mangle_map(name2,False,True,SNUM(conn)))
         continue;
 
-      if ((mangled && mangled_equal(name,name2)) || fname_equal(name, dname)) {
+      if ((mangled && mangled_equal(name,name2,SNUM(conn))) || fname_equal(name, dname)) {
         /* we've found the file, change it's name and return */
         if (docache)
           DirCacheAdd(path,name,dname,SNUM(conn));
index e50537e4cb590e98aed9716d7221db551b1b6d39..9d0641d5c80f189bdc4d157195fcf5bff6c0fca2 100644 (file)
@@ -1,9 +1,7 @@
 /* 
    Unix SMB/CIFS implementation.
-   Name mangling
-   Copyright (C) Andrew Tridgell 1992-1998
-   Copyright (C) Simo Sorce 2001
-   Copyright (C) Andrew Bartlett 2002
+   Name mangling interface
+   Copyright (C) Andrew Tridgell 2002
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
 
-/* -------------------------------------------------------------------------- **
- * Notable problems...
- *
- *  March/April 1998  CRH
- *  - Many of the functions in this module overwrite string buffers passed to
- *    them.  This causes a variety of problems and is, generally speaking,
- *    dangerous and scarry.  See the kludge notes in name_map_mangle()
- *    below.
- *  - It seems that something is calling name_map_mangle() twice.  The
- *    first call is probably some sort of test.  Names which contain
- *    illegal characters are being doubly mangled.  I'm not sure, but
- *    I'm guessing the problem is in server.c.
- *
- * -------------------------------------------------------------------------- **
- */
-
-/* -------------------------------------------------------------------------- **
- * History...
- *
- *  March/April 1998  CRH
- *  Updated a bit.  Rewrote is_mangled() to be a bit more selective.
- *  Rewrote the mangled name cache.  Added comments here and there.
- *  &c.
- * -------------------------------------------------------------------------- **
- */
-
 #include "includes.h"
 
+static struct mangle_fns *mangle_fns;
 
-/* -------------------------------------------------------------------------- **
- * External Variables...
- */
-
-extern int case_default;    /* Are conforming 8.3 names all upper or lower?   */
-extern BOOL case_mangle;    /* If true, all chars in 8.3 should be same case. */
-
-/* -------------------------------------------------------------------------- **
- * Other stuff...
- *
- * magic_char     - This is the magic char used for mangling.  It's
- *                  global.  There is a call to lp_magicchar() in server.c
- *                  that is used to override the initial value.
- *
- * MANGLE_BASE    - This is the number of characters we use for name mangling.
- *
- * basechars      - The set characters used for name mangling.  This
- *                  is static (scope is this file only).
- *
- * mangle()       - Macro used to select a character from basechars (i.e.,
- *                  mangle(n) will return the nth digit, modulo MANGLE_BASE).
- *
- * chartest       - array 0..255.  The index range is the set of all possible
- *                  values of a byte.  For each byte value, the content is a
- *                  two nibble pair.  See BASECHAR_MASK and ILLEGAL_MASK,
- *                  below.
- *
- * ct_initialized - False until the chartest array has been initialized via
- *                  a call to init_chartest().
- *
- * BASECHAR_MASK  - Masks the upper nibble of a one-byte value.
- *
- * ILLEGAL_MASK   - Masks the lower nibble of a one-byte value.
- *
- * isbasecahr()   - Given a character, check the chartest array to see
- *                  if that character is in the basechars set.  This is
- *                  faster than using strchr_m().
- *
- * isillegal()    - Given a character, check the chartest array to see
- *                  if that character is in the illegal characters set.
- *                  This is faster than using strchr_m().
- *
- * mangled_cache  - Cache header used for storing mangled -> original
- *                  reverse maps.
- *
- * mc_initialized - False until the mangled_cache structure has been
- *                  initialized via a call to reset_mangled_cache().
- *
- * MANGLED_CACHE_MAX_ENTRIES - Default maximum number of entries for the
- *                  cache.  A value of 0 indicates "infinite".
- *
- * MANGLED_CACHE_MAX_MEMORY  - Default maximum amount of memory for the
- *                  cache.  When the cache was kept as an array of 256
- *                  byte strings, the default cache size was 50 entries.
- *                  This required a fixed 12.5Kbytes of memory.  The
- *                  mangled stack parameter is no longer used (though
- *                  this might change).  We're now using a fixed 16Kbyte
- *                  maximum cache size.  This will probably be much more
- *                  than 50 entries.
- */
-
-char magic_char = '~';
-
-static char basechars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_-!@#$%";
-#define MANGLE_BASE       (sizeof(basechars)/sizeof(char)-1)
-
-static unsigned char chartest[256]  = { 0 };
-static BOOL          ct_initialized = False;
-
-#define mangle(V) ((char)(basechars[(V) % MANGLE_BASE]))
-#define BASECHAR_MASK 0xf0
-#define ILLEGAL_MASK  0x0f
-#define isbasechar(C) ( (chartest[ ((C) & 0xff) ]) & BASECHAR_MASK )
-#define isillegal(C) ( (chartest[ ((C) & 0xff) ]) & ILLEGAL_MASK )
-
-static ubi_cacheRoot mangled_cache[1] =  { { { 0, 0, 0, 0 }, 0, 0, 0, 0, 0, 0 } };
-static BOOL          mc_initialized   = False;
-#define MANGLED_CACHE_MAX_ENTRIES 0
-#define MANGLED_CACHE_MAX_MEMORY  16384
-
-
-/* -------------------------------------------------------------------------- **
- * External Variables...
- */
-
-extern int case_default;    /* Are conforming 8.3 names all upper or lower?   */
-extern BOOL case_mangle;    /* If true, all chars in 8.3 should be same case. */
-
-/* -------------------------------------------------------------------- */
+/* this allows us to add more mangling backends */
+static struct {
+       char *name;
+       struct mangle_fns *(*init_fn)(void);
+} mangle_backends[] = {
+       { "hash", mangle_hash_init },
+       { NULL, NULL }
+};
 
-NTSTATUS has_valid_chars(const smb_ucs2_t *s)
+/*
+  initialise the mangling subsystem
+*/
+static void mangle_init(void)
 {
-       if (!s || !*s) return NT_STATUS_INVALID_PARAMETER;
+       int i;
+       char *method;
 
-       DEBUG(10,("has_valid_chars: testing\n")); /* [%s]\n", s)); */
-       
-       /* CHECK: this should not be necessary if the ms wild chars
-          are not valid in valid.dat  --- simo */
-       if (ms_has_wild_w(s)) return NT_STATUS_UNSUCCESSFUL;
+       if (mangle_fns) return;
 
-       while (*s) {
-               if(!isvalid83_w(*s)) return NT_STATUS_UNSUCCESSFUL;
-               s++;
-       }
-
-       return NT_STATUS_OK;
-}
+       method = lp_mangling_method();
 
-/* return False if something fail and
- * return 2 alloced unicode strings that contain prefix and extension
- */
-static NTSTATUS mangle_get_prefix(const smb_ucs2_t *ucs2_string, smb_ucs2_t **prefix, smb_ucs2_t **extension)
-{
-       size_t ext_len;
-       smb_ucs2_t *p;
-
-       *extension = 0;
-       *prefix = strdup_w(ucs2_string);
-       if (!*prefix)
-       {
-               DEBUG(0,("mangle_get_prefix: out of memory!\n"));
-               return NT_STATUS_NO_MEMORY;
-       }
-       if ((p = strrchr_w(*prefix, UCS2_CHAR('.'))))
-       {
-               ext_len = strlen_w(p+1);
-               if ((ext_len > 0) && (ext_len < 4) && (p != *prefix) &&
-                   (NT_STATUS_IS_OK(has_valid_chars(p+1)))) /* check extension */
-               {
-                       *p = 0;
-                       *extension = strdup_w(p+1);
-                       if (!*extension)
-                       {
-                               DEBUG(0,("mangle_get_prefix: out of memory!\n"));
-                               SAFE_FREE(*prefix);
-                               return NT_STATUS_NO_MEMORY;
-                       }
+       /* find the first mangling method that manages to initialise and 
+          matches the "mangling method" parameter */
+       for (i=0; mangle_backends[i].name && !mangle_fns; i++) {
+               if (!method || !*method || strcmp(method, mangle_backends[i].name) == 0) {
+                       mangle_fns = mangle_backends[i].init_fn();
                }
        }
-       return NT_STATUS_OK;
-}
-
-/* ************************************************************************** **
- * Return NT_STATUS_UNSUCCESSFUL if a name is a special msdos reserved name.
- *
- *  Input:  fname - String containing the name to be tested.
- *
- *  Output: NT_STATUS_UNSUCCESSFUL, if the name matches one of the list of reserved names.
- *
- *  Notes:  This is a static function called by is_8_3(), below.
- *
- * ************************************************************************** **
- */
-static NTSTATUS is_valid_name(const smb_ucs2_t *fname)
-{
-       smb_ucs2_t *str, *p;
-       NTSTATUS ret = NT_STATUS_OK;
-
-       if (!fname || !*fname) return NT_STATUS_INVALID_PARAMETER;
-
-       DEBUG(10,("is_valid_name: testing\n")); /* [%s]\n", s)); */
-
-       if (*fname == UCS2_CHAR('.')) return NT_STATUS_UNSUCCESSFUL;
-       
-       ret = has_valid_chars(fname);
-       if (NT_STATUS_IS_ERR(ret)) return ret;
-
-       str = strdup_w(fname);
-       p = strchr_w(str, UCS2_CHAR('.'));
-       if (p) *p = 0;
-       strupper_w(str);
-       p = &(str[1]);
 
-       switch(str[0])
-       {
-       case UCS2_CHAR('A'):
-               if(strcmp_wa(p, "UX") == 0)
-                       ret = NT_STATUS_UNSUCCESSFUL;
-               break;
-       case UCS2_CHAR('C'):
-               if((strcmp_wa(p, "LOCK$") == 0)
-               || (strcmp_wa(p, "ON") == 0)
-               || (strcmp_wa(p, "OM1") == 0)
-               || (strcmp_wa(p, "OM2") == 0)
-               || (strcmp_wa(p, "OM3") == 0)
-               || (strcmp_wa(p, "OM4") == 0)
-               )
-                       ret = NT_STATUS_UNSUCCESSFUL;
-               break;
-       case UCS2_CHAR('L'):
-               if((strcmp_wa(p, "PT1") == 0)
-               || (strcmp_wa(p, "PT2") == 0)
-               || (strcmp_wa(p, "PT3") == 0)
-               )
-                       ret = NT_STATUS_UNSUCCESSFUL;
-               break;
-       case UCS2_CHAR('N'):
-               if(strcmp_wa(p, "UL") == 0)
-                       ret = NT_STATUS_UNSUCCESSFUL;
-               break;
-       case UCS2_CHAR('P'):
-               if(strcmp_wa(p, "RN") == 0)
-                       ret = NT_STATUS_UNSUCCESSFUL;
-               break;
-       default:
-               break;
+       if (!mangle_fns) {
+               DEBUG(0,("Failed to initialise mangling system '%s'\n", method));
+               exit_server("mangling init failed");
        }
-
-       SAFE_FREE(str);
-       return ret;
 }
 
-static NTSTATUS is_8_3_w(const smb_ucs2_t *fname)
-{
-       smb_ucs2_t *pref = 0, *ext = 0;
-       size_t plen;
-       NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
-
-       if (!fname || !*fname) return NT_STATUS_INVALID_PARAMETER;
-
-       DEBUG(10,("is_8_3_w: testing\n")); /* [%s]\n", fname)); */
-
-       if (strlen_w(fname) > 12) return NT_STATUS_UNSUCCESSFUL;
-       
-       if (strcmp_wa(fname, ".") == 0 || strcmp_wa(fname, "..") == 0)
-               return NT_STATUS_OK;
 
-       if (NT_STATUS_IS_ERR(is_valid_name(fname))) goto done;
-
-       if (NT_STATUS_IS_ERR(mangle_get_prefix(fname, &pref, &ext))) goto done;
-       plen = strlen_w(pref);
-
-       if (strchr_wa(pref, '.')) goto done;
-       if (plen < 1 || plen > 8) goto done;
-       if (ext) if (strlen_w(ext) > 3) goto done;
-
-       ret = NT_STATUS_OK;
+/*
+  reset the cache. This is called when smb.conf has been reloaded
+*/
+void mangle_reset_cache(void)
+{
+       mangle_init();
 
-done:
-       SAFE_FREE(pref);
-       SAFE_FREE(ext);
-       return ret;
+       return mangle_fns->reset();
 }
 
-BOOL is_8_3(const char *fname, BOOL check_case)
+/*
+  see if a filename has come out of our mangling code
+*/
+BOOL mangle_is_mangled(const char *s)
 {
-       const char *f;
-       smb_ucs2_t *ucs2name;
-       NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
-
-       if (!fname || !*fname) return False;
-       if ((f = strrchr(fname, '/')) == NULL) f = fname;
-       else f++;
-
-       DEBUG(10,("is_8_3: testing [%s]\n", f));
-
-       if (strlen(f) > 12) return False;
-       
-       ucs2name = acnv_uxu2(f);
-       if (!ucs2name)
-       {
-               DEBUG(0,("is_8_3: internal error acnv_uxu2() failed!\n"));
-               goto done;
-       }
-
-       ret = is_8_3_w(ucs2name);
-
-done:
-       SAFE_FREE(ucs2name);
-
-       DEBUG(10,("is_8_3: returning -> %s\n", NT_STATUS_IS_OK(ret)?"True":"False"));
-
-       if (!NT_STATUS_IS_OK(ret)) { 
-               return False;
-       }
-       
-       return True;
+       return mangle_fns->is_mangled(s);
 }
 
-
-
-/* -------------------------------------------------------------------------- **
- * Functions...
- */
-
-/* ************************************************************************** **
- * Initialize the static character test array.
- *
- *  Input:  none
- *
- *  Output: none
- *
- *  Notes:  This function changes (loads) the contents of the <chartest>
- *          array.  The scope of <chartest> is this file.
- *
- * ************************************************************************** **
- */
-static void init_chartest( void )
-  {
-  char          *illegalchars = "*\\/?<>|\":";
-  unsigned char *s;
-  
-  memset( (char *)chartest, '\0', 256 );
-
-  for( s = (unsigned char *)illegalchars; *s; s++ )
-    chartest[*s] = ILLEGAL_MASK;
-
-  for( s = (unsigned char *)basechars; *s; s++ )
-    chartest[*s] |= BASECHAR_MASK;
-
-  ct_initialized = True;
-  } /* init_chartest */
-
-
-/* ************************************************************************** **
- * Return True if the name *could be* a mangled name.
- *
- *  Input:  s - A path name - in UNIX pathname format.
- *
- *  Output: True if the name matches the pattern described below in the
- *          notes, else False.
- *
- *  Notes:  The input name is *not* tested for 8.3 compliance.  This must be
- *          done separately.  This function returns true if the name contains
- *          a magic character followed by excactly two characters from the
- *          basechars list (above), which in turn are followed either by the
- *          nul (end of string) byte or a dot (extension) or by a '/' (end of
- *          a directory name).
- *
- * ************************************************************************** **
- */
-BOOL is_mangled( char *s )
-  {
-  char *magic;
-
-  if( !ct_initialized )
-    init_chartest();
-
-  magic = strchr_m( s, magic_char );
-  while( magic && magic[1] && magic[2] )          /* 3 chars, 1st is magic. */
-    {
-    if( ('.' == magic[3] || '/' == magic[3] || !(magic[3]))          /* Ends with '.' or nul or '/' ?  */
-     && isbasechar( toupper(magic[1]) )           /* is 2nd char basechar?  */
-     && isbasechar( toupper(magic[2]) ) )         /* is 3rd char basechar?  */
-      return( True );                           /* If all above, then true, */
-    magic = strchr_m( magic+1, magic_char );      /*    else seek next magic. */
-    }
-  return( False );
-  } /* is_mangled */
-
-
-/* ************************************************************************** **
- * Compare two cache keys and return a value indicating their ordinal
- * relationship.
- *
- *  Input:  ItemPtr - Pointer to a comparison key.  In this case, this will
- *                    be a mangled name string.
- *          NodePtr - Pointer to a node in the cache.  The node structure
- *                    will be followed in memory by a mangled name string.
- *
- *  Output: A signed integer, as follows:
- *            (x < 0)  <==> Key1 less than Key2
- *            (x == 0) <==> Key1 equals Key2
- *            (x > 0)  <==> Key1 greater than Key2
- *
- *  Notes:  This is a ubiqx-style comparison routine.  See ubi_BinTree for
- *          more info.
- *
- * ************************************************************************** **
- */
-static signed int cache_compare( ubi_btItemPtr ItemPtr, ubi_btNodePtr NodePtr )
-  {
-  char *Key1 = (char *)ItemPtr;
-  char *Key2 = (char *)(((ubi_cacheEntryPtr)NodePtr) + 1);
-
-  return( StrCaseCmp( Key1, Key2 ) );
-  } /* cache_compare */
-
-/* ************************************************************************** **
- * Free a cache entry.
- *
- *  Input:  WarrenZevon - Pointer to the entry that is to be returned to
- *                        Nirvana.
- *  Output: none.
- *
- *  Notes:  This function gets around the possibility that the standard
- *          free() function may be implemented as a macro, or other evil
- *          subversions (oh, so much fun).
- *
- * ************************************************************************** **
- */
-static void cache_free_entry( ubi_trNodePtr WarrenZevon )
-  {
-         ZERO_STRUCTP(WarrenZevon);
-         SAFE_FREE( WarrenZevon );
-  } /* cache_free_entry */
-
-/* ************************************************************************** **
- * Initializes or clears the mangled cache.
- *
- *  Input:  none.
- *  Output: none.
- *
- *  Notes:  There is a section below that is commented out.  It shows how
- *          one might use lp_ calls to set the maximum memory and entry size
- *          of the cache.  You might also want to remove the constants used
- *          in ubi_cacheInit() and replace them with lp_ calls.  If so, then
- *          the calls to ubi_cacheSetMax*() would be moved into the else
- *          clause.  Another option would be to pass in the max_entries and
- *          max_memory values as parameters.  crh 09-Apr-1998.
- *
- * ************************************************************************** **
- */
-void reset_mangled_cache( void )
-  {
-  if( !mc_initialized )
-    {
-    (void)ubi_cacheInit( mangled_cache,
-                         cache_compare,
-                         cache_free_entry,
-                         MANGLED_CACHE_MAX_ENTRIES,
-                         MANGLED_CACHE_MAX_MEMORY );
-    mc_initialized = True;
-    }
-  else
-    {
-    (void)ubi_cacheClear( mangled_cache );
-    }
-
-  /*
-  (void)ubi_cacheSetMaxEntries( mangled_cache, lp_mangled_cache_entries() );
-  (void)ubi_cacheSetMaxMemory(  mangled_cache, lp_mangled_cache_memory() );
-  */
-  } /* reset_mangled_cache  */
-
-
-/* ************************************************************************** **
- * Add a mangled name into the cache.
- *
- *  Notes:  If the mangled cache has not been initialized, then the
- *          function will simply fail.  It could initialize the cache,
- *          but that's not the way it was done before I changed the
- *          cache mechanism, so I'm sticking with the old method.
- *
- *          If the extension of the raw name maps directly to the
- *          extension of the mangled name, then we'll store both names
- *          *without* extensions.  That way, we can provide consistent
- *          reverse mangling for all names that match.  The test here is
- *          a bit more careful than the one done in earlier versions of
- *          mangle.c:
- *
- *            - the extension must exist on the raw name,
- *            - it must be all lower case
- *            - it must match the mangled extension (to prove that no
- *              mangling occurred).
- *
- *  crh 07-Apr-1998
- *
- * ************************************************************************** **
- */
-static void cache_mangled_name( char *mangled_name, char *raw_name )
-  {
-  ubi_cacheEntryPtr new_entry;
-  char             *s1;
-  char             *s2;
-  size_t               mangled_len;
-  size_t               raw_len;
-  size_t               i;
-
-  /* If the cache isn't initialized, give up. */
-  if( !mc_initialized )
-    return;
-
-  /* Init the string lengths. */
-  mangled_len = strlen( mangled_name );
-  raw_len     = strlen( raw_name );
-
-  /* See if the extensions are unmangled.  If so, store the entry
-   * without the extension, thus creating a "group" reverse map.
-   */
-  s1 = strrchr( mangled_name, '.' );
-  if( s1 && (s2 = strrchr( raw_name, '.' )) )
-    {
-    i = 1;
-    while( s1[i] && (tolower( s1[i] ) == s2[i]) )
-      i++;
-    if( !s1[i] && !s2[i] )
-      {
-      mangled_len -= i;
-      raw_len     -= i;
-      }
-    }
-
-  /* Allocate a new cache entry.  If the allocation fails, just return. */
-  i = sizeof( ubi_cacheEntry ) + mangled_len + raw_len + 2;
-  new_entry = malloc( i );
-  if( !new_entry )
-    return;
-
-  /* Fill the new cache entry, and add it to the cache. */
-  s1 = (char *)(new_entry + 1);
-  s2 = (char *)&(s1[mangled_len + 1]);
-  (void)StrnCpy( s1, mangled_name, mangled_len );
-  (void)StrnCpy( s2, raw_name,     raw_len );
-  ubi_cachePut( mangled_cache, i, new_entry, s1 );
-  } /* cache_mangled_name */
-
-/* ************************************************************************** **
- * Check for a name on the mangled name stack
- *
- *  Input:  s - Input *and* output string buffer.
- *
- *  Output: True if the name was found in the cache, else False.
- *
- *  Notes:  If a reverse map is found, the function will overwrite the string
- *          space indicated by the input pointer <s>.  This is frightening.
- *          It should be rewritten to return NULL if the long name was not
- *          found, and a pointer to the long name if it was found.
- *
- * ************************************************************************** **
- */
-
-BOOL check_mangled_cache( char *s )
+/*
+  see if a filename matches the rules of a 8.3 filename
+*/
+BOOL mangle_is_8_3(const char *fname, BOOL check_case)
 {
-  ubi_cacheEntryPtr FoundPtr;
-  char             *ext_start = NULL;
-  char             *found_name;
-  char             *saved_ext = NULL;
-
-  /* If the cache isn't initialized, give up. */
-  if( !mc_initialized )
-    return( False );
-
-  FoundPtr = ubi_cacheGet( mangled_cache, (ubi_trItemPtr)s );
-
-  /* If we didn't find the name *with* the extension, try without. */
-  if( !FoundPtr )
-  {
-    ext_start = strrchr( s, '.' );
-    if( ext_start )
-    {
-      if((saved_ext = strdup(ext_start)) == NULL)
-        return False;
-
-      *ext_start = '\0';
-      FoundPtr = ubi_cacheGet( mangled_cache, (ubi_trItemPtr)s );
-      /* 
-       * At this point s is the name without the
-       * extension. We re-add the extension if saved_ext
-       * is not null, before freeing saved_ext.
-       */
-    }
-  }
-
-  /* Okay, if we haven't found it we're done. */
-  if( !FoundPtr )
-  {
-    if(saved_ext)
-    {
-      /* Replace the saved_ext as it was truncated. */
-      (void)pstrcat( s, saved_ext );
-      SAFE_FREE(saved_ext);
-    }
-    return( False );
-  }
-
-  /* If we *did* find it, we need to copy it into the string buffer. */
-  found_name = (char *)(FoundPtr + 1);
-  found_name += (strlen( found_name ) + 1);
-
-  DEBUG( 3, ("Found %s on mangled stack ", s) );
-
-  (void)pstrcpy( s, found_name );
-  if( saved_ext )
-  {
-    /* Replace the saved_ext as it was truncated. */
-    (void)pstrcat( s, saved_ext );
-    SAFE_FREE(saved_ext);
-  }
-
-  DEBUG( 3, ("as %s\n", s) );
-
-  return( True );
-} /* check_mangled_cache */
-
-
-/* ************************************************************************** **
- * Used only in do_fwd_mangled_map(), below.
- * ************************************************************************** **
- */
-static char *map_filename( char *s,         /* This is null terminated */
-                           char *pattern,   /* This isn't. */
-                           int len )        /* This is the length of pattern. */
-  {
-  static pstring matching_bit;  /* The bit of the string which matches */
-                                /* a * in pattern if indeed there is a * */
-  char *sp;                     /* Pointer into s. */
-  char *pp;                     /* Pointer into p. */
-  char *match_start;            /* Where the matching bit starts. */
-  pstring pat;
-
-  StrnCpy( pat, pattern, len ); /* Get pattern into a proper string! */
-  pstrcpy( matching_bit, "" );  /* Match but no star gets this. */
-  pp = pat;                     /* Initialize the pointers. */
-  sp = s;
-
-  if( strequal(s, ".") || strequal(s, ".."))
-    {
-    return NULL;                /* Do not map '.' and '..' */
-    }
-
-  if( (len == 1) && (*pattern == '*') )
-    {
-    return NULL;                /* Impossible, too ambiguous for */
-    }                           /* words! */
-
-  while( (*sp)                  /* Not the end of the string. */
-      && (*pp)                  /* Not the end of the pattern. */
-      && (*sp == *pp)           /* The two match. */
-      && (*pp != '*') )         /* No wildcard. */
-    {
-    sp++;                       /* Keep looking. */
-    pp++;
-    }
-
-  if( !*sp && !*pp )            /* End of pattern. */
-    return( matching_bit );     /* Simple match.  Return empty string. */
-
-  if( *pp == '*' )
-    {
-    pp++;                       /* Always interrested in the chacter */
-                                /* after the '*' */
-    if( !*pp )                  /* It is at the end of the pattern. */
-      {
-      StrnCpy( matching_bit, s, sp-s );
-      return( matching_bit );
-      }
-    else
-      {
-      /* The next character in pattern must match a character further */
-      /* along s than sp so look for that character. */
-      match_start = sp;
-      while( (*sp)              /* Not the end of s. */
-          && (*sp != *pp) )     /* Not the same  */
-        sp++;                   /* Keep looking. */
-      if( !*sp )                /* Got to the end without a match. */
-        {
-        return( NULL );
-        }                       /* Still hope for a match. */
-      else
-        {
-        /* Now sp should point to a matching character. */
-        StrnCpy(matching_bit, match_start, sp-match_start);
-        /* Back to needing a stright match again. */
-        while( (*sp)            /* Not the end of the string. */
-            && (*pp)            /* Not the end of the pattern. */
-            && (*sp == *pp) )   /* The two match. */
-          {
-          sp++;                 /* Keep looking. */
-          pp++;
-          }
-        if( !*sp && !*pp )      /* Both at end so it matched */
-          return( matching_bit );
-        else
-          return( NULL );
-        }
-      }
-    }
-  return( NULL );               /* No match. */
-  } /* map_filename */
-
-
-/* ************************************************************************** **
- * MangledMap is a series of name pairs in () separated by spaces.
- * If s matches the first of the pair then the name given is the
- * second of the pair.  A * means any number of any character and if
- * present in the second of the pair as well as the first the
- * matching part of the first string takes the place of the * in the
- * second.
- *
- * I wanted this so that we could have RCS files which can be used
- * by UNIX and DOS programs.  My mapping string is (RCS rcs) which
- * converts the UNIX RCS file subdirectory to lowercase thus
- * preventing mangling.
- *
- * (I think Andrew wrote the above, but I'm not sure. -- CRH)
- *
- * See 'mangled map' in smb.conf(5).
- *
- * ************************************************************************** **
- */
-static void do_fwd_mangled_map(char *s, char *MangledMap)
-  {
-  char *start=MangledMap;       /* Use this to search for mappings. */
-  char *end;                    /* Used to find the end of strings. */
-  char *match_string;
-  pstring new_string;           /* Make up the result here. */
-  char *np;                     /* Points into new_string. */
-
-  DEBUG( 5, ("Mangled Mapping '%s' map '%s'\n", s, MangledMap) );
-  while( *start )
-    {
-    while( (*start) && (*start != '(') )
-      start++;
-    if( !*start )
-      continue;                 /* Always check for the end. */
-    start++;                    /* Skip the ( */
-    end = start;                /* Search for the ' ' or a ')' */
-    DEBUG( 5, ("Start of first in pair '%s'\n", start) );
-    while( (*end) && !((*end == ' ') || (*end == ')')) )
-      end++;
-    if( !*end )
-      {
-      start = end;
-      continue;                 /* Always check for the end. */
-      }
-    DEBUG( 5, ("End of first in pair '%s'\n", end) );
-    if( (match_string = map_filename( s, start, end-start )) )
-      {
-      DEBUG( 5, ("Found a match\n") );
-      /* Found a match. */
-      start = end + 1;          /* Point to start of what it is to become. */
-      DEBUG( 5, ("Start of second in pair '%s'\n", start) );
-      end = start;
-      np = new_string;
-      while( (*end)             /* Not the end of string. */
-          && (*end != ')')      /* Not the end of the pattern. */
-          && (*end != '*') )    /* Not a wildcard. */
-        *np++ = *end++;
-      if( !*end )
-        {
-        start = end;
-        continue;               /* Always check for the end. */
-        }
-      if( *end == '*' )
-        {
-        pstrcpy( np, match_string );
-        np += strlen( match_string );
-        end++;                  /* Skip the '*' */
-        while( (*end)             /* Not the end of string. */
-            && (*end != ')')      /* Not the end of the pattern. */
-            && (*end != '*') )    /* Not a wildcard. */
-          *np++ = *end++;
-        }
-      if( !*end )
-        {
-        start = end;
-        continue;               /* Always check for the end. */
-        }
-      *np++ = '\0';             /* NULL terminate it. */
-      DEBUG(5,("End of second in pair '%s'\n", end));
-      pstrcpy( s, new_string );  /* Substitute with the new name. */
-      DEBUG( 5, ("s is now '%s'\n", s) );
-      }
-    start = end;              /* Skip a bit which cannot be wanted anymore. */
-    start++;
-    }
-  } /* do_fwd_mangled_map */
-
-/*****************************************************************************
- * do the actual mangling to 8.3 format
- * the buffer must be able to hold 13 characters (including the null)
- *****************************************************************************
- */
-void mangle_name_83( char *s)
-  {
-  int csum;
-  char *p;
-  char extension[4];
-  char base[9];
-  int baselen = 0;
-  int extlen = 0;
-
-  extension[0] = 0;
-  base[0] = 0;
-
-  p = strrchr(s,'.');  
-  if( p && (strlen(p+1) < (size_t)4) )
-    {
-    BOOL all_normal = ( strisnormal(p+1) ); /* XXXXXXXXX */
-
-    if( all_normal && p[1] != 0 )
-      {
-      *p = 0;
-      csum = str_checksum( s );
-      *p = '.';
-      }
-    else
-      csum = str_checksum(s);
-    }
-  else
-    csum = str_checksum(s);
-
-  strupper( s );
-
-  DEBUG( 5, ("Mangling name %s to ",s) );
-
-  if( p )
-  {
-         if( p == s )
-                 safe_strcpy( extension, "___", 3 );
-         else
-         {
-                 *p++ = 0;
-                 while( *p && extlen < 3 )
-                 {
-                         if ( *p != '.') {
-                                 extension[extlen++] = p[0];
-                         }
-                         p++;
-                 }
-                 extension[extlen] = 0;
-      }
-  }
-  
-  p = s;
-
-  while( *p && baselen < 5 )
-  {
-         if (*p != '.') {
-                 base[baselen++] = p[0];
-         }
-         p++;
-  }
-  base[baselen] = 0;
-  
-  csum = csum % (MANGLE_BASE*MANGLE_BASE);
-  
-  (void)slprintf(s, 12, "%s%c%c%c",
-                 base, magic_char, mangle( csum/MANGLE_BASE ), mangle( csum ) );
-  
-  if( *extension )
-  {
-         (void)pstrcat( s, "." );
-         (void)pstrcat( s, extension );
-  }
-  
-  DEBUG( 5, ( "%s\n", s ) );
+       return mangle_fns->is_8_3(fname, check_case);
+}
 
-  } /* mangle_name_83 */
+/*
+  try to reverse map a 8.3 name to the original filename. This doesn't have to 
+  always succeed, as the directory handling code in smbd will scan the directory
+  looking for a matching name if it doesn't. It should succeed most of the time
+  or there will be a huge performance penalty
+*/
+BOOL mangle_check_cache(char *s)
+{
+       return mangle_fns->check_cache(s);
+}
 
-/*****************************************************************************
- * Convert a filename to DOS format.  Return True if successful.
- *
- *  Input:  OutName - Source *and* destination buffer. 
- *
- *                    NOTE that OutName must point to a memory space that
- *                    is at least 13 bytes in size!
- *
- *          need83  - If False, name mangling will be skipped unless the
- *                    name contains illegal characters.  Mapping will still
- *                    be done, if appropriate.  This is probably used to
- *                    signal that a client does not require name mangling,
- *                    thus skipping the name mangling even on shares which
- *                    have name-mangling turned on.
- *          cache83 - If False, the mangled name cache will not be updated.
- *                    This is usually used to prevent that we overwrite
- *                    a conflicting cache entry prematurely, i.e. before
- *                    we know whether the client is really interested in the
- *                    current name.  (See PR#13758).  UKD.
- *          snum    - Share number.  This identifies the share in which the
- *                    name exists.
- *
- *  Output: Returns False only if the name wanted mangling but the share does
- *          not have name mangling turned on.
- *
- * ****************************************************************************
+/* 
+   map a long filename to a 8.3 name. 
  */
-BOOL name_map_mangle(char *OutName, BOOL need83, BOOL cache83, int snum)
+BOOL mangle_map(char *OutName, BOOL need83, BOOL cache83, int snum)
 {
-       char *map;
-       smb_ucs2_t *OutName_ucs2;
-       DEBUG(5,("name_map_mangle( %s, need83 = %s, cache83 = %s, %d )\n", OutName,
-                need83 ? "True" : "False", cache83 ? "True" : "False", snum));
-       
-       if (push_ucs2_allocate((void **)&OutName_ucs2, OutName) < 0) {
-               DEBUG(0, ("push_ucs2_allocate failed!\n"));
-               return False;
-       }
-
-       /* apply any name mappings */
-       map = lp_mangled_map(snum);
-
-       if (map && *map) {
-               do_fwd_mangled_map( OutName, map );
-       }
-
-       /* check if it's already in 8.3 format */
-       if (need83 && !NT_STATUS_IS_OK(is_8_3_w(OutName_ucs2))) {
-               char *tmp = NULL; 
-
-               if (!lp_manglednames(snum)) {
-                       return(False);
-               }
-
-               /* mangle it into 8.3 */
-               if (cache83)
-                       tmp = strdup(OutName);
-
-               mangle_name_83(OutName);
-
-               if(tmp != NULL) {
-                       cache_mangled_name(OutName, tmp);
-                       SAFE_FREE(tmp);
+       /* name mangling can be disabled for speed, in which case
+          we just truncate the string */
+       if (!lp_manglednames(snum)) {
+               if (need83) {
+                       string_truncate(OutName, 12);
                }
+               return True;
        }
 
-       DEBUG(5,("name_map_mangle() ==> [%s]\n", OutName));
-       SAFE_FREE(OutName_ucs2);
-       return(True);
-} /* name_map_mangle */
+       /* invoke the inane "mangled map" code */
+       mangle_map_filename(OutName, snum);
 
+       return mangle_fns->name_map(OutName, need83, cache83);
+}
diff --git a/source/smbd/mangle_hash.c b/source/smbd/mangle_hash.c
new file mode 100644 (file)
index 0000000..f38c2ae
--- /dev/null
@@ -0,0 +1,775 @@
+/* 
+   Unix SMB/CIFS implementation.
+   Name mangling
+   Copyright (C) Andrew Tridgell 1992-2002
+   Copyright (C) Simo Sorce 2001
+   Copyright (C) Andrew Bartlett 2002
+   
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2 of the License, or
+   (at your option) any later version.
+   
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+   
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+*/
+
+
+/* -------------------------------------------------------------------------- **
+ * Notable problems...
+ *
+ *  March/April 1998  CRH
+ *  - Many of the functions in this module overwrite string buffers passed to
+ *    them.  This causes a variety of problems and is, generally speaking,
+ *    dangerous and scarry.  See the kludge notes in name_map()
+ *    below.
+ *  - It seems that something is calling name_map() twice.  The
+ *    first call is probably some sort of test.  Names which contain
+ *    illegal characters are being doubly mangled.  I'm not sure, but
+ *    I'm guessing the problem is in server.c.
+ *
+ * -------------------------------------------------------------------------- **
+ */
+
+/* -------------------------------------------------------------------------- **
+ * History...
+ *
+ *  March/April 1998  CRH
+ *  Updated a bit.  Rewrote is_mangled() to be a bit more selective.
+ *  Rewrote the mangled name cache.  Added comments here and there.
+ *  &c.
+ * -------------------------------------------------------------------------- **
+ */
+
+#include "includes.h"
+
+
+/* -------------------------------------------------------------------------- **
+ * External Variables...
+ */
+
+extern int case_default;    /* Are conforming 8.3 names all upper or lower?   */
+extern BOOL case_mangle;    /* If true, all chars in 8.3 should be same case. */
+
+/* -------------------------------------------------------------------------- **
+ * Other stuff...
+ *
+ * magic_char     - This is the magic char used for mangling.  It's
+ *                  global.  There is a call to lp_magicchar() in server.c
+ *                  that is used to override the initial value.
+ *
+ * MANGLE_BASE    - This is the number of characters we use for name mangling.
+ *
+ * basechars      - The set characters used for name mangling.  This
+ *                  is static (scope is this file only).
+ *
+ * mangle()       - Macro used to select a character from basechars (i.e.,
+ *                  mangle(n) will return the nth digit, modulo MANGLE_BASE).
+ *
+ * chartest       - array 0..255.  The index range is the set of all possible
+ *                  values of a byte.  For each byte value, the content is a
+ *                  two nibble pair.  See BASECHAR_MASK and ILLEGAL_MASK,
+ *                  below.
+ *
+ * ct_initialized - False until the chartest array has been initialized via
+ *                  a call to init_chartest().
+ *
+ * BASECHAR_MASK  - Masks the upper nibble of a one-byte value.
+ *
+ * ILLEGAL_MASK   - Masks the lower nibble of a one-byte value.
+ *
+ * isbasecahr()   - Given a character, check the chartest array to see
+ *                  if that character is in the basechars set.  This is
+ *                  faster than using strchr_m().
+ *
+ * isillegal()    - Given a character, check the chartest array to see
+ *                  if that character is in the illegal characters set.
+ *                  This is faster than using strchr_m().
+ *
+ * mangled_cache  - Cache header used for storing mangled -> original
+ *                  reverse maps.
+ *
+ * mc_initialized - False until the mangled_cache structure has been
+ *                  initialized via a call to reset_mangled_cache().
+ *
+ * MANGLED_CACHE_MAX_ENTRIES - Default maximum number of entries for the
+ *                  cache.  A value of 0 indicates "infinite".
+ *
+ * MANGLED_CACHE_MAX_MEMORY  - Default maximum amount of memory for the
+ *                  cache.  When the cache was kept as an array of 256
+ *                  byte strings, the default cache size was 50 entries.
+ *                  This required a fixed 12.5Kbytes of memory.  The
+ *                  mangled stack parameter is no longer used (though
+ *                  this might change).  We're now using a fixed 16Kbyte
+ *                  maximum cache size.  This will probably be much more
+ *                  than 50 entries.
+ */
+
+char magic_char = '~';
+
+static char basechars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_-!@#$%";
+#define MANGLE_BASE       (sizeof(basechars)/sizeof(char)-1)
+
+static unsigned char chartest[256]  = { 0 };
+static BOOL          ct_initialized = False;
+
+#define mangle(V) ((char)(basechars[(V) % MANGLE_BASE]))
+#define BASECHAR_MASK 0xf0
+#define ILLEGAL_MASK  0x0f
+#define isbasechar(C) ( (chartest[ ((C) & 0xff) ]) & BASECHAR_MASK )
+#define isillegal(C) ( (chartest[ ((C) & 0xff) ]) & ILLEGAL_MASK )
+
+static ubi_cacheRoot mangled_cache[1] =  { { { 0, 0, 0, 0 }, 0, 0, 0, 0, 0, 0 } };
+static BOOL          mc_initialized   = False;
+#define MANGLED_CACHE_MAX_ENTRIES 0
+#define MANGLED_CACHE_MAX_MEMORY  16384
+
+
+/* -------------------------------------------------------------------------- **
+ * External Variables...
+ */
+
+extern int case_default;    /* Are conforming 8.3 names all upper or lower?   */
+extern BOOL case_mangle;    /* If true, all chars in 8.3 should be same case. */
+
+/* -------------------------------------------------------------------- */
+
+static NTSTATUS has_valid_chars(const smb_ucs2_t *s)
+{
+       if (!s || !*s) return NT_STATUS_INVALID_PARAMETER;
+
+       /* CHECK: this should not be necessary if the ms wild chars
+          are not valid in valid.dat  --- simo */
+       if (ms_has_wild_w(s)) return NT_STATUS_UNSUCCESSFUL;
+
+       while (*s) {
+               if(!isvalid83_w(*s)) return NT_STATUS_UNSUCCESSFUL;
+               s++;
+       }
+
+       return NT_STATUS_OK;
+}
+
+/* return False if something fail and
+ * return 2 alloced unicode strings that contain prefix and extension
+ */
+static NTSTATUS mangle_get_prefix(const smb_ucs2_t *ucs2_string, smb_ucs2_t **prefix, smb_ucs2_t **extension)
+{
+       size_t ext_len;
+       smb_ucs2_t *p;
+
+       *extension = 0;
+       *prefix = strdup_w(ucs2_string);
+       if (!*prefix) {
+               return NT_STATUS_NO_MEMORY;
+       }
+       if ((p = strrchr_w(*prefix, UCS2_CHAR('.'))))
+       {
+               ext_len = strlen_w(p+1);
+               if ((ext_len > 0) && (ext_len < 4) && (p != *prefix) &&
+                   (NT_STATUS_IS_OK(has_valid_chars(p+1)))) /* check extension */
+               {
+                       *p = 0;
+                       *extension = strdup_w(p+1);
+                       if (!*extension) {
+                               SAFE_FREE(*prefix);
+                               return NT_STATUS_NO_MEMORY;
+                       }
+               }
+       }
+       return NT_STATUS_OK;
+}
+
+/* ************************************************************************** **
+ * Return NT_STATUS_UNSUCCESSFUL if a name is a special msdos reserved name.
+ *
+ *  Input:  fname - String containing the name to be tested.
+ *
+ *  Output: NT_STATUS_UNSUCCESSFUL, if the name matches one of the list of reserved names.
+ *
+ *  Notes:  This is a static function called by is_8_3(), below.
+ *
+ * ************************************************************************** **
+ */
+static NTSTATUS is_valid_name(const smb_ucs2_t *fname)
+{
+       smb_ucs2_t *str, *p;
+       NTSTATUS ret = NT_STATUS_OK;
+
+       if (!fname || !*fname) return NT_STATUS_INVALID_PARAMETER;
+
+       if (*fname == UCS2_CHAR('.')) return NT_STATUS_UNSUCCESSFUL;
+       
+       ret = has_valid_chars(fname);
+       if (NT_STATUS_IS_ERR(ret)) return ret;
+
+       str = strdup_w(fname);
+       p = strchr_w(str, UCS2_CHAR('.'));
+       if (p) *p = 0;
+       strupper_w(str);
+       p = &(str[1]);
+
+       switch(str[0])
+       {
+       case UCS2_CHAR('A'):
+               if(strcmp_wa(p, "UX") == 0)
+                       ret = NT_STATUS_UNSUCCESSFUL;
+               break;
+       case UCS2_CHAR('C'):
+               if((strcmp_wa(p, "LOCK$") == 0)
+               || (strcmp_wa(p, "ON") == 0)
+               || (strcmp_wa(p, "OM1") == 0)
+               || (strcmp_wa(p, "OM2") == 0)
+               || (strcmp_wa(p, "OM3") == 0)
+               || (strcmp_wa(p, "OM4") == 0)
+               )
+                       ret = NT_STATUS_UNSUCCESSFUL;
+               break;
+       case UCS2_CHAR('L'):
+               if((strcmp_wa(p, "PT1") == 0)
+               || (strcmp_wa(p, "PT2") == 0)
+               || (strcmp_wa(p, "PT3") == 0)
+               )
+                       ret = NT_STATUS_UNSUCCESSFUL;
+               break;
+       case UCS2_CHAR('N'):
+               if(strcmp_wa(p, "UL") == 0)
+                       ret = NT_STATUS_UNSUCCESSFUL;
+               break;
+       case UCS2_CHAR('P'):
+               if(strcmp_wa(p, "RN") == 0)
+                       ret = NT_STATUS_UNSUCCESSFUL;
+               break;
+       default:
+               break;
+       }
+
+       SAFE_FREE(str);
+       return ret;
+}
+
+static NTSTATUS is_8_3_w(const smb_ucs2_t *fname)
+{
+       smb_ucs2_t *pref = 0, *ext = 0;
+       size_t plen;
+       NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
+
+       if (!fname || !*fname) return NT_STATUS_INVALID_PARAMETER;
+
+       if (strlen_w(fname) > 12) return NT_STATUS_UNSUCCESSFUL;
+       
+       if (strcmp_wa(fname, ".") == 0 || strcmp_wa(fname, "..") == 0)
+               return NT_STATUS_OK;
+
+       if (NT_STATUS_IS_ERR(is_valid_name(fname))) goto done;
+
+       if (NT_STATUS_IS_ERR(mangle_get_prefix(fname, &pref, &ext))) goto done;
+       plen = strlen_w(pref);
+
+       if (strchr_wa(pref, '.')) goto done;
+       if (plen < 1 || plen > 8) goto done;
+       if (ext) if (strlen_w(ext) > 3) goto done;
+
+       ret = NT_STATUS_OK;
+
+done:
+       SAFE_FREE(pref);
+       SAFE_FREE(ext);
+       return ret;
+}
+
+static BOOL is_8_3(const char *fname, BOOL check_case)
+{
+       const char *f;
+       smb_ucs2_t *ucs2name;
+       NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
+
+       if (!fname || !*fname) return False;
+       if ((f = strrchr(fname, '/')) == NULL) f = fname;
+       else f++;
+
+       if (strlen(f) > 12) return False;
+       
+       ucs2name = acnv_uxu2(f);
+       if (!ucs2name)
+       {
+               DEBUG(0,("is_8_3: internal error acnv_uxu2() failed!\n"));
+               goto done;
+       }
+
+       ret = is_8_3_w(ucs2name);
+
+done:
+       SAFE_FREE(ucs2name);
+
+       if (!NT_STATUS_IS_OK(ret)) { 
+               return False;
+       }
+       
+       return True;
+}
+
+
+
+/* -------------------------------------------------------------------------- **
+ * Functions...
+ */
+
+/* ************************************************************************** **
+ * Initialize the static character test array.
+ *
+ *  Input:  none
+ *
+ *  Output: none
+ *
+ *  Notes:  This function changes (loads) the contents of the <chartest>
+ *          array.  The scope of <chartest> is this file.
+ *
+ * ************************************************************************** **
+ */
+static void init_chartest( void )
+  {
+  char          *illegalchars = "*\\/?<>|\":";
+  unsigned char *s;
+  
+  memset( (char *)chartest, '\0', 256 );
+
+  for( s = (unsigned char *)illegalchars; *s; s++ )
+    chartest[*s] = ILLEGAL_MASK;
+
+  for( s = (unsigned char *)basechars; *s; s++ )
+    chartest[*s] |= BASECHAR_MASK;
+
+  ct_initialized = True;
+  } /* init_chartest */
+
+
+/* ************************************************************************** **
+ * Return True if the name *could be* a mangled name.
+ *
+ *  Input:  s - A path name - in UNIX pathname format.
+ *
+ *  Output: True if the name matches the pattern described below in the
+ *          notes, else False.
+ *
+ *  Notes:  The input name is *not* tested for 8.3 compliance.  This must be
+ *          done separately.  This function returns true if the name contains
+ *          a magic character followed by excactly two characters from the
+ *          basechars list (above), which in turn are followed either by the
+ *          nul (end of string) byte or a dot (extension) or by a '/' (end of
+ *          a directory name).
+ *
+ * ************************************************************************** **
+ */
+static BOOL is_mangled(const char *s)
+  {
+  char *magic;
+
+  if( !ct_initialized )
+    init_chartest();
+
+  magic = strchr_m( s, magic_char );
+  while( magic && magic[1] && magic[2] )          /* 3 chars, 1st is magic. */
+    {
+    if( ('.' == magic[3] || '/' == magic[3] || !(magic[3]))          /* Ends with '.' or nul or '/' ?  */
+     && isbasechar( toupper(magic[1]) )           /* is 2nd char basechar?  */
+     && isbasechar( toupper(magic[2]) ) )         /* is 3rd char basechar?  */
+      return( True );                           /* If all above, then true, */
+    magic = strchr_m( magic+1, magic_char );      /*    else seek next magic. */
+    }
+  return( False );
+  } /* is_mangled */
+
+
+/* ************************************************************************** **
+ * Compare two cache keys and return a value indicating their ordinal
+ * relationship.
+ *
+ *  Input:  ItemPtr - Pointer to a comparison key.  In this case, this will
+ *                    be a mangled name string.
+ *          NodePtr - Pointer to a node in the cache.  The node structure
+ *                    will be followed in memory by a mangled name string.
+ *
+ *  Output: A signed integer, as follows:
+ *            (x < 0)  <==> Key1 less than Key2
+ *            (x == 0) <==> Key1 equals Key2
+ *            (x > 0)  <==> Key1 greater than Key2
+ *
+ *  Notes:  This is a ubiqx-style comparison routine.  See ubi_BinTree for
+ *          more info.
+ *
+ * ************************************************************************** **
+ */
+static signed int cache_compare( ubi_btItemPtr ItemPtr, ubi_btNodePtr NodePtr )
+  {
+  char *Key1 = (char *)ItemPtr;
+  char *Key2 = (char *)(((ubi_cacheEntryPtr)NodePtr) + 1);
+
+  return( StrCaseCmp( Key1, Key2 ) );
+  } /* cache_compare */
+
+/* ************************************************************************** **
+ * Free a cache entry.
+ *
+ *  Input:  WarrenZevon - Pointer to the entry that is to be returned to
+ *                        Nirvana.
+ *  Output: none.
+ *
+ *  Notes:  This function gets around the possibility that the standard
+ *          free() function may be implemented as a macro, or other evil
+ *          subversions (oh, so much fun).
+ *
+ * ************************************************************************** **
+ */
+static void cache_free_entry( ubi_trNodePtr WarrenZevon )
+  {
+         ZERO_STRUCTP(WarrenZevon);
+         SAFE_FREE( WarrenZevon );
+  } /* cache_free_entry */
+
+/* ************************************************************************** **
+ * Initializes or clears the mangled cache.
+ *
+ *  Input:  none.
+ *  Output: none.
+ *
+ *  Notes:  There is a section below that is commented out.  It shows how
+ *          one might use lp_ calls to set the maximum memory and entry size
+ *          of the cache.  You might also want to remove the constants used
+ *          in ubi_cacheInit() and replace them with lp_ calls.  If so, then
+ *          the calls to ubi_cacheSetMax*() would be moved into the else
+ *          clause.  Another option would be to pass in the max_entries and
+ *          max_memory values as parameters.  crh 09-Apr-1998.
+ *
+ * ************************************************************************** **
+ */
+static void mangle_reset( void )
+  {
+  if( !mc_initialized )
+    {
+    (void)ubi_cacheInit( mangled_cache,
+                         cache_compare,
+                         cache_free_entry,
+                         MANGLED_CACHE_MAX_ENTRIES,
+                         MANGLED_CACHE_MAX_MEMORY );
+    mc_initialized = True;
+    }
+  else
+    {
+    (void)ubi_cacheClear( mangled_cache );
+    }
+
+  /*
+  (void)ubi_cacheSetMaxEntries( mangled_cache, lp_mangled_cache_entries() );
+  (void)ubi_cacheSetMaxMemory(  mangled_cache, lp_mangled_cache_memory() );
+  */
+  } /* reset_mangled_cache  */
+
+
+/* ************************************************************************** **
+ * Add a mangled name into the cache.
+ *
+ *  Notes:  If the mangled cache has not been initialized, then the
+ *          function will simply fail.  It could initialize the cache,
+ *          but that's not the way it was done before I changed the
+ *          cache mechanism, so I'm sticking with the old method.
+ *
+ *          If the extension of the raw name maps directly to the
+ *          extension of the mangled name, then we'll store both names
+ *          *without* extensions.  That way, we can provide consistent
+ *          reverse mangling for all names that match.  The test here is
+ *          a bit more careful than the one done in earlier versions of
+ *          mangle.c:
+ *
+ *            - the extension must exist on the raw name,
+ *            - it must be all lower case
+ *            - it must match the mangled extension (to prove that no
+ *              mangling occurred).
+ *
+ *  crh 07-Apr-1998
+ *
+ * ************************************************************************** **
+ */
+static void cache_mangled_name( char *mangled_name, char *raw_name )
+  {
+  ubi_cacheEntryPtr new_entry;
+  char             *s1;
+  char             *s2;
+  size_t               mangled_len;
+  size_t               raw_len;
+  size_t               i;
+
+  /* If the cache isn't initialized, give up. */
+  if( !mc_initialized )
+    return;
+
+  /* Init the string lengths. */
+  mangled_len = strlen( mangled_name );
+  raw_len     = strlen( raw_name );
+
+  /* See if the extensions are unmangled.  If so, store the entry
+   * without the extension, thus creating a "group" reverse map.
+   */
+  s1 = strrchr( mangled_name, '.' );
+  if( s1 && (s2 = strrchr( raw_name, '.' )) )
+    {
+    i = 1;
+    while( s1[i] && (tolower( s1[i] ) == s2[i]) )
+      i++;
+    if( !s1[i] && !s2[i] )
+      {
+      mangled_len -= i;
+      raw_len     -= i;
+      }
+    }
+
+  /* Allocate a new cache entry.  If the allocation fails, just return. */
+  i = sizeof( ubi_cacheEntry ) + mangled_len + raw_len + 2;
+  new_entry = malloc( i );
+  if( !new_entry )
+    return;
+
+  /* Fill the new cache entry, and add it to the cache. */
+  s1 = (char *)(new_entry + 1);
+  s2 = (char *)&(s1[mangled_len + 1]);
+  (void)StrnCpy( s1, mangled_name, mangled_len );
+  (void)StrnCpy( s2, raw_name,     raw_len );
+  ubi_cachePut( mangled_cache, i, new_entry, s1 );
+  } /* cache_mangled_name */
+
+/* ************************************************************************** **
+ * Check for a name on the mangled name stack
+ *
+ *  Input:  s - Input *and* output string buffer.
+ *
+ *  Output: True if the name was found in the cache, else False.
+ *
+ *  Notes:  If a reverse map is found, the function will overwrite the string
+ *          space indicated by the input pointer <s>.  This is frightening.
+ *          It should be rewritten to return NULL if the long name was not
+ *          found, and a pointer to the long name if it was found.
+ *
+ * ************************************************************************** **
+ */
+
+static BOOL check_cache( char *s )
+{
+  ubi_cacheEntryPtr FoundPtr;
+  char             *ext_start = NULL;
+  char             *found_name;
+  char             *saved_ext = NULL;
+
+  /* If the cache isn't initialized, give up. */
+  if( !mc_initialized )
+    return( False );
+
+  FoundPtr = ubi_cacheGet( mangled_cache, (ubi_trItemPtr)s );
+
+  /* If we didn't find the name *with* the extension, try without. */
+  if( !FoundPtr )
+  {
+    ext_start = strrchr( s, '.' );
+    if( ext_start )
+    {
+      if((saved_ext = strdup(ext_start)) == NULL)
+        return False;
+
+      *ext_start = '\0';
+      FoundPtr = ubi_cacheGet( mangled_cache, (ubi_trItemPtr)s );
+      /* 
+       * At this point s is the name without the
+       * extension. We re-add the extension if saved_ext
+       * is not null, before freeing saved_ext.
+       */
+    }
+  }
+
+  /* Okay, if we haven't found it we're done. */
+  if( !FoundPtr )
+  {
+    if(saved_ext)
+    {
+      /* Replace the saved_ext as it was truncated. */
+      (void)pstrcat( s, saved_ext );
+      SAFE_FREE(saved_ext);
+    }
+    return( False );
+  }
+
+  /* If we *did* find it, we need to copy it into the string buffer. */
+  found_name = (char *)(FoundPtr + 1);
+  found_name += (strlen( found_name ) + 1);
+
+  (void)pstrcpy( s, found_name );
+  if( saved_ext )
+  {
+    /* Replace the saved_ext as it was truncated. */
+    (void)pstrcat( s, saved_ext );
+    SAFE_FREE(saved_ext);
+  }
+
+  return( True );
+} /* check_mangled_cache */
+
+
+/*****************************************************************************
+ * do the actual mangling to 8.3 format
+ * the buffer must be able to hold 13 characters (including the null)
+ *****************************************************************************
+ */
+static void to_8_3(char *s)
+  {
+  int csum;
+  char *p;
+  char extension[4];
+  char base[9];
+  int baselen = 0;
+  int extlen = 0;
+
+  extension[0] = 0;
+  base[0] = 0;
+
+  p = strrchr(s,'.');  
+  if( p && (strlen(p+1) < (size_t)4) )
+    {
+    BOOL all_normal = ( strisnormal(p+1) ); /* XXXXXXXXX */
+
+    if( all_normal && p[1] != 0 )
+      {
+      *p = 0;
+      csum = str_checksum( s );
+      *p = '.';
+      }
+    else
+      csum = str_checksum(s);
+    }
+  else
+    csum = str_checksum(s);
+
+  strupper( s );
+
+  if( p )
+  {
+         if( p == s )
+                 safe_strcpy( extension, "___", 3 );
+         else
+         {
+                 *p++ = 0;
+                 while( *p && extlen < 3 )
+                 {
+                         if ( *p != '.') {
+                                 extension[extlen++] = p[0];
+                         }
+                         p++;
+                 }
+                 extension[extlen] = 0;
+      }
+  }
+  
+  p = s;
+
+  while( *p && baselen < 5 )
+  {
+         if (*p != '.') {
+                 base[baselen++] = p[0];
+         }
+         p++;
+  }
+  base[baselen] = 0;
+  
+  csum = csum % (MANGLE_BASE*MANGLE_BASE);
+  
+  (void)slprintf(s, 12, "%s%c%c%c",
+                 base, magic_char, mangle( csum/MANGLE_BASE ), mangle( csum ) );
+  
+  if( *extension )
+  {
+         (void)pstrcat( s, "." );
+         (void)pstrcat( s, extension );
+  }
+  
+  } /* mangle_name_83 */
+
+/*****************************************************************************
+ * Convert a filename to DOS format.  Return True if successful.
+ *
+ *  Input:  OutName - Source *and* destination buffer. 
+ *
+ *                    NOTE that OutName must point to a memory space that
+ *                    is at least 13 bytes in size!
+ *
+ *          need83  - If False, name mangling will be skipped unless the
+ *                    name contains illegal characters.  Mapping will still
+ *                    be done, if appropriate.  This is probably used to
+ *                    signal that a client does not require name mangling,
+ *                    thus skipping the name mangling even on shares which
+ *                    have name-mangling turned on.
+ *          cache83 - If False, the mangled name cache will not be updated.
+ *                    This is usually used to prevent that we overwrite
+ *                    a conflicting cache entry prematurely, i.e. before
+ *                    we know whether the client is really interested in the
+ *                    current name.  (See PR#13758).  UKD.
+ *
+ *  Output: Returns False only if the name wanted mangling but the share does
+ *          not have name mangling turned on.
+ *
+ * ****************************************************************************
+ */
+static BOOL name_map(char *OutName, BOOL need83, BOOL cache83)
+{
+       smb_ucs2_t *OutName_ucs2;
+       DEBUG(5,("name_map( %s, need83 = %s, cache83 = %s)\n", OutName,
+                need83 ? "True" : "False", cache83 ? "True" : "False"));
+       
+       if (push_ucs2_allocate((void **)&OutName_ucs2, OutName) < 0) {
+               DEBUG(0, ("push_ucs2_allocate failed!\n"));
+               return False;
+       }
+
+       /* check if it's already in 8.3 format */
+       if (need83 && !NT_STATUS_IS_OK(is_8_3_w(OutName_ucs2))) {
+               char *tmp = NULL; 
+
+               /* mangle it into 8.3 */
+               if (cache83)
+                       tmp = strdup(OutName);
+
+               to_8_3(OutName);
+
+               if(tmp != NULL) {
+                       cache_mangled_name(OutName, tmp);
+                       SAFE_FREE(tmp);
+               }
+       }
+
+       DEBUG(5,("name_map() ==> [%s]\n", OutName));
+       SAFE_FREE(OutName_ucs2);
+       return(True);
+} /* name_map */
+
+
+/*
+  the following provides the abstraction layer to make it easier
+  to drop in an alternative mangling implementation
+*/
+static struct mangle_fns mangle_fns = {
+       is_mangled,
+       is_8_3,
+       mangle_reset,
+       check_cache,
+       name_map
+};
+
+/* return the methods for this mangling implementation */
+struct mangle_fns *mangle_hash_init(void)
+{
+       mangle_reset();
+
+       return &mangle_fns;
+}
diff --git a/source/smbd/mangle_map.c b/source/smbd/mangle_map.c
new file mode 100644 (file)
index 0000000..71d9340
--- /dev/null
@@ -0,0 +1,203 @@
+/* 
+   Unix SMB/CIFS implementation.
+   Name mapping code 
+   Copyright (C) Jeremy Allison 1998
+   Copyright (C) Andrew Tridgell 2002
+   
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2 of the License, or
+   (at your option) any later version.
+   
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+   
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+*/
+
+#include "includes.h"
+
+
+/* ************************************************************************** **
+ * Used only in do_fwd_mangled_map(), below.
+ * ************************************************************************** **
+ */
+static char *map_filename( char *s,         /* This is null terminated */
+                           const char *pattern,   /* This isn't. */
+                           int len )        /* This is the length of pattern. */
+  {
+  static pstring matching_bit;  /* The bit of the string which matches */
+                                /* a * in pattern if indeed there is a * */
+  char *sp;                     /* Pointer into s. */
+  char *pp;                     /* Pointer into p. */
+  char *match_start;            /* Where the matching bit starts. */
+  pstring pat;
+
+  StrnCpy( pat, pattern, len ); /* Get pattern into a proper string! */
+  pstrcpy( matching_bit, "" );  /* Match but no star gets this. */
+  pp = pat;                     /* Initialize the pointers. */
+  sp = s;
+
+  if( strequal(s, ".") || strequal(s, ".."))
+    {
+    return NULL;                /* Do not map '.' and '..' */
+    }
+
+  if( (len == 1) && (*pattern == '*') )
+    {
+    return NULL;                /* Impossible, too ambiguous for */
+    }                           /* words! */
+
+  while( (*sp)                  /* Not the end of the string. */
+      && (*pp)                  /* Not the end of the pattern. */
+      && (*sp == *pp)           /* The two match. */
+      && (*pp != '*') )         /* No wildcard. */
+    {
+    sp++;                       /* Keep looking. */
+    pp++;
+    }
+
+  if( !*sp && !*pp )            /* End of pattern. */
+    return( matching_bit );     /* Simple match.  Return empty string. */
+
+  if( *pp == '*' )
+    {
+    pp++;                       /* Always interrested in the chacter */
+                                /* after the '*' */
+    if( !*pp )                  /* It is at the end of the pattern. */
+      {
+      StrnCpy( matching_bit, s, sp-s );
+      return( matching_bit );
+      }
+    else
+      {
+      /* The next character in pattern must match a character further */
+      /* along s than sp so look for that character. */
+      match_start = sp;
+      while( (*sp)              /* Not the end of s. */
+          && (*sp != *pp) )     /* Not the same  */
+        sp++;                   /* Keep looking. */
+      if( !*sp )                /* Got to the end without a match. */
+        {
+        return( NULL );
+        }                       /* Still hope for a match. */
+      else
+        {
+        /* Now sp should point to a matching character. */
+        StrnCpy(matching_bit, match_start, sp-match_start);
+        /* Back to needing a stright match again. */
+        while( (*sp)            /* Not the end of the string. */
+            && (*pp)            /* Not the end of the pattern. */
+            && (*sp == *pp) )   /* The two match. */
+          {
+          sp++;                 /* Keep looking. */
+          pp++;
+          }
+        if( !*sp && !*pp )      /* Both at end so it matched */
+          return( matching_bit );
+        else
+          return( NULL );
+        }
+      }
+    }
+  return( NULL );               /* No match. */
+  } /* map_filename */
+
+
+/* ************************************************************************** **
+ * MangledMap is a series of name pairs in () separated by spaces.
+ * If s matches the first of the pair then the name given is the
+ * second of the pair.  A * means any number of any character and if
+ * present in the second of the pair as well as the first the
+ * matching part of the first string takes the place of the * in the
+ * second.
+ *
+ * I wanted this so that we could have RCS files which can be used
+ * by UNIX and DOS programs.  My mapping string is (RCS rcs) which
+ * converts the UNIX RCS file subdirectory to lowercase thus
+ * preventing mangling.
+ *
+ * See 'mangled map' in smb.conf(5).
+ *
+ * ************************************************************************** **
+ */
+static void mangled_map(char *s, const char *MangledMap)
+{
+       char *start=MangledMap;       /* Use this to search for mappings. */
+       char *end;                    /* Used to find the end of strings. */
+       char *match_string;
+       pstring new_string;           /* Make up the result here. */
+       char *np;                     /* Points into new_string. */
+
+       DEBUG( 5, ("Mangled Mapping '%s' map '%s'\n", s, MangledMap) );
+       while( *start ) {
+               while( (*start) && (*start != '(') )
+                       start++;
+               if( !*start )
+                       continue;                 /* Always check for the end. */
+               start++;                    /* Skip the ( */
+               end = start;                /* Search for the ' ' or a ')' */
+               DEBUG( 5, ("Start of first in pair '%s'\n", start) );
+               while( (*end) && !((*end == ' ') || (*end == ')')) )
+                       end++;
+               if( !*end ) {
+                       start = end;
+                       continue;                 /* Always check for the end. */
+               }
+               DEBUG( 5, ("End of first in pair '%s'\n", end) );
+               if( (match_string = map_filename( s, start, end-start )) ) {
+                       DEBUG( 5, ("Found a match\n") );
+                       /* Found a match. */
+                       start = end + 1; /* Point to start of what it is to become. */
+                       DEBUG( 5, ("Start of second in pair '%s'\n", start) );
+                       end = start;
+                       np = new_string;
+                       while( (*end)             /* Not the end of string. */
+                              && (*end != ')')      /* Not the end of the pattern. */
+                              && (*end != '*') )    /* Not a wildcard. */
+                               *np++ = *end++;
+
+                       if( !*end ) {
+                               start = end;
+                               continue;               /* Always check for the end. */
+                       }
+                       if( *end == '*' ) {
+                               pstrcpy( np, match_string );
+                               np += strlen( match_string );
+                               end++;                  /* Skip the '*' */
+                               while ((*end)           /* Not the end of string. */
+                                      && (*end != ')') /* Not the end of the pattern. */
+                                      && (*end != '*'))/* Not a wildcard. */
+                                       *np++ = *end++;
+                       }
+                       if (!*end) {
+                               start = end;
+                               continue;               /* Always check for the end. */
+                       }
+                       *np++ = '\0';             /* NULL terminate it. */
+                       DEBUG(5,("End of second in pair '%s'\n", end));
+                       pstrcpy( s, new_string );  /* Substitute with the new name. */
+                       DEBUG( 5, ("s is now '%s'\n", s) );
+               }
+               start = end;  /* Skip a bit which cannot be wanted anymore. */
+               start++;
+       }
+}
+
+/*
+  front end routine to the mangled map code 
+  personally I think that the whole idea of "mangled map" is completely bogus
+*/
+void mangle_map_filename(char *fname, int snum)
+{
+       char *map;
+
+       map = lp_mangled_map(snum);
+       if (!map || !*map) return;
+
+       mangled_map(fname, map);
+}
index c55c806a438fbfb5701ecf56c93ccb0975213bb1..23606f1d147f9ad42d05d0ad4492469ab972f803 100644 (file)
@@ -831,7 +831,9 @@ static BOOL oplock_break(SMB_DEV_T dev, SMB_INO_T inode, unsigned long file_id,
                        OPEN_FSP(fsp) && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
                DEBUG(0,("oplock_break: client failure in oplock break in file %s\n", fsp->fsp_name));
                remove_oplock(fsp,True);
+#if FASCIST_OPLOCK_BACKOFF
                global_client_failed_oplock_break = True; /* Never grant this client an oplock again. */
+#endif
        }
 
        /*
index f3b3ce4a8a2473925aab3108953cdfdf4d26b9a6..fbb981781fdd748c04c813346d5835c434d1fd9f 100644 (file)
@@ -1300,8 +1300,8 @@ NTSTATUS unlink_internals(connection_struct *conn, int dirtype, char *name)
         * Tine Smukavec <valentin.smukavec@hermes.si>.
         */
        
-       if (!rc && is_mangled(mask))
-               check_mangled_cache( mask );
+       if (!rc && mangle_is_mangled(mask))
+               mangle_check_cache( mask );
        
        has_wild = ms_has_wild(mask);
        
@@ -1842,12 +1842,15 @@ int reply_writebraw(connection_struct *conn, char *inbuf,char *outbuf, int size,
        /* we won't return a status if write through is not selected - this follows what WfWg does */
        END_PROFILE(SMBwritebraw);
        if (!write_through && total_written==tcount) {
+
+#if RABBIT_PELLET_FIX
                /*
                 * Fix for "rabbit pellet" mode, trigger an early TCP ack by
                 * sending a SMBkeepalive. Thanks to DaveCB at Sun for this. JRA.
                 */
                if (!send_keepalive(smbd_server_fd()))
                        exit_server("reply_writebraw: send of keepalive failed");
+#endif
                return(-1);
        }
 
@@ -3022,21 +3025,8 @@ NTSTATUS rename_internals(connection_struct *conn, char *name, char *newname, BO
         * Tine Smukavec <valentin.smukavec@hermes.si>.
         */
 
-#if 1
-       if (!rc && is_mangled(mask))
-               check_mangled_cache( mask );
-#else
-       if (!rc)
-       {
-               char *unmangled;
-               
-               unmangled = dos_unmangle(mask);
-               if (unmangled)
-                       strncpy(mask, unmangled, strlen(unmangled) + 1);
-                       
-               SAFE_FREE(unmangled);
-       }
-#endif
+       if (!rc && mangle_is_mangled(mask))
+               mangle_check_cache( mask );
 
        has_wild = ms_has_wild(mask);
 
@@ -3044,7 +3034,7 @@ NTSTATUS rename_internals(connection_struct *conn, char *name, char *newname, BO
                /*
                 * No wildcards - just process the one file.
                 */
-               BOOL is_short_name = is_8_3(name, True);
+               BOOL is_short_name = mangle_is_8_3(name, True);
 
                /* Add a terminating '/' to the directory name. */
                pstrcat(directory,"/");
@@ -3439,21 +3429,8 @@ int reply_copy(connection_struct *conn, char *inbuf,char *outbuf, int dum_size,
    * Tine Smukavec <valentin.smukavec@hermes.si>.
    */
 
-#if 1
-       if (!rc && is_mangled(mask))
-               check_mangled_cache( mask );
-#else
-       if (!rc)
-       {
-               char *unmangled;
-               
-               unmangled = dos_unmangle(mask);
-               if (unmangled)
-                       strncpy(mask, unmangled, strlen(unmangled) + 1);
-                       
-               SAFE_FREE(unmangled);
-       }
-#endif
+  if (!rc && mangle_is_mangled(mask))
+         mangle_check_cache( mask );
 
   has_wild = ms_has_wild(mask);
 
index e3912ba939527ea06b54ed202d5773abba945782..c759f56e0cb34aa78dbf03e22ae811ab040eb7b7 100644 (file)
@@ -418,7 +418,7 @@ BOOL reload_services(BOOL test)
                }
        }
 
-       reset_mangled_cache();
+       mangle_reset_cache();
        reset_stat_cache();
 
        /* this forces service parameters to be flushed */
index ca8ad5fa797a7fdf3dbe06fe43309c2673ad7f3b..1972e9c8c8ef0d5b3cf1ed73a4379cd61ee52b93 100644 (file)
@@ -475,7 +475,7 @@ static BOOL get_lanman2_dir_entry(connection_struct *conn,
                if(!(got_match = *got_exact_match = exact_match(fname, mask, case_sensitive)))
                        got_match = mask_match(fname, mask, case_sensitive);
 
-               if(!got_match && !is_8_3(fname, False)) {
+               if(!got_match && !mangle_is_8_3(fname, False)) {
 
                        /*
                         * It turns out that NT matches wildcards against
@@ -486,7 +486,7 @@ static BOOL get_lanman2_dir_entry(connection_struct *conn,
 
                        pstring newname;
                        pstrcpy( newname, fname);
-                       name_map_mangle( newname, True, False, SNUM(conn));
+                       mangle_map( newname, True, False, SNUM(conn));
                        if(!(got_match = *got_exact_match = exact_match(newname, mask, case_sensitive)))
                                got_match = mask_match(newname, mask, case_sensitive);
                }
@@ -549,7 +549,7 @@ static BOOL get_lanman2_dir_entry(connection_struct *conn,
                }
        }
 
-       name_map_mangle(fname,False,True,SNUM(conn));
+       mangle_map(fname,False,True,SNUM(conn));
 
        p = pdata;
        nameptr = p;
@@ -597,7 +597,7 @@ static BOOL get_lanman2_dir_entry(connection_struct *conn,
                        break;
 
                case SMB_FIND_FILE_BOTH_DIRECTORY_INFO:
-                       was_8_3 = is_8_3(fname, True);
+                       was_8_3 = mangle_is_8_3(fname, True);
                        p += 4;
                        SIVAL(p,0,reskey); p += 4;
                        put_long_date(p,cdate); p += 8;
@@ -613,7 +613,7 @@ static BOOL get_lanman2_dir_entry(connection_struct *conn,
                        if (!was_8_3) {
                                pstring mangled_name;
                                pstrcpy(mangled_name, fname);
-                               name_map_mangle(mangled_name,True,True,SNUM(conn));
+                               mangle_map(mangled_name,True,True,SNUM(conn));
                                mangled_name[12] = 0;
                                len = srvstr_push(outbuf, p+2, mangled_name, 24, STR_UPPER);
                                SSVAL(p, 0, len);
@@ -997,8 +997,8 @@ static int call_trans2findfirst(connection_struct *conn,
    * (see PR#13758). JRA.
    */
 
-  if(!is_8_3( mask, False))
-    name_map_mangle(mask, True, True, SNUM(conn));
+  if(!mangle_is_8_3( mask, False))
+    mangle_map(mask, True, True, SNUM(conn));
 
   return(-1);
 }
@@ -1142,14 +1142,14 @@ resume_key = %d resume name = %s continue=%d level = %d\n",
       dname = ReadDirName(dirptr);
 
       /*
-       * Remember, name_map_mangle is called by
+       * Remember, mangle_map is called by
        * get_lanman2_dir_entry(), so the resume name
        * could be mangled. Ensure we do the same
        * here.
        */
 
       if(dname != NULL)
-        name_map_mangle( dname, False, True, SNUM(conn));
+        mangle_map( dname, False, True, SNUM(conn));
 
       if(dname && strcsequal( resume_name, dname))
       {
@@ -1170,14 +1170,14 @@ resume_key = %d resume name = %s continue=%d level = %d\n",
       for(current_pos = start_pos; (dname = ReadDirName(dirptr)) != NULL; SeekDir(dirptr,++current_pos))
       {
         /*
-         * Remember, name_map_mangle is called by
+         * Remember, mangle_map is called by
          * get_lanman2_dir_entry(), so the resume name
          * could be mangled. Ensure we do the same
          * here.
          */
 
         if(dname != NULL)
-          name_map_mangle( dname, False, True, SNUM(conn));
+          mangle_map( dname, False, True, SNUM(conn));
 
         if(dname && strcsequal( resume_name, dname))
         {
@@ -1657,8 +1657,8 @@ static int call_trans2qfilepathinfo(connection_struct *conn,
 
                        pstrcpy(short_name,base_name);
                        /* Mangle if not already 8.3 */
-                       if(!is_8_3(short_name, True)) {
-                               if(!name_map_mangle(short_name,True,True,SNUM(conn)))
+                       if(!mangle_is_8_3(short_name, True)) {
+                               if(!mangle_map(short_name,True,True,SNUM(conn)))
                                        *short_name = '\0';
                        }
                        len = srvstr_push(outbuf, pdata+4, short_name, -1, STR_TERMINATE|STR_UPPER);