rx: Remove RX_CALL_IDLE
[openafs.git] / src / WINNT / afsd / cm_utils.c
index fc1d8fb..ea19f7b 100644 (file)
@@ -1,77 +1,32 @@
 /*
  * Copyright 2000, International Business Machines Corporation and others.
  * All Rights Reserved.
- * 
+ *
  * This software has been released under the terms of the IBM Public
  * License.  For details, see the LICENSE file in the top-level source
  * directory or online at http://www.openafs.org/dl/license10.html
  */
 
+#include <afsconfig.h>
 #include <afs/param.h>
+#include <roken.h>
+
 #include <afs/stds.h>
 
 #include <errno.h>
 #include <windows.h>
+#include <shlwapi.h>
 #include <winsock2.h>
-#ifndef EWOULDBLOCK
-#define EWOULDBLOCK             WSAEWOULDBLOCK
-#define EINPROGRESS             WSAEINPROGRESS
-#define EALREADY                WSAEALREADY
-#define ENOTSOCK                WSAENOTSOCK
-#define EDESTADDRREQ            WSAEDESTADDRREQ
-#define EMSGSIZE                WSAEMSGSIZE
-#define EPROTOTYPE              WSAEPROTOTYPE
-#define ENOPROTOOPT             WSAENOPROTOOPT
-#define EPROTONOSUPPORT         WSAEPROTONOSUPPORT
-#define ESOCKTNOSUPPORT         WSAESOCKTNOSUPPORT
-#define EOPNOTSUPP              WSAEOPNOTSUPP
-#define EPFNOSUPPORT            WSAEPFNOSUPPORT
-#define EAFNOSUPPORT            WSAEAFNOSUPPORT
-#define EADDRINUSE              WSAEADDRINUSE
-#define EADDRNOTAVAIL           WSAEADDRNOTAVAIL
-#define ENETDOWN                WSAENETDOWN
-#define ENETUNREACH             WSAENETUNREACH
-#define ENETRESET               WSAENETRESET
-#define ECONNABORTED            WSAECONNABORTED
-#define ECONNRESET              WSAECONNRESET
-#define ENOBUFS                 WSAENOBUFS
-#define EISCONN                 WSAEISCONN
-#define ENOTCONN                WSAENOTCONN
-#define ESHUTDOWN               WSAESHUTDOWN
-#define ETOOMANYREFS            WSAETOOMANYREFS
-#define ETIMEDOUT               WSAETIMEDOUT
-#define ECONNREFUSED            WSAECONNREFUSED
-#ifdef ELOOP
-#undef ELOOP
-#endif
-#define ELOOP                   WSAELOOP
-#ifdef ENAMETOOLONG
-#undef ENAMETOOLONG
-#endif
-#define ENAMETOOLONG            WSAENAMETOOLONG
-#define EHOSTDOWN               WSAEHOSTDOWN
-#define EHOSTUNREACH            WSAEHOSTUNREACH
-#ifdef ENOTEMPTY
-#undef ENOTEMPTY
-#endif 
-#define ENOTEMPTY               WSAENOTEMPTY
-#define EPROCLIM                WSAEPROCLIM
-#define EUSERS                  WSAEUSERS
-#define EDQUOT                  WSAEDQUOT
-#define ESTALE                  WSAESTALE
-#define EREMOTE                 WSAEREMOTE
-#endif /* EWOULDBLOCK */
-#include <afs/unified_afs.h>
-
 #include <string.h>
 #include <malloc.h>
+#define STRSAFE_NO_DEPRECATE
+#include <strsafe.h>
+
 #include "afsd.h"
 #include <osi.h>
 #include <rx/rx.h>
 
-#define STRSAFE_NO_DEPRECATE
-#include <strsafe.h>
-
+#include <afs/unified_afs.h>
 
 static osi_once_t cm_utilsOnce;
 
@@ -81,6 +36,24 @@ cm_space_t *cm_spaceListp;
 
 static int et2sys[512];
 
+static DWORD cm_TlsRequestSlot = -1;
+
+void cm_utilsInit(void)
+{
+    if (osi_Once(&cm_utilsOnce)) {
+        lock_InitializeRWLock(&cm_utilsLock, "cm_utilsLock", LOCK_HIERARCHY_UTILS_GLOBAL);
+
+        cm_TlsRequestSlot = TlsAlloc();
+
+        osi_EndOnce(&cm_utilsOnce);
+    }
+}
+
+void cm_utilsCleanup(void)
+{
+    TlsFree(cm_TlsRequestSlot);
+}
+
 void
 init_et_to_sys_error(void)
 {
@@ -222,7 +195,7 @@ et_to_sys_error(afs_int32 in)
 
 long cm_MapRPCError(long error, cm_req_t *reqp)
 {
-    if (error == 0) 
+    if (error == 0)
         return 0;
 
     /* If we had to stop retrying, report our saved error code. */
@@ -238,17 +211,27 @@ long cm_MapRPCError(long error, cm_req_t *reqp)
 
     error = et_to_sys_error(error);
 
-    if (error < 0) 
-        error = CM_ERROR_TIMEDOUT;
-    else if (error == EROFS) 
+    if (error == RX_CALL_DEAD ||
+        error == RX_CALL_TIMEOUT ||
+        error == RX_CALL_BUSY ||
+        error == RX_MSGSIZE ||
+        error == VNOSERVICE)
+       error = CM_ERROR_TIMEDOUT;
+    else if (error == RX_INVALID_OPERATION)
+        error = CM_ERROR_INVAL_NET_RESP;
+    else if (error < 0)
+        error = CM_ERROR_UNKNOWN;
+    else if (error == EINVAL)
+        error = CM_ERROR_INVAL;
+    else if (error == EROFS)
         error = CM_ERROR_READONLY;
-    else if (error == EACCES) 
+    else if (error == EACCES)
         error = CM_ERROR_NOACCESS;
-    else if (error == EXDEV) 
+    else if (error == EXDEV)
         error = CM_ERROR_CROSSDEVLINK;
-    else if (error == EEXIST) 
+    else if (error == EEXIST)
         error = CM_ERROR_EXISTS;
-    else if (error == ENOTDIR) 
+    else if (error == ENOTDIR)
         error = CM_ERROR_NOTDIR;
     else if (error == ENOENT)
         error = CM_ERROR_NOSUCHFILE;
@@ -269,6 +252,10 @@ long cm_MapRPCError(long error, cm_req_t *reqp)
         error = CM_ERROR_QUOTA;
     else if (error == VNOVNODE)
         error = CM_ERROR_BADFD;
+    else if (error == VSALVAGE || error == VOFFLINE)
+        error = CM_ERROR_ALLOFFLINE;
+    else if (error == VBUSY || error == VRESTARTING)
+        error = CM_ERROR_ALLBUSY;
     else if (error == EISDIR)
         return CM_ERROR_ISDIR;
     return error;
@@ -276,7 +263,7 @@ long cm_MapRPCError(long error, cm_req_t *reqp)
 
 long cm_MapRPCErrorRmdir(long error, cm_req_t *reqp)
 {
-    if (error == 0) 
+    if (error == 0)
         return 0;
 
     /* If we had to stop retrying, report our saved error code. */
@@ -292,24 +279,41 @@ long cm_MapRPCErrorRmdir(long error, cm_req_t *reqp)
 
     error = et_to_sys_error(error);
 
-    if (error < 0) 
-        error = CM_ERROR_TIMEDOUT;
-    else if (error == EROFS) 
+    if (error == RX_CALL_DEAD ||
+        error == RX_CALL_TIMEOUT ||
+        error == RX_CALL_BUSY ||
+        error == RX_MSGSIZE ||
+        error == VNOSERVICE)
+       error = CM_ERROR_TIMEDOUT;
+    else if (error == VNOVNODE)
+        error = CM_ERROR_BADFD;
+    else if (error == VSALVAGE || error == VOFFLINE)
+        error = CM_ERROR_ALLOFFLINE;
+    else if (error == VBUSY || error == VRESTARTING)
+        error = CM_ERROR_ALLBUSY;
+    else if (error == RX_INVALID_OPERATION)
+        error = CM_ERROR_INVAL_NET_RESP;
+    else if (error < 0)
+        error = CM_ERROR_UNKNOWN;
+    else if (error == EROFS)
         error = CM_ERROR_READONLY;
-    else if (error == ENOTDIR) 
+    else if (error == ENOTDIR)
         error = CM_ERROR_NOTDIR;
-    else if (error == EACCES) 
+    else if (error == EACCES)
         error = CM_ERROR_NOACCESS;
-    else if (error == ENOENT) 
+    else if (error == ENOENT)
         error = CM_ERROR_NOSUCHFILE;
-    else if (error == ENOTEMPTY 
+    else if (error == EINVAL)
+        error = CM_ERROR_INVAL;
+    else if (error == ENOTEMPTY
+              || error == EEXIST
               || error == 17           /* AIX */
               || error == 66           /* SunOS 4, Digital UNIX */
               || error == 93           /* Solaris 2, IRIX */
               || error == 247) /* HP/UX */
         error = CM_ERROR_NOTEMPTY;
     return error;
-}       
+}
 
 long cm_MapVLRPCError(long error, cm_req_t *reqp)
 {
@@ -328,9 +332,21 @@ long cm_MapVLRPCError(long error, cm_req_t *reqp)
 
     error = et_to_sys_error(error);
 
-    if (error < 0) 
+    if (error == RX_CALL_DEAD ||
+        error == RX_CALL_TIMEOUT ||
+        error == RX_CALL_BUSY ||
+        error == RX_MSGSIZE ||
+        error == VNOSERVICE)
        error = CM_ERROR_TIMEDOUT;
-    else if (error == VL_NOENT) 
+    else if (error == RX_INVALID_OPERATION)
+        error = CM_ERROR_INVAL_NET_RESP;
+    else if (error == RX_RESTARTING)
+        error = CM_ERROR_ALLBUSY;
+    else if (error < 0)
+        error = CM_ERROR_UNKNOWN;
+    else if (error == EINVAL)
+        error = CM_ERROR_INVAL;
+    else if (error == VL_NOENT || error == VL_BADNAME)
        error = CM_ERROR_NOSUCHVOLUME;
     return error;
 }
@@ -339,11 +355,8 @@ cm_space_t *cm_GetSpace(void)
 {
        cm_space_t *tsp;
 
-       if (osi_Once(&cm_utilsOnce)) {
-               lock_InitializeRWLock(&cm_utilsLock, "cm_utilsLock");
-               osi_EndOnce(&cm_utilsOnce);
-        }
-        
+        cm_utilsInit();
+
         lock_ObtainWrite(&cm_utilsLock);
        if (tsp = cm_spaceListp) {
                cm_spaceListp = tsp->nextp;
@@ -351,7 +364,7 @@ cm_space_t *cm_GetSpace(void)
         else tsp = (cm_space_t *) malloc(sizeof(cm_space_t));
        (void) memset(tsp, 0, sizeof(cm_space_t));
         lock_ReleaseWrite(&cm_utilsLock);
-        
+
         return tsp;
 }
 
@@ -363,275 +376,759 @@ void cm_FreeSpace(cm_space_t *tsp)
         lock_ReleaseWrite(&cm_utilsLock);
 }
 
-/* This is part of the Microsoft Internationalized Domain Name
-   Mitigation APIs. */
-#include <normalization.h>
-
-int
-(WINAPI *pNormalizeString)( __in NORM_FORM NormForm,
-                            __in_ecount(cwSrcLength) LPCWSTR lpSrcString,
-                            __in int cwSrcLength,
-                            __out_ecount(cwDstLength) LPWSTR lpDstString,
-                            __in int cwDstLength ) = NULL;
+/* characters that are legal in an 8.3 name */
+/*
+ * We used to have 1's for all characters from 128 to 254.  But
+ * the NT client behaves better if we create an 8.3 name for any
+ * name that has a character with the high bit on, and if we
+ * delete those characters from 8.3 names.  In particular, see
+ * Sybase defect 10859.
+ */
+char cm_LegalChars[256] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+#define ISLEGALCHAR(c) ((c) < 256 && (c) > 0 && cm_LegalChars[(c)] != 0)
+
+/* return true iff component is a valid 8.3 name */
+int cm_Is8Dot3(clientchar_t *namep)
+{
+    int sawDot = 0;
+    clientchar_t tc;
+    int charCount = 0;
 
-BOOL
-(WINAPI *pIsNormalizedString)( __in NORM_FORM NormForm,
-                               __in_ecount(cwLength) LPCWSTR lpString,
-                               __in int cwLength ) = NULL;
+    if (namep == NULL || !namep[0])
+        return 0;
 
+    /*
+     * can't have a leading dot;
+     * special case for . and ..
+     */
+    if (namep[0] == '.') {
+        if (namep[1] == 0)
+            return 1;
+        if (namep[1] == '.' && namep[2] == 0)
+            return 1;
+        return 0;
+    }
+    while (tc = *namep++) {
+        if (tc == '.') {
+            /* saw another dot */
+            if (sawDot) return 0;      /* second dot */
+            sawDot = 1;
+            charCount = 0;
+            continue;
+        }
+        if (!ISLEGALCHAR(tc))
+            return 0;
+        charCount++;
+        if (!sawDot && charCount > 8)
+            /* more than 8 chars in name */
+            return 0;
+        if (sawDot && charCount > 3)
+            /* more than 3 chars in extension */
+            return 0;
+    }
+    return 1;
+}
 
-#define NLSDLLNAME "Normaliz.dll"
-#define NLSMAXCCH  1024
-#define NLSERRCCH  8
+/*
+ * Number unparsing map for generating 8.3 names;
+ * The version taken from DFS was on drugs.
+ * You can't include '&' and '@' in a file name.
+ */
+char cm_8Dot3Mapping[42] =
+{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
+ 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
+ 'V', 'W', 'X', 'Y', 'Z', '_', '-', '$', '#', '!', '{', '}'
+};
+int cm_8Dot3MapSize = sizeof(cm_8Dot3Mapping);
+
+void cm_Gen8Dot3NameInt(const fschar_t * longname, cm_dirFid_t * pfid,
+                        clientchar_t *shortName, clientchar_t **shortNameEndp)
+{
+    char number[12];
+    int i, nsize = 0;
+    int vnode = ntohl(pfid->vnode);
+    char *lastDot;
+    int validExtension = 0;
+    char tc, *temp;
+    const char *name;
+
+    /* Unparse the file's vnode number to get a "uniquifier" */
+    do {
+        number[nsize] = cm_8Dot3Mapping[vnode % cm_8Dot3MapSize];
+        nsize++;
+        vnode /= cm_8Dot3MapSize;
+    } while (vnode);
+
+    /*
+     * Look for valid extension.  There has to be a dot, and
+     * at least one of the characters following has to be legal.
+     */
+    lastDot = strrchr(longname, '.');
+    if (lastDot) {
+        temp = lastDot; temp++;
+        while (tc = *temp++)
+            if (ISLEGALCHAR(tc))
+                break;
+        if (tc)
+            validExtension = 1;
+    }
 
-#define AFS_NORM_FORM NormalizationC
+    /* Copy name characters */
+    for (i = 0, name = longname;
+          i < (7 - nsize) && name != lastDot; ) {
+        tc = *name++;
+
+        if (tc == 0)
+            break;
+        if (!ISLEGALCHAR(tc))
+            continue;
+        i++;
+        *shortName++ = toupper(tc);
+    }
 
-long cm_InitNormalization(void)
-{
-    HMODULE h_Nls;
+    /* tilde */
+    *shortName++ = '~';
 
-    if (pNormalizeString != NULL)
-        return 0;
+    /* Copy uniquifier characters */
+    for (i=0; i < nsize; i++) {
+        *shortName++ = number[i];
+    }
 
-    h_Nls = LoadLibrary(NLSDLLNAME);
-    if (h_Nls == INVALID_HANDLE_VALUE) {
-        afsi_log("Can't load " NLSDLLNAME ": LastError=%d", GetLastError());
-        return 1;
+    if (validExtension) {
+        /* Copy extension characters */
+        *shortName++ = *lastDot++;     /* copy dot */
+        for (i = 0, tc = *lastDot++;
+             i < 3 && tc;
+             tc = *lastDot++) {
+            if (ISLEGALCHAR(tc)) {
+                i++;
+                *shortName++ = toupper(tc);
+            }
+        }
     }
 
-    pNormalizeString = GetProcAddress(h_Nls, "NormalizeString");
-    pIsNormalizedString = GetProcAddress(h_Nls, "IsNormalizedString");
+    /* Trailing null */
+    *shortName = 0;
 
-    return (pNormalizeString && pIsNormalizedString);
+    if (shortNameEndp)
+        *shortNameEndp = shortName;
 }
 
-/* \brief Normalize a UTF-16 string.
-
-   If the supplied destination buffer is
-   insufficient or NULL, then a new buffer will be allocated to hold
-   the normalized string.
+void cm_Gen8Dot3NameIntW(const clientchar_t * longname, cm_dirFid_t * pfid,
+                         clientchar_t *shortName, clientchar_t **shortNameEndp)
+{
+    clientchar_t number[12];
+    int i, nsize = 0;
+    int vnode = ntohl(pfid->vnode);
+    clientchar_t *lastDot;
+    int validExtension = 0;
+    clientchar_t tc, *temp;
+    const clientchar_t *name;
+
+    /* Unparse the file's vnode number to get a "uniquifier" */
+    do {
+        number[nsize] = cm_8Dot3Mapping[vnode % cm_8Dot3MapSize];
+        nsize++;
+        vnode /= cm_8Dot3MapSize;
+    } while (vnode);
+
+    /*
+     * Look for valid extension.  There has to be a dot, and
+     * at least one of the characters following has to be legal.
+     */
+    lastDot = cm_ClientStrRChr(longname, '.');
+    if (lastDot) {
+        temp = lastDot; temp++;
+        while (tc = *temp++)
+            if (ISLEGALCHAR(tc))
+                break;
+        if (tc)
+            validExtension = 1;
+    }
 
-   \param[in] src : Source UTF-16 string.  Length is specified in
-       cch_src.
+    /* Copy name characters */
+    for (i = 0, name = longname;
+          i < (7 - nsize) && name != lastDot; ) {
+        tc = *name++;
+
+        if (tc == 0)
+            break;
+        if (!ISLEGALCHAR(tc))
+            continue;
+        i++;
+        *shortName++ = toupper((char) tc);
+    }
 
-   \param[in] cch_src : The character count in cch_src is assumed to
-       be tight and include the terminating NULL character if there is
-       one.  If the NULL is absent, the resulting string will not be
-       NULL terminated.
+    /* tilde */
+    *shortName++ = '~';
 
-   \param[out] ext_dest : The destination buffer.  Can be NULL, in
-       which case *pcch_dest MUST be NULL.
+    /* Copy uniquifier characters */
+    for (i=0; i < nsize; i++) {
+        *shortName++ = number[i];
+    }
 
-   \param[in,out] pcch_dest : On entry *pcch_dest contains a count of
-       characters in the destination buffer.  On exit, it will contain
-       a count of characters that were copied to the destination
-       buffer.
+    if (validExtension) {
+        /* Copy extension characters */
+        *shortName++ = *lastDot++;     /* copy dot */
+        for (i = 0, tc = *lastDot++;
+             i < 3 && tc;
+             tc = *lastDot++) {
+            if (ISLEGALCHAR(tc)) {
+                i++;
+                *shortName++ = toupper(tc);
+            }
+        }
+    }
 
-   Returns a pointer to the buffer containing the normalized string or
-   NULL if the call was unsuccessful.  If the returned destination
-   buffer is different fron the supplied buffer and non-NULL, it
-   should be freed using free().
-*/
-static wchar_t * 
-NormalizeUtf16String(const wchar_t * src, int cch_src, wchar_t * ext_dest, int *pcch_dest)
-{
-    if ((pIsNormalizedString && (*pIsNormalizedString)(AFS_NORM_FORM, src, cch_src)) ||
-        (!pNormalizeString)) {
+    /* Trailing null */
+    *shortName = 0;
 
-        int rv;
-        DWORD gle;
-        int tries = 10;
-        wchar_t * dest;
-        int cch_dest = *pcch_dest;
+    if (shortNameEndp)
+        *shortNameEndp = shortName;
+}
 
-        dest = ext_dest;
+void cm_Gen8Dot3VolNameW(afs_uint32 cell, afs_uint32 volume,
+                         clientchar_t *shortName, clientchar_t **shortNameEndp)
+{
+    clientchar_t number[12];
+    int i, nsize = 0;
+    int validExtension = 0;
+
+    /* Unparse the file's cell and volume numbers */
+    do {
+        number[nsize] = cm_8Dot3Mapping[cell % cm_8Dot3MapSize];
+        nsize++;
+        cell /= cm_8Dot3MapSize;
+    } while (cell);
+    do {
+        number[nsize] = cm_8Dot3Mapping[volume % cm_8Dot3MapSize];
+        nsize++;
+        volume /= cm_8Dot3MapSize;
+    } while (volume && nsize < 8);
+
+    /* Copy uniquifier characters */
+    for (i=0; i < nsize; i++) {
+        *shortName++ = number[i];
+    }
 
-        while (tries-- > 0) {
+    /* Add extension characters */
+    *shortName++ = '.';        /* copy dot */
+    *shortName++ = 'v';
+    *shortName++ = 'o';
+    *shortName++ = 'l';
 
-            rv = (*pNormalizeString)(AFS_NORM_FORM, src, cch_src, dest, cch_dest);
+    /* Trailing null */
+    *shortName = 0;
 
-            if (rv <= 0 && (gle = GetLastError()) != ERROR_SUCCESS) {
-#ifdef DEBUG
-                osi_Log1(afsd_logp, "NormalizeUtf16String error = %d", gle);
-#endif
-                if (gle == ERROR_INSUFFICIENT_BUFFER) {
+    if (shortNameEndp)
+        *shortNameEndp = shortName;
+}
 
-                    /* The buffer wasn't big enough.  We are going to
-                       try allocating one. */
+/*! \brief Compare 'pattern' (containing metacharacters '*' and '?') with the file name 'name'.
 
-                    cch_dest = (-rv) + NLSERRCCH;
-                    goto cont;
+  \note This procedure works recursively calling itself.
 
-                } else {
-                    /* Something else is wrong */
-                    break;
-                }
+  \param[in] pattern string containing metacharacters.
+  \param[in] name File name to be compared with 'pattern'.
 
-            } else if (rv < 0) { /* rv < 0 && gle == ERROR_SUCCESS */
+  \return BOOL : TRUE/FALSE (match/mistmatch)
+*/
+static BOOL
+szWildCardMatchFileName(clientchar_t * pattern, clientchar_t * name, int casefold)
+{
+    clientchar_t upattern[MAX_PATH];
+    clientchar_t uname[MAX_PATH];
+
+    clientchar_t * pename;         // points to the last 'name' character
+    clientchar_t * p;
+    clientchar_t * pattern_next;
+
+    if (casefold) {
+        cm_ClientStrCpy(upattern, lengthof(upattern), pattern);
+        cm_ClientStrUpr(upattern);
+        pattern = upattern;
+
+        cm_ClientStrCpy(uname, lengthof(uname), name);
+        cm_ClientStrUpr(uname);
+        name = uname;
+
+        /* The following translations all work on single byte
+           characters */
+        for (p=upattern; *p; p++) {
+            if (*p == '"') *p = '.'; continue;
+            if (*p == '<') *p = '*'; continue;
+            if (*p == '>') *p = '?'; continue;
+        }
 
-                /* Technically not one of the expected outcomes */
-                break;
+        for (p=uname; *p; p++) {
+            if (*p == '"') *p = '.'; continue;
+            if (*p == '<') *p = '*'; continue;
+            if (*p == '>') *p = '?'; continue;
+        }
+    }
 
-            } else {            /* rv > 0 || (rv == 0 && gle == ERROR_SUCCESS) */
+    pename = cm_ClientCharThis(name + cm_ClientStrLen(name));
+
+    while (*name) {
+        switch (*pattern) {
+        case '?':
+           pattern = cm_ClientCharNext(pattern);
+            if (*name == '.')
+               continue;
+            name = cm_ClientCharNext(name);
+            break;
+
+         case '*':
+            pattern = cm_ClientCharNext(pattern);
+            if (*pattern == '\0')
+                return TRUE;
+
+            pattern_next = cm_ClientCharNext(pattern);
+
+            for (p = pename; p >= name; p = cm_ClientCharPrev(p)) {
+                if (*p == *pattern &&
+                    szWildCardMatchFileName(pattern_next,
+                                            cm_ClientCharNext(p), FALSE))
+                    return TRUE;
+            } /* endfor */
+            if (*pattern == '.' && *pattern_next == '\0') {
+                for (p = name; p && *p; p = cm_ClientCharNext(p))
+                    if (*p == '.')
+                        break;
+                if (p && *p)
+                    return FALSE;
+                return TRUE;
+            }
+            return FALSE;
+
+        default:
+            if (*name != *pattern)
+                return FALSE;
+            pattern = cm_ClientCharNext(pattern);
+            name = cm_ClientCharNext(name);
+            break;
+        } /* endswitch */
+    } /* endwhile */
+
+    /* if all we have left are wildcards, then we match */
+    for (;*pattern; pattern = cm_ClientCharNext(pattern)) {
+       if (*pattern != '*' && *pattern != '?')
+           return FALSE;
+    }
+    return TRUE;
+}
 
-                /* Possibly succeeded */
+/* do a case-folding search of the star name mask with the name in namep.
+ * Return 1 if we match, otherwise 0.
+ */
+int cm_MatchMask(clientchar_t *namep, clientchar_t *maskp, int flags)
+{
+    clientchar_t *newmask, lastchar = _C('\0');
+    int    i, j, casefold, retval;
+    int  star = 0, qmark = 0, dot = 0;
 
-                if (rv == 0) { /* Succeeded and the return string is empty */
-                    *pcch_dest = 0;
-                    return dest;
-                }
+    /* make sure we only match 8.3 names, if requested */
+    if ((flags & CM_FLAG_8DOT3) && !cm_Is8Dot3(namep))
+        return 0;
 
-                if (cch_dest == 0) {
-                    /* Nope.  We only calculated the required size of the buffer */
+    casefold = (flags & CM_FLAG_CASEFOLD) ? 1 : 0;
+
+    /* optimize the pattern:
+     * if there is a mixture of '?' and '*',
+     * for example  the sequence "*?*?*?*"
+     * must be turned into the form "*"
+     */
+    newmask = (clientchar_t *)malloc((cm_ClientStrLen(maskp)+2)*sizeof(clientchar_t));
+    for ( i=0, j=0, star=0, qmark=0; maskp[i]; i++) {
+        lastchar = maskp[i];
+        switch ( maskp[i] ) {
+        case '?':
+        case '>':
+            qmark++;
+            break;
+        case '<':
+        case '*':
+            star++;
+            break;
+        case '.':
+            dot++;
+            /* fallthrough */
+        default:
+            if ( star ) {
+                newmask[j++] = '*';
+            } else if ( qmark ) {
+                while ( qmark-- )
+                    newmask[j++] = '?';
+            }
+            newmask[j++] = maskp[i];
+            star = 0;
+            qmark = 0;
+        }
+    }
+    if ( star ) {
+        newmask[j++] = '*';
+    } else if ( qmark ) {
+        while ( qmark-- )
+            newmask[j++] = '?';
+    }
+    if (dot == 0 && lastchar == '<')
+        newmask[j++] = '.';
+    newmask[j++] = '\0';
 
-                    cch_dest = rv + NLSERRCCH;
-                    goto cont;
-                }
+    retval = szWildCardMatchFileName(newmask, namep, casefold) ? 1:0;
 
-                *pcch_dest = rv;
+    free(newmask);
+    return retval;
+}
 
-                /* Success! */
-                return dest;
-            }
+BOOL
+cm_TargetPerceivedAsDirectory(const fschar_t *target)
+{
+    char        * ext;
 
-        cont:
-            if (dest != ext_dest && dest)
-                free(dest);
-            dest = malloc(cch_dest * sizeof(wchar_t));
-        }
+    ext = PathFindExtension(target);
+    if (!ext[0])
+        return TRUE;
 
-        /* Failed */
+    return FALSE;
+}
 
-        if (dest != ext_dest && dest)
-            free(dest);
+HANDLE
+cm_LoadAfsdHookLib(void)
+{
+    char dllname[260];
+    char *p;
+    HANDLE hLib;
 
-        *pcch_dest = 0;
+    if (!GetModuleFileName(NULL, dllname, sizeof(dllname)))
         return NULL;
+
+    p = strrchr(dllname, '\\');
+    if (p) {
+        p++;
+        strcpy(p, AFSD_HOOK_DLL);
+        hLib = LoadLibrary(dllname);
     } else {
+        hLib = LoadLibrary(AFSD_HOOK_DLL);
+    }
 
-        /* No need to or unable to normalize.  Just copy the string */
-        if (SUCCEEDED(StringCchCopyNW(ext_dest, *pcch_dest, src, cch_src))) {
-            *pcch_dest = cch_src;
-            return ext_dest;
-        } else {
-            *pcch_dest = 0;
-            return NULL;
-        }
+    return hLib;
+}
+
+/*
+ * Obtain the file info structure for the specified file.
+ * If a full path is not specified, the search order is the
+ * same as that used by LoadLibrary().
+ */
+BOOL
+cm_GetOSFileVersion (char *filename, LARGE_INTEGER *liVer)
+{
+    DWORD dwHandle;
+    DWORD dwSize;
+    char* pInfo = NULL;
+    BOOL  rc;
+    UINT uLen;
+    void *pbuf;
+    VS_FIXEDFILEINFO vsf;
+
+    dwSize = GetFileVersionInfoSizeA(filename,&dwHandle);
+    if (dwSize == 0) {
+        rc = FALSE;
+        goto done;
     }
+    pInfo = (char*)malloc(dwSize);
+    if (!pInfo) {
+        rc = FALSE;
+        goto done;
+    }
+    rc = GetFileVersionInfoA(filename, dwHandle, dwSize, pInfo);
+    if (!rc)
+        goto done;
+    rc = VerQueryValueA(pInfo,"\\",&pbuf, &uLen);
+    if (!rc)
+        goto done;
+    memcpy(&vsf, pbuf, sizeof(VS_FIXEDFILEINFO));
+
+    liVer->LowPart = vsf.dwFileVersionLS;
+    liVer->HighPart = vsf.dwFileVersionMS;
+    rc = TRUE;
+
+  done:
+    if (pInfo)
+        free(pInfo);
+    return rc;
 }
 
-/* \brief Normalize a UTF-16 string into a UTF-8 string.
+typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
+typedef BOOL (WINAPI *LPFN_DISABLEWOW64FSREDIRECTION) (PVOID *);
+typedef BOOL (WINAPI *LPFN_REVERTWOW64FSREDIRECTION) (PVOID);
 
-   \param[in] src : Source string.
+BOOL msftSMBRedirectorSupportsExtendedTimeouts(void)
+{
+    static BOOL fChecked = FALSE;
+    static BOOL fSupportsExtendedTimeouts = FALSE;
 
-   \param[in] cch_src : Count of characters in src. If the count includes the
-       NULL terminator, then the resulting string will be NULL
-       terminated.  If it is -1, then src is assumed to be NULL
-       terminated.
+    if (!fChecked)
+    {
+        BOOL isWow64 = FALSE;
+        OSVERSIONINFOEX Version;
+        HANDLE h1 = NULL;
+        LPFN_ISWOW64PROCESS fnIsWow64Process = NULL;
+        LPFN_DISABLEWOW64FSREDIRECTION fnDisableWow64FsRedirection = NULL;
+        LPFN_REVERTWOW64FSREDIRECTION fnRevertWow64FsRedirection = NULL;
+        PVOID Wow64RedirectionState;
+        LARGE_INTEGER fvFile, fvHotFixMin;
+
+        h1 = GetModuleHandle("kernel32.dll"); /* no refcount increase */
+        /*
+         * If we don't find the fnIsWow64Process function then we
+         * are not running in a Wow64 environment
+         */
+        fnIsWow64Process =
+            (LPFN_ISWOW64PROCESS)GetProcAddress(h1, "IsWow64Process");
+
+        memset (&Version, 0x00, sizeof(Version));
+        Version.dwOSVersionInfoSize = sizeof(Version);
+        GetVersionEx((OSVERSIONINFO *) &Version);
+
+        /*
+         * Support is available as hot fixes / service packs on:
+         *   XP SP2
+         *   XP SP3
+         *   2003 and XP64 SP2
+         *   Vista and 2008 SP2
+         *   Win7 and 2008 R2
+         */
+        if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT &&
+            Version.dwMajorVersion >= 5) {
+
+            /* 32-bit XP */
+            if (Version.dwMajorVersion == 5 &&
+                Version.dwMinorVersion == 1) {
+
+                fvHotFixMin.HighPart = (5 << 16) | 1;
+
+                switch (Version.wServicePackMajor) {
+                case 3:
+                    fvHotFixMin.LowPart = (2600 << 16) | 5815;
+                    break;
+                case 2:
+                    fvHotFixMin.LowPart = (2600 << 16) | 3572;
+                    break;
+                default:
+                    fSupportsExtendedTimeouts = (Version.wServicePackMajor > 3);
+                    goto checked;
+                }
+            }
 
-   \param[out] adest : Destination buffer.
+            /* 64-bit XP and Server 2003 */
+            else if (Version.dwMajorVersion == 5 &&
+                     Version.dwMinorVersion == 2) {
 
-   \param[in] cch_adest : Number of characters in the destination buffer.
+                fvHotFixMin.HighPart = (5 << 16) | 2;
 
-   Returns the number of characters stored into cch_adest. This will
-   include the terminating NULL if cch_src included the terminating
-   NULL or was -1.  If this is 0, then the operation was unsuccessful.
- */
-long cm_NormalizeUtf16StringToUtf8(const wchar_t * src, int cch_src,
-                                   char * adest, int cch_adest)
-{
-    if (cch_src < 0) {
-        size_t cch;
+                switch (Version.wServicePackMajor) {
+                case 2:
+                    fvHotFixMin.LowPart = (3790 << 16) | 4479;
+                    break;
+                case 1:
+                    fvHotFixMin.LowPart = (3790 << 16) | 3310;
+                    break;
+                default:
+                    fSupportsExtendedTimeouts = (Version.wServicePackMajor > 2);
+                    goto checked;
+                }
+            }
 
-        if (FAILED(StringCchLengthW(src, NLSMAXCCH, &cch)))
-            return CM_ERROR_TOOBIG;
+            /* Vista and Server 2008 */
+            else if (Version.dwMajorVersion == 6 &&
+                     Version.dwMinorVersion == 0) {
 
-        cch_src = cch+1;
-    }
+                fvHotFixMin.HighPart = (6 << 16) | 0;
 
-    {
-        wchar_t nbuf[NLSMAXCCH];
-        wchar_t * normalized;
-        int cch_norm = NLSMAXCCH;
+                switch (Version.wServicePackMajor) {
+                case 2:
+                    fvHotFixMin.LowPart = (6002 << 16) | 18005;
+                    break;
+                default:
+                    fSupportsExtendedTimeouts = (Version.wServicePackMajor > 2);
+                    goto checked;
+                }
+            }
 
-        normalized = NormalizeUtf16String(src, cch_src, nbuf, &cch_norm);
-        if (normalized) {
-            cch_adest = WideCharToMultiByte(CP_UTF8, 0, normalized, cch_norm,
-                                            adest, cch_adest, NULL, 0);
+            /* Windows 7 and Server 2008 R2 and beyond */
+            else if (Version.dwMajorVersion > 6 ||
+                     Version.dwMajorVersion == 6 &&
+                     Version.dwMinorVersion >= 1) {
+                fSupportsExtendedTimeouts = TRUE;
+                goto checked;
+            }
 
-            if (normalized != nbuf && normalized)
-                free(normalized);
+            /* If wow64, disable wow64 redirection and preserve the existing state */
+            if (fnIsWow64Process &&
+                 fnIsWow64Process(GetCurrentProcess(), &isWow64) &&
+                 isWow64) {
+                fnDisableWow64FsRedirection =
+                    (LPFN_DISABLEWOW64FSREDIRECTION)GetProcAddress(h1, "Wow64DisableWow64FsRedirection");
+                fnRevertWow64FsRedirection =
+                    (LPFN_REVERTWOW64FSREDIRECTION)GetProcAddress(h1, "Wow64RevertWow64FsRedirection");
+                fnDisableWow64FsRedirection(&Wow64RedirectionState);
+            }
 
-            return cch_adest;
+            if (cm_GetOSFileVersion("drivers\\mrxsmb.sys", &fvFile) ||
+                (fvFile.QuadPart >= fvHotFixMin.QuadPart))
+                fSupportsExtendedTimeouts = TRUE;
+
+            /* If wow64, restore the previous redirection state */
+            if (fnIsWow64Process && isWow64) {
+                fnRevertWow64FsRedirection(Wow64RedirectionState);
+            }
+        }
+      checked:
+        fChecked = TRUE;
+    }
 
-        } else {
+    return fSupportsExtendedTimeouts;
+}
 
-            return 0;
+void cm_ResetServerPriority()
+{
+    void * p = TlsGetValue(cm_TlsRequestSlot);
+    if (p) {
+       free(p);
+       TlsSetValue(cm_TlsRequestSlot, NULL);
+       SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
+    }
+}
 
-        }
+void cm_SetRequestStartTime()
+{
+    time_t * tp = TlsGetValue(cm_TlsRequestSlot);
+    if (!tp)
+       tp = malloc(sizeof(time_t));
+    if (tp) {
+       *tp = osi_Time();
+
+       if (!TlsSetValue(cm_TlsRequestSlot, tp))
+           free(tp);
     }
 }
 
+void cm_UpdateServerPriority()
+{
+    time_t *tp = TlsGetValue(cm_TlsRequestSlot);
 
-/* \brief Normalize a UTF-8 string.
+    if (tp) {
+       time_t now = osi_Time();
 
-   \param[in] src String to normalize.
+       /* Give one priority boost for each 15 seconds */
+       SetThreadPriority(GetCurrentThread(), (int)((now - *tp) / 15));
+    }
+}
 
-   \param[in] cch_src : Count of characters in src.  If this value is
-       -1, then src is assumed to be NULL terminated.  The translated
-       string will be NULL terminated only if this is -1 or the count
-       includes the terminating NULL.
 
-   \param[out] adest : Destination string.
+void cm_LargeSearchTimeFromUnixTime(FILETIME *largeTimep, time_t unixTime)
+{
+    // Note that LONGLONG is a 64-bit value
+    LARGE_INTEGER ll;
 
-   \param[in] cch_adest : Number of characters in the destination
-       string.
+#ifdef _USE_32BIT_TIME_T
+    ll.QuadPart = UInt32x32To64(unixTime, 10000000) + 116444736000000000;
+#else
+    ll.QuadPart = unixTime * 10000000 + 116444736000000000;
+#endif
+    largeTimep->dwLowDateTime = ll.LowPart;
+    largeTimep->dwHighDateTime = ll.HighPart;
+}
 
-   Returns the number of characters stored into adest or 0 if the call
-   was unsuccessful.
- */
-long cm_NormalizeUtf8String(const char * src, int cch_src,
-                            char * adest, int cch_adest)
+void cm_UnixTimeFromLargeSearchTime(time_t *unixTimep, FILETIME *largeTimep)
 {
-    wchar_t wsrcbuf[NLSMAXCCH];
-    wchar_t *wnorm;
-    int cch;
-    int cch_norm;
-
-    /* Get some edge cases out first, so we don't have to worry about
-       cch_src being 0 etc. */
-    if (cch_src == 0) {
-        return 0;
-    } else if (*src == '\0') {
-        *adest = '\0';
-        return 1;
-    }
+    // Note that LONGLONG is a 64-bit value
+    LARGE_INTEGER ll;
 
-    cch = MultiByteToWideChar(CP_UTF8, 0, src, cch_src * sizeof(char),
-                             wsrcbuf, NLSMAXCCH);
+    ll.HighPart = largeTimep->dwHighDateTime;
+    ll.LowPart  = largeTimep->dwLowDateTime;
 
-    if (cch == 0) {
-#ifdef DEBUG
-        DebugBreak();
-#endif
-        return 0;
-    }
+    ll.QuadPart -= 116444736000000000;
+    ll.QuadPart /= 10000000;
 
-    cch_norm = 0;
-    wnorm = NormalizeUtf16String(wsrcbuf, cch, NULL, &cch_norm);
-    if (wnorm == NULL) {
-#ifdef DEBUG
-        DebugBreak();
-#endif
-        return 0;
+    *unixTimep = (time_t)ll.QuadPart;
+}
+
+void cm_SearchTimeFromUnixTime(afs_uint32 *searchTimep, time_t unixTime)
+{
+    struct tm *ltp;
+    int dosDate;
+    int dosTime;
+    struct tm localJunk;
+    time_t t = unixTime;
+
+    ltp = localtime(&t);
+
+    /* if we fail, make up something */
+    if (!ltp) {
+        ltp = &localJunk;
+        localJunk.tm_year = 89 - 20;
+        localJunk.tm_mon = 4;
+        localJunk.tm_mday = 12;
+        localJunk.tm_hour = 0;
+        localJunk.tm_min = 0;
+        localJunk.tm_sec = 0;
     }
 
-    cch = WideCharToMultiByte(CP_UTF8, 0, wnorm, cch_norm,
-                              adest, cch_adest * sizeof(char),
-                              NULL, FALSE);
+    dosDate = ((ltp->tm_year-80)<<9) | ((ltp->tm_mon+1) << 5) | (ltp->tm_mday);
+    dosTime = (ltp->tm_hour<<11) | (ltp->tm_min << 5) | (ltp->tm_sec / 2);
+    *searchTimep = (dosDate<<16) | dosTime;
+}
 
-    if (wnorm)
-        free(wnorm);
+void cm_UnixTimeFromSearchTime(time_t *unixTimep, afs_uint32 searchTime)
+{
+    unsigned short dosDate;
+    unsigned short dosTime;
+    struct tm localTm;
+
+    dosDate = (unsigned short) (searchTime & 0xffff);
+    dosTime = (unsigned short) ((searchTime >> 16) & 0xffff);
+
+    localTm.tm_year = 80 + ((dosDate>>9) & 0x3f);
+    localTm.tm_mon = ((dosDate >> 5) & 0xf) - 1;       /* January is 0 in localTm */
+    localTm.tm_mday = (dosDate) & 0x1f;
+    localTm.tm_hour = (dosTime>>11) & 0x1f;
+    localTm.tm_min = (dosTime >> 5) & 0x3f;
+    localTm.tm_sec = (dosTime & 0x1f) * 2;
+    localTm.tm_isdst = -1;                             /* compute whether DST in effect */
+
+    *unixTimep = mktime(&localTm);
+}
 
-    return cch;
+afs_uint32
+cm_NextHighestPowerOf2(afs_uint32 n)
+{
+    n--;
+    n |= n >> 1;
+    n |= n >> 2;
+    n |= n >> 4;
+    n |= n >> 8;
+    n |= n >> 16;
+    n++;
+    return n;
 }