rx: Remove RX_CALL_BUSY
[openafs.git] / src / WINNT / aklog / aklog.c
index 803e270..b72cc78 100644 (file)
@@ -1,6 +1,6 @@
-/* 
+/*
  *  Copyright (C) 1989,2004 by the Massachusetts Institute of Technology
- * 
+ *
  * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
  * distribute this software and its documentation for any purpose and
  * without fee is hereby granted, provided that the above copyright
  * or implied warranty.
  */
 
+/*
+ * Copyright (c) 2007-2008 Secure Endpoints Inc.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Neither the name of the Secure Endpoints Inc. nor the names of its
+ *       contributors may be used to endorse or promote products derived
+ *       from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <afsconfig.h>
+#include <afs/param.h>
+#include <roken.h>
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <errno.h>
 #include <afs/stds.h>
+#include <afs/com_err.h>
+#ifdef HAVE_KRB4
 #include <krb.h>
+#else
+#define REALM_SZ 64
+#define ANAME_SZ 64
+#define INST_SZ  64
+#define KSUCCESS 0
+
+#define CREDENTIALS void
+#endif
 #include <krb5.h>
 #include <afs/ptserver.h>
 #include <afs/ptuser.h>
+#include <afs/pterror.h>
 
 #ifdef WIN32
 #include <windows.h>
 
-#include <cm_config.h>
-#include <auth.h>
-#include <cellconfig.h>
-#include <pioctl_nt.h>
-#include <smb_iocons.h>
-
-#define stat _stat
-#define lstat stat
-#define __S_ISTYPE(mode, mask) (((mode) & _S_IFMT) == (mask))
-#define S_ISDIR(mode)          __S_ISTYPE((mode), _S_IFDIR)
+#include <afs\cm_config.h>
+#include <afs\auth.h>
+#include <afs\cellconfig.h>
+#include <afs\pioctl_nt.h>
+#include <afs\smb_iocons.h>
+#include <WINNT\afsreg.h>
+#include <krbcompat_delayload.h>
 
 #define DONT_HAVE_GET_AD_TKT
 #define MAXSYMLINKS 255
 
+#ifdef HAVE_KRB4
 /* Win32 uses get_krb_err_txt_entry(status) instead of krb_err_txt[status],
 * so we use a bit of indirection like the GNU CVS sources.
 */
 #define krb_err_text(status) get_krb_err_txt_entry(status)
+#endif
 
 #define DRIVECOLON ':'         /* Drive letter separator */
 #define BDIR '\\'              /* Other character that divides directories */
 
-static int 
+static int
 readlink(char *path, char *buf, int buffers)
 {
        return -1;
@@ -59,7 +101,7 @@ readlink(char *path, char *buf, int buffers)
 
 char * getcwd(char*, size_t);
 
-static long 
+static long
 get_cellconfig_callback(void *cellconfig, struct sockaddr_in *addrp, char *namep)
 {
        struct afsconf_cell *cc = (struct afsconf_cell *) cellconfig;
@@ -112,6 +154,7 @@ get_cellconfig_callback(void *cellconfig, struct sockaddr_in *addrp, char *namep
 #define AKLOG_TOKEN 5
 #define AKLOG_BADPATH 6
 #define AKLOG_MISC 7
+#define AKLOG_KFW_NOT_INSTALLED 8
 
 #ifndef NULL
 #define NULL 0
@@ -140,8 +183,6 @@ typedef struct {
 } cellinfo_t;
 
 
-struct afsconf_cell ak_cellconfig; /* General information about the cell */
-
 static char *progname = NULL;  /* Name of this program */
 static int dflag = FALSE;      /* Give debugging information */
 static int noprdb = FALSE;     /* Skip resolving name to id? */
@@ -150,7 +191,55 @@ static linked_list authedcells;    /* List of cells already logged to */
 
 static int usev5 = TRUE;   /* use kerberos 5? */
 static int use524 = FALSE;  /* use krb524? */
-static krb5_ccache _krb425_ccache;
+static krb5_context context = 0;
+static krb5_ccache _krb425_ccache = 0;
+
+void akexit(int exit_code)
+{
+    if (_krb425_ccache)
+        krb5_cc_close(context, _krb425_ccache);
+    if (context)
+        krb5_free_context(context);
+    exit(exit_code);
+}
+
+/* A com_error bodge. The idea here is that this routine lets us lookup
+ * things in the system com_err, if the AFS one just tells us the error
+ * is unknown
+ */
+
+void
+redirect_errors(const char *who, afs_int32 code, const char *fmt, va_list ap)
+{
+    krb5_context context;
+
+    if (who) {
+        fputs(who, stderr);
+        fputs(": ", stderr);
+    }
+    if (code) {
+        int freestr = 0;
+        char *str = (char *)afs_error_message(code);
+        if (strncmp(str, "unknown", strlen(str)) == 0) {
+            if (!krb5_init_context(&context))
+            {
+                str = krb5_get_error_message(NULL, code);
+                freestr = 1;
+            }
+        }
+        fputs(str, stderr);
+        fputs(" ", stderr);
+        if (freestr) {
+            krb5_free_error_message(context, str);
+            krb5_free_context(context);
+        }
+    }
+    if (fmt) {
+        vfprintf(stderr, fmt, ap);
+    }
+    putc('\n', stderr);
+    fflush(stderr);
+}
 
 long GetLocalCell(struct afsconf_dir **pconfigdir, char *local_cell)
 {
@@ -158,36 +247,33 @@ long GetLocalCell(struct afsconf_dir **pconfigdir, char *local_cell)
     {
         fprintf(stderr, "%s: can't get afs configuration (afsconf_Open(%s))\n",
                  progname, AFSDIR_CLIENT_ETC_DIRPATH);
-        exit(AKLOG_AFS);
+        akexit(AKLOG_AFS);
     }
 
     return afsconf_GetLocalCell(*pconfigdir, local_cell, MAXCELLCHARS);
 }
 
-long GetCellInfo(struct afsconf_dir **pconfigdir, char* cell, 
+long GetCellInfo(struct afsconf_dir **pconfigdir, char* cell,
 struct afsconf_cell **pcellconfig)
 {
     return afsconf_GetCellInfo(*pconfigdir, cell, NULL, *pcellconfig);
 }
 
 void CloseConf(struct afsconf_dir **pconfigdir)
-{       
+{
     (void) afsconf_Close(*pconfigdir);
 }
 
 #define ALLOW_REGISTER 1
 void ViceIDToUsername(char *username, char *realm_of_user, char *realm_of_cell,
                       char * cell_to_use, CREDENTIALS *c,
-                      int *status, 
+                      int *status,
                       struct ktc_principal *aclient, struct ktc_principal *aserver, struct ktc_token *atoken)
 {
     static char lastcell[MAXCELLCHARS+1] = { 0 };
     static char confname[512] = { 0 };
     char username_copy[BUFSIZ];
     afs_int32 viceId;                  /* AFS uid of user */
-#ifdef ALLOW_REGISTER
-    afs_int32 id;
-#endif /* ALLOW_REGISTER */
 
     if (confname[0] == '\0') {
         strncpy(confname, AFSDIR_CLIENT_ETC_DIRPATH, sizeof(confname));
@@ -214,10 +300,10 @@ void ViceIDToUsername(char *username, char *realm_of_user, char *realm_of_cell,
     if (dflag)
     {
         if (*status)
-            printf("Error %d\n", *status);
+            printf("pr_SNameToId Error %s\n",  afs_error_message(*status));
         else
             printf("Id %d\n", viceId);
-    }       
+    }
 
     /*
      * This code is taken from cklog -- it lets people
@@ -239,11 +325,13 @@ void ViceIDToUsername(char *username, char *realm_of_user, char *realm_of_cell,
 #ifdef ALLOW_REGISTER
         } else if (strcmp(realm_of_user, realm_of_cell) != 0) {
             int i;
+            int flags = 0;
+            char * smbname = NULL;
+
             if (dflag) {
                 printf("doing first-time registration of %s "
                         "at %s\n", username, cell_to_use);
             }
-            id = 0;
             strncpy(aclient->name, username, MAXKTCNAMELEN - 1);
             aclient->name[MAXKTCNAMELEN - 1] = '\0';
             strcpy(aclient->instance, "");
@@ -255,9 +343,19 @@ void ViceIDToUsername(char *username, char *realm_of_user, char *realm_of_cell,
                     aclient->cell[i] = toupper(aclient->cell[i]);
             }
 
-            if ((*status = ktc_SetToken(aserver, atoken, aclient, 0))) {
-                printf("%s: unable to set tokens for cell %s "
-                        "(status: %d).\n", progname, cell_to_use, status);
+            smbname = getenv("AFS_SMBNAME");
+            if ( smbname ) {
+                strncpy(aclient->smbname, smbname, MAXKTCNAMELEN - 1);
+                aclient->smbname[MAXKTCNAMELEN - 1] = '\0';
+                flags = AFS_SETTOK_LOGON;
+                if (dflag)
+                    printf("obtaining tokens for %s\n", aclient->smbname);
+            }
+
+            if ((*status = ktc_SetToken(aserver, atoken, aclient, flags))) {
+                afs_com_err(progname, *status,
+                             "while obtaining tokens for cell %s\n",
+                             cell_to_use);
                 *status = AKLOG_TOKEN;
                 return ;
             }
@@ -270,25 +368,23 @@ void ViceIDToUsername(char *username, char *realm_of_user, char *realm_of_cell,
              */
 
             if ((*status = pr_Initialize(1L, confname, aserver->cell))) {
-                printf("Error %d\n", status);
+                printf("pr_Initialize Error %s\n",  afs_error_message(*status));
                 return;
             }
 
             /* copy the name because pr_CreateUser lowercases the realm */
             strncpy(username_copy, username, BUFSIZ);
 
-            *status = pr_CreateUser(username, &id);
-
-            /* and restore the name to the original state */
-            strncpy(username, username_copy, BUFSIZ);
+            viceId = 0;
+            *status = pr_CreateUser(username_copy, &viceId);
 
             if (*status) {
                 printf("%s: unable to create remote PTS "
-                        "user %s in cell %s (status: %d).\n", progname,
-                        username, cell_to_use, *status);
+                        "user %s in cell %s (status: %s).\n", progname,
+                        username_copy, cell_to_use, afs_error_message(*status));
             } else {
                 printf("created cross-cell entry for %s (Id %d) at %s\n",
-                        username, viceId, cell_to_use);
+                        username_copy, viceId, cell_to_use);
 #ifdef AFS_ID_TO_NAME
                 snprintf (username, BUFSIZ, "%s (AFS ID %d)", username_copy, (int) viceId);
 #endif /* AFS_ID_TO_NAME */
@@ -354,8 +450,10 @@ int BeginsWithDir(char *str, int colon)
 int des_pcbc_init()
 {
     abort();
+    return 0;   /* avoid warning */
 }
 
+#ifdef HAVE_KRB4
 static int get_cred(char *name, char *inst, char *realm, CREDENTIALS *c)
 {
     int status;
@@ -371,12 +469,13 @@ static int get_cred(char *name, char *inst, char *realm, CREDENTIALS *c)
 #endif
         if (status == KSUCCESS)
             status = krb_get_cred(name, inst, realm, c);
-    }       
+    }
 
     return (status);
 }
+#endif
 
-static int get_v5cred(krb5_context context, 
+static int get_v5cred(krb5_context context,
                       char *name, char *inst, char *realm, CREDENTIALS *c,
                       krb5_creds **creds)
 {
@@ -384,36 +483,52 @@ static int get_v5cred(krb5_context context,
     krb5_error_code r;
     static krb5_principal client_principal = 0;
 
-    memset((char *)&increds, 0, sizeof(increds));
+    if (client_principal) {
+        krb5_free_principal(context, client_principal);
+        client_principal = 0;
+    }
+
+    memset(&increds, 0, sizeof(increds));
 
     if ((r = krb5_build_principal(context, &increds.server,
-                                  strlen(realm), realm,
+                                  (int)strlen(realm), realm,
                                   name,
                                   (inst && strlen(inst)) ? inst : 0,
                                   0))) {
         return((int)r);
     }
 
-    if (!_krb425_ccache)
-        krb5_cc_default(context, &_krb425_ccache);
-    if (!client_principal)
-        krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
+    if (!_krb425_ccache) {
+        if ((r = krb5_cc_default(context, &_krb425_ccache)))
+            return ((int)r);
+    }
+    if (!client_principal) {
+        if ((r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal))) {
+            krb5_cc_close(context, _krb425_ccache);
+            return ((int)r);
+        }
+    }
 
     increds.client = client_principal;
     increds.times.endtime = 0;
        /* Ask for DES since that is what V4 understands */
-    increds.keyblock.enctype = ENCTYPE_DES_CBC_CRC;
+    if (c != NULL)
+       increds.session.keytype = ENCTYPE_DES_CBC_CRC;
 
     r = krb5_get_credentials(context, 0, _krb425_ccache, &increds, creds);
-    if (r)
+    if (r) {
         return((int)r);
-
+    }
+#ifdef HAVE_KRB4
     /* This requires krb524d to be running with the KDC */
     if (c != NULL)
         r = krb5_524_convert_creds(context, *creds, c);
+#endif
+
     return((int)r);
 }
 
+#ifdef HAVE_KRB4
 /* There is no header for this function.  It is supposed to be private */
 int krb_get_admhst(char *h,char *r, int n);
 
@@ -443,10 +558,10 @@ static char *afs_realm_of_cell(struct afsconf_cell *cellconfig)
     }
     return krbrlm;
 }
+#endif
 
-
-/* As of MIT Kerberos 1.6, krb5_get_host_realm() will return the NUL-string 
- * if there is no domain_realm mapping for the hostname's domain.  This is 
+/* As of MIT Kerberos 1.6, krb5_get_host_realm() will return the NUL-string
+ * if there is no domain_realm mapping for the hostname's domain.  This is
  * used as a trigger indicating that referrals should be used within the
  * krb5_get_credentials() call.  However, if the KDC does not support referrals
  * that will result in a KRB5_ERR_HOST_REALM_UNKNOWN error and we will have
@@ -483,7 +598,7 @@ static char *afs_realm_of_cell5(krb5_context context, struct afsconf_cell *cellc
            krb5_free_host_realm( context, krbrlms );
     }
     return krbrlm;
-}      
+}
 
 static char *copy_cellinfo(cellinfo_t *cellinfo)
 {
@@ -496,65 +611,134 @@ static char *copy_cellinfo(cellinfo_t *cellinfo)
 }
 
 
-static char *copy_string(char *string)
-{
-    char *new_string;
-
-    if (new_string = (char *)calloc(strlen(string) + 1, sizeof(char)))
-       (void) strcpy(new_string, string);
-
-    return (new_string);
-}      
-
-
 static int get_cellconfig(char *cell, struct afsconf_cell *cellconfig,
                                                  char *local_cell)
 {
-       int status = AKLOG_SUCCESS;
-       struct afsconf_dir *configdir = 0;
+    int status = AKLOG_SUCCESS;
+    struct afsconf_dir *configdir = 0;
 
-       memset(local_cell, 0, sizeof(local_cell));
-       memset(cellconfig, 0, sizeof(*cellconfig));
+    memset(local_cell, 0, sizeof(local_cell));
+    memset(cellconfig, 0, sizeof(*cellconfig));
 
-       if (GetLocalCell(&configdir, local_cell))
-       {
-               fprintf(stderr, "%s: can't determine local cell.\n", progname);
-               exit(AKLOG_AFS);
-       }
+    if (GetLocalCell(&configdir, local_cell))
+    {
+        fprintf(stderr, "%s: can't determine local cell.\n", progname);
+        akexit(AKLOG_AFS);
+    }
 
-       if ((cell == NULL) || (cell[0] == 0))
-               cell = local_cell;
+    if ((cell == NULL) || (cell[0] == 0))
+        cell = local_cell;
 
-       if (GetCellInfo(&configdir, cell, &cellconfig))
-       {
-               fprintf(stderr, "%s: Can't get information about cell %s.\n",
-                       progname, cell);
-               status = AKLOG_AFS;
-       }
+    if (GetCellInfo(&configdir, cell, &cellconfig))
+    {
+        fprintf(stderr, "%s: Can't get information about cell %s.\n",
+                progname, cell);
+        status = AKLOG_AFS;
+    }
 
+    if (cellconfig->linkedCell)
+        cellconfig->linkedCell = strdup(cellconfig->linkedCell);
 
-       CloseConf(&configdir);
+    CloseConf(&configdir);
 
-       return(status);
+    return(status);
 }
 
 static int get_v5_user_realm(krb5_context context,char *realm)
 {
     static krb5_principal client_principal = 0;
-    int i;
+    krb5_error_code code;
 
-    if (!_krb425_ccache)
-        krb5_cc_default(context, &_krb425_ccache);
-    if (!client_principal)
-        krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
-
-    i = krb5_princ_realm(context, client_principal)->length;
-    if (i < REALM_SZ-1) i = REALM_SZ-1;
-    strncpy(realm,krb5_princ_realm(context, client_principal)->data,i);
-    realm[i] = 0;
+    if (!_krb425_ccache) {
+        code = krb5_cc_default(context, &_krb425_ccache);
+        if (code)
+            return(code);
+    }
+    if (!client_principal) {
+        code = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
+        if (code)
+            return(code);
+    }
+    strncpy(realm, krb5_principal_get_realm(context, client_principal), REALM_SZ - 1);
+    realm[REALM_SZ - 1] = 0;
     return(KSUCCESS);
 }
 
+static void
+copy_realm_of_ticket(krb5_context context, char * dest, size_t destlen, krb5_creds *v5cred) {
+    Ticket ticket;
+    size_t len;
+    int ret;
+
+    ret = decode_Ticket(v5cred->ticket.data, v5cred->ticket.length,
+                        &ticket, &len);
+    if (ret == 0) {
+        strncpy(dest, ticket.realm, destlen - 1);
+        dest[destlen - 1] = '\0';
+
+        free_Ticket(&ticket);
+    }
+}
+
+typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
+static
+int is_wow64()
+{
+    static int init = TRUE;
+    static int bIsWow64 = FALSE;
+
+    if (init) {
+        HMODULE hModule;
+        LPFN_ISWOW64PROCESS fnIsWow64Process = NULL;
+
+        hModule = GetModuleHandle(TEXT("kernel32"));
+        if (hModule) {
+            fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(hModule, "IsWow64Process");
+
+            if (NULL != fnIsWow64Process)
+            {
+                if (!fnIsWow64Process(GetCurrentProcess(),&bIsWow64))
+                {
+                    // on error, assume FALSE.
+                    // in other words, do nothing.
+                }
+            }
+            FreeLibrary(hModule);
+        }
+        init = FALSE;
+    }
+    return bIsWow64;
+}
+
+static int
+accept_dotted_usernames(void)
+{
+    HKEY parmKey;
+    DWORD code, len;
+    DWORD value = 1;
+
+    code = RegOpenKeyEx(HKEY_CURRENT_USER, AFSREG_USER_OPENAFS_SUBKEY,
+                         0, (is_wow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &parmKey);
+    if (code == ERROR_SUCCESS) {
+        len = sizeof(value);
+        code = RegQueryValueEx(parmKey, "AcceptDottedPrincipalNames", NULL, NULL,
+                                (BYTE *) &value, &len);
+        RegCloseKey(parmKey);
+    }
+    if (code != ERROR_SUCCESS) {
+        code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
+                             0, (is_wow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &parmKey);
+        if (code == ERROR_SUCCESS) {
+            len = sizeof(value);
+            code = RegQueryValueEx(parmKey, "AcceptDottedPrincipalNames", NULL, NULL,
+                                    (BYTE *) &value, &len);
+            RegCloseKey (parmKey);
+        }
+    }
+    return value;
+}
+
+
 /*
 * Log to a cell.  If the cell has already been logged to, return without
 * doing anything.  Otherwise, log to it and mark that it has been logged
@@ -572,11 +756,17 @@ static int auth_to_cell(krb5_context context, char *cell, char *realm)
     char cell_to_use[MAXCELLCHARS+1]; /* Cell to authenticate to */
 
     krb5_creds *v5cred = NULL;
+#ifdef HAVE_KRB4
     CREDENTIALS c;
+#endif
     struct ktc_principal aserver;
     struct ktc_principal aclient;
     struct ktc_token atoken, btoken;
+    struct afsconf_cell ak_cellconfig; /* General information about the cell */
     int i;
+    int getLinkedCell = 0;
+    int flags = 0;
+    char * smbname = getenv("AFS_SMBNAME");
 
     /* try to avoid an expensive call to get_cellconfig */
     if (cell && ll_string_check(&authedcells, cell))
@@ -590,19 +780,25 @@ static int auth_to_cell(krb5_context context, char *cell, char *realm)
     memset(instance, 0, sizeof(instance));
     memset(realm_of_user, 0, sizeof(realm_of_user));
     memset(realm_of_cell, 0, sizeof(realm_of_cell));
+    memset(&ak_cellconfig, 0, sizeof(ak_cellconfig));
 
     /* NULL or empty cell returns information on local cell */
     if (status = get_cellconfig(cell, &ak_cellconfig, local_cell))
         return(status);
 
-    strncpy(cell_to_use, ak_cellconfig.name, MAXCELLCHARS);
+  linkedCell:
+    if (getLinkedCell)
+        strncpy(cell_to_use, ak_cellconfig.linkedCell, MAXCELLCHARS);
+    else
+        strncpy(cell_to_use, ak_cellconfig.name, MAXCELLCHARS);
     cell_to_use[MAXCELLCHARS] = 0;
 
     if (ll_string_check(&authedcells, cell_to_use))
     {
         if (dflag)
             printf("Already authenticated to %s (or tried to)\n", cell_to_use);
-        return(AKLOG_SUCCESS);
+        status = AKLOG_SUCCESS;
+        goto done2;
     }
 
     /*
@@ -625,49 +821,110 @@ static int auth_to_cell(krb5_context context, char *cell, char *realm)
      * afs style authenticator.
      */
 
-    if (usev5) 
+    if (usev5)
     { /* using krb5 */
         int retry = 1;
        int realm_fallback = 0;
 
-        if ( strchr(name,'.') != NULL ) {
+        if ((status = get_v5_user_realm(context, realm_of_user)) != KSUCCESS) {
+            char * msg;
+
+            msg = krb5_get_error_message(context, status);
+            fprintf(stderr, "%s: Couldn't determine realm of user: %s\n",
+                    progname, msg);
+            krb5_free_error_message(context, msg);
+            status = AKLOG_KERBEROS;
+            goto done;
+        }
+
+        if ( strchr(name,'.') != NULL && !accept_dotted_usernames()) {
             fprintf(stderr, "%s: Can't support principal names including a dot.\n",
                     progname);
-            return(AKLOG_MISC);
+            status = AKLOG_MISC;
+            goto done;
         }
 
       try_v5:
-       if (realm && realm[0])
-           strcpy(realm_of_cell, realm);
-       else
+       if (realm && realm[0]) {
+            if (dflag)
+                printf("Getting v5 tickets: %s/%s@%s\n", name, instance, realm);
+            status = get_v5cred(context, name, instance, realm,
+#ifdef HAVE_KRB4
+                            use524 ? &c : NULL,
+#else
+                            NULL,
+#endif
+                            &v5cred);
+            strcpy(realm_of_cell, realm);
+        } else {
            strcpy(realm_of_cell,
                    afs_realm_of_cell5(context, &ak_cellconfig, realm_fallback));
 
-       if (dflag)
-            printf("Getting v5 tickets: %s/%s@%s\n", name, instance, realm_of_cell);
-        status = get_v5cred(context, name, instance, realm_of_cell, 
-                            use524 ? &c : NULL, &v5cred);
-       if (status == KRB5_ERR_HOST_REALM_UNKNOWN) {
+            if (retry == 1 && realm_fallback == 0) {
+                /* Only try the realm_of_user once */
+                status = -1;
+                if (dflag)
+                    printf("Getting v5 tickets: %s/%s@%s\n", name, instance, realm_of_user);
+                status = get_v5cred(context, name, instance, realm_of_user,
+#ifdef HAVE_KRB4
+                                     use524 ? &c : NULL,
+#else
+                                     NULL,
+#endif
+                                     &v5cred);
+                if (status == 0) {
+                    /* we have determined that the client realm
+                     * is a valid cell realm
+                     */
+                    strcpy(realm_of_cell, realm_of_user);
+                }
+            }
+
+            if (status != 0 && (!retry || retry && strcmp(realm_of_user,realm_of_cell))) {
+                if (dflag)
+                    printf("Getting v5 tickets: %s/%s@%s\n", name, instance, realm_of_cell);
+                status = get_v5cred(context, name, instance, realm_of_cell,
+#ifdef HAVE_KRB4
+                                     use524 ? &c : NULL,
+#else
+                                     NULL,
+#endif
+                                     &v5cred);
+                if (!status && !strlen(realm_of_cell))
+                    copy_realm_of_ticket(context, realm_of_cell, sizeof(realm_of_cell), v5cred);
+            }
+        }
+
+       if (!realm_fallback && status == KRB5_ERR_HOST_REALM_UNKNOWN) {
            realm_fallback = 1;
            goto try_v5;
        } else if (status == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN) {
-           if (!realm_of_cell[0]) {
+           if (!realm_fallback && !realm_of_cell[0]) {
                realm_fallback = 1;
                goto try_v5;
            }
             if (dflag)
                 printf("Getting v5 tickets: %s@%s\n", name, realm_of_cell);
-            status = get_v5cred(context, name, "", realm_of_cell, 
-                                use524 ? &c : NULL, &v5cred);
+            status = get_v5cred(context, name, "", realm_of_cell,
+#ifdef HAVE_KRB4
+                                use524 ? &c : NULL,
+#else
+                                NULL,
+#endif
+                                &v5cred);
+            if (!status && !strlen(realm_of_cell))
+                copy_realm_of_ticket(context, realm_of_cell, sizeof(realm_of_cell), v5cred);
        }
+
         if ( status == KRB5KRB_AP_ERR_MSG_TYPE && retry ) {
             retry = 0;
            realm_fallback = 0;
             goto try_v5;
-        }       
-    }       
-    else 
+        }
+    }
+    else
     {
+#ifdef HAVE_KRB4
        if (realm && realm[0])
            strcpy(realm_of_cell, realm);
        else
@@ -689,18 +946,31 @@ static int auth_to_cell(krb5_context context, char *cell, char *realm)
                 printf("Getting tickets: %s@%s\n", name, realm_of_cell);
             status = get_cred(name, "", realm_of_cell, &c);
         }
-    } 
+#else
+        status = AKLOG_MISC;
+        goto done;
+#endif
+    }
 
-    /* TODO: get k5 error text */
     if (status != KSUCCESS)
     {
+        char * msg = NULL;
         if (dflag)
             printf("Kerberos error code returned by get_cred: %d\n", status);
+
+        if (usev5) {
+            msg = krb5_get_error_message(context, status);
+        }
+#ifdef HAVE_KRB4
+        else
+            msg = krb_err_text(status);
+#endif
         fprintf(stderr, "%s: Couldn't get %s AFS tickets: %s\n",
-                 progname, cell_to_use, 
-                 (usev5)?"":
-                 krb_err_text(status));
-        return(AKLOG_KERBEROS);
+                progname, cell_to_use, msg?msg:"(unknown error)");
+        if (usev5)
+            krb5_free_error_message(context, msg);
+        status = AKLOG_KERBEROS;
+        goto done;
     }
 
     strncpy(aserver.name, AFSKEY, MAXKTCNAMELEN - 1);
@@ -714,16 +984,17 @@ static int auth_to_cell(krb5_context context, char *cell, char *realm)
          */
         char * p;
         int len;
-        
-        len = min(v5cred->client->data[0].length,MAXKTCNAMELEN - 1);
-        strncpy(username, v5cred->client->data[0].data, len);
-        username[len] = '\0';
+        const char *un;
 
-        if ( v5cred->client->length > 1 ) {
+        un = krb5_principal_get_comp_string(context, v5cred->client, 0);
+        strncpy(username, un, MAXKTCNAMELEN - 1);
+        username[MAXKTCNAMELEN - 1] = '\0';
+
+        if ( krb5_principal_get_num_comp(context, v5cred->client) > 1 ) {
             strcat(username, ".");
             p = username + strlen(username);
-            len = min(v5cred->client->data[1].length,MAXKTCNAMELEN - strlen(username) - 1);
-            strncpy(p, v5cred->client->data[1].data, len);
+            len = (unsigned int)(MAXKTCNAMELEN - strlen(username) - 1);
+            strncpy(p, krb5_principal_get_comp_string(context, v5cred->client, 1), len);
             p[len] = '\0';
         }
 
@@ -731,10 +1002,16 @@ static int auth_to_cell(krb5_context context, char *cell, char *realm)
         atoken.kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
         atoken.startTime = v5cred->times.starttime;
         atoken.endTime = v5cred->times.endtime;
-        memcpy(&atoken.sessionKey, v5cred->keyblock.contents, v5cred->keyblock.length);
+       if (tkt_DeriveDesKey(v5cred->session.keytype,
+                            v5cred->session.keyvalue.data,
+                            v5cred->session.keyvalue.length, &atoken.sessionKey)) {
+           status = AKLOG_MISC;
+           goto done;
+       }
         atoken.ticketLen = v5cred->ticket.length;
         memcpy(atoken.ticket, v5cred->ticket.data, atoken.ticketLen);
     } else {
+#ifdef HAVE_KRB4
         strcpy (username, c.pname);
         if (c.pinst[0])
         {
@@ -750,50 +1027,59 @@ static int auth_to_cell(krb5_context context, char *cell, char *realm)
         memcpy(&atoken.sessionKey, c.session, 8);
         atoken.ticketLen = c.ticket_st.length;
         memcpy(atoken.ticket, c.ticket_st.dat, atoken.ticketLen);
+#else
+        status = AKLOG_MISC;
+        goto done;
+#endif
     }
 
     if (!force &&
-         !ktc_GetToken(&aserver, &btoken, sizeof(btoken), &aclient) &&
-         atoken.kvno == btoken.kvno &&
-         atoken.ticketLen == btoken.ticketLen &&
-         !memcmp(&atoken.sessionKey, &btoken.sessionKey, sizeof(atoken.sessionKey)) &&
-         !memcmp(atoken.ticket, btoken.ticket, atoken.ticketLen))
-    {       
+        !smbname &&
+        !ktc_GetToken(&aserver, &btoken, sizeof(btoken), &aclient) &&
+        atoken.kvno == btoken.kvno &&
+        atoken.ticketLen == btoken.ticketLen &&
+        !memcmp(&atoken.sessionKey, &btoken.sessionKey, sizeof(atoken.sessionKey)) &&
+        !memcmp(atoken.ticket, btoken.ticket, atoken.ticketLen))
+    {
         if (dflag)
             printf("Identical tokens already exist; skipping.\n");
-        return 0;
+        status = AKLOG_SUCCESS;
+        goto done2;
     }
 
     if (noprdb)
     {
         if (dflag)
             printf("Not resolving name %s to id (-noprdb set)\n", username);
-    }       
-    else    
+    }
+    else
     {
-        if (usev5) {
-            if((status = get_v5_user_realm(context, realm_of_user)) != KSUCCESS) {
-                fprintf(stderr, "%s: Couldn't determine realm of user: %d\n",
-                         progname, status);
-                return(AKLOG_KERBEROS);
-            }
-        } else {
+        if (!usev5) {
+#ifdef HAVE_KRB4
             if ((status = krb_get_tf_realm(TKT_FILE, realm_of_user)) != KSUCCESS)
             {
                 fprintf(stderr, "%s: Couldn't determine realm of user: %s)",
                          progname, krb_err_text(status));
-                return(AKLOG_KERBEROS);
+                status = AKLOG_KERBEROS;
+                goto done;
             }
+#else
+            status = AKLOG_MISC;
+            goto done;
+#endif
         }
 
-        /* For Khimaira we want to always append the realm to the name */
-        if (1 /* strcmp(realm_of_user, realm_of_cell) */)
-        {
-            strcat(username, "@");
-            strcat(username, realm_of_user);
-        }
+        /* For Network Identity Manager append the realm to the name */
+        strcat(username, "@");
+        strcat(username, realm_of_user);
 
-        ViceIDToUsername(username, realm_of_user, realm_of_cell, cell_to_use, &c, &status, &aclient, &aserver, &atoken);
+        ViceIDToUsername(username, realm_of_user, realm_of_cell, cell_to_use,
+#ifdef HAVE_KRB4
+                          &c,
+#else
+                          NULL,
+#endif
+                          &status, &aclient, &aserver, &atoken);
     }
 
     if (dflag)
@@ -805,29 +1091,57 @@ static int auth_to_cell(krb5_context context, char *cell, char *realm)
      */
     strncpy(aclient.name, username, MAXKTCNAMELEN - 1);
     strcpy(aclient.instance, "");
-    
+
     if (usev5 && !use524) {
-        int len = min(v5cred->client->realm.length,MAXKTCNAMELEN - 1);
-        strncpy(aclient.cell, v5cred->client->realm.data, len);
-        aclient.cell[len] = '\0';
-    } else
+        strncpy(aclient.cell,
+                krb5_principal_get_realm(context, v5cred->client), MAXKTCNAMELEN - 1);
+        aclient.cell[MAXKTCNAMELEN - 1] = '\0';
+    }
+#ifdef HAVE_KRB4
+    else
        strncpy(aclient.cell, c.realm, MAXKTCREALMLEN - 1);
+#endif
 
     for ( i=0; aclient.cell[i]; i++ ) {
         if ( islower(aclient.cell[i]) )
             aclient.cell[i] = toupper(aclient.cell[i]);
     }
 
-    if (dflag)
-        printf("Getting tokens.\n");
-    if (status = ktc_SetToken(&aserver, &atoken, &aclient, 0))
+    if ( smbname ) {
+        if (dflag)
+            printf("Setting tokens for %s.\n", smbname);
+
+        strncpy(aclient.smbname, smbname, MAXKTCNAMELEN - 1);
+        aclient.smbname[MAXKTCNAMELEN - 1] = '\0';
+        flags = AFS_SETTOK_LOGON;
+    } else {
+        if (dflag)
+            printf("Setting tokens.\n");
+    }
+
+    if (status = ktc_SetToken(&aserver, &atoken, &aclient, flags))
     {
-        fprintf(stderr,
-                 "%s: unable to obtain tokens for cell %s (status: %d).\n",
-                 progname, cell_to_use, status);
+        afs_com_err(progname, status,
+                     "while setting token for cell %s\n",
+                     cell_to_use);
         status = AKLOG_TOKEN;
     }
 
+  done2:
+    if (ak_cellconfig.linkedCell && !getLinkedCell) {
+        getLinkedCell = 1;
+        goto linkedCell;
+    }
+
+  done:
+#if 0
+    /*
+     * intentionally leak the linkedCell field because it was allocated
+     * using a different C RTL version.
+     */
+    if (ak_cellconfig.linkedCell)
+        free(ak_cellconfig.linkedCell);
+#endif
     return(status);
 }
 
@@ -856,7 +1170,7 @@ static int get_afs_mountpoint(char *file, char *mountpoint, int size)
     memset(cellname, 0, sizeof(cellname));
 
     vio.in = last_component;
-    vio.in_size = strlen(last_component)+1;
+    vio.in_size = (long)strlen(last_component)+1;
     vio.out_size = size;
     vio.out = mountpoint;
 
@@ -865,7 +1179,7 @@ static int get_afs_mountpoint(char *file, char *mountpoint, int size)
         if (strchr(mountpoint, VOLMARKER) == NULL)
         {
             vio.in = file;
-            vio.in_size = strlen(file) + 1;
+            vio.in_size = (long)strlen(file) + 1;
             vio.out_size = sizeof(cellname);
             vio.out = cellname;
 
@@ -882,7 +1196,7 @@ static int get_afs_mountpoint(char *file, char *mountpoint, int size)
     else {
         return(FALSE);
     }
-}       
+}
 
 /*
 * This routine each time it is called returns the next directory
@@ -928,8 +1242,8 @@ static char *next_path(char *origpath)
     {
         while (BeginsWithDir(last_comp, FALSE))
             strncat(pathtocheck, last_comp++, 1);
-        len = (elast_comp = LastComponent(last_comp))
-            ? elast_comp - last_comp : strlen(last_comp);
+        len = (int) ((elast_comp = LastComponent(last_comp))
+            ? elast_comp - last_comp : strlen(last_comp));
         strncat(pathtocheck, last_comp, len);
         memset(linkbuf, 0, sizeof(linkbuf));
         if (link = (readlink(pathtocheck, linkbuf, sizeof(linkbuf)) > 0))
@@ -937,7 +1251,7 @@ static char *next_path(char *origpath)
             if (++symlinkcount > MAXSYMLINKS)
             {
                 fprintf(stderr, "%s: %s\n", progname, strerror(ELOOP));
-                exit(AKLOG_BADPATH);
+                akexit(AKLOG_BADPATH);
             }
             memset(tmpbuf, 0, sizeof(tmpbuf));
             if (elast_comp)
@@ -975,7 +1289,7 @@ static char *next_path(char *origpath)
         }
         else
             last_comp = elast_comp;
-    }       
+    }
     while(link);
 
     return(pathtocheck);
@@ -1007,16 +1321,16 @@ static int auth_to_path(krb5_context context, char *path)
             fprintf(stderr, "Unable to find current working directory:\n");
             fprintf(stderr, "%s\n", pathtocheck);
             fprintf(stderr, "Try an absolute pathname.\n");
-            exit(AKLOG_BADPATH);
+            akexit(AKLOG_BADPATH);
         }
         else
         {
             /* in WIN32, if getcwd returns a root dir (eg: c:\), the returned string
             * will already have a trailing slash ('\'). Otherwise, the string will
             * end in the last directory name */
-#ifdef WIN32    
+#ifdef WIN32
             if(pathtocheck[strlen(pathtocheck) - 1] != BDIR)
-#endif  
+#endif
                 strcat(pathtocheck, DIRSTRING);
             strcat(pathtocheck, path);
         }
@@ -1086,20 +1400,55 @@ static void usage(void)
              "[-d] [[-cell | -c] cell [-k krb_realm]] ",
              "[[-p | -path] pathname]\n",
              "    [-noprdb] [-force]\n",
+#ifdef HAVE_KRB4
              "    [-5 [-m]| -4]\n"
+#else
+             "    [-5]\n"
+#endif
              );
     fprintf(stderr, "    -d gives debugging information.\n");
     fprintf(stderr, "    krb_realm is the kerberos realm of a cell.\n");
     fprintf(stderr, "    pathname is the name of a directory to which ");
     fprintf(stderr, "you wish to authenticate.\n");
     fprintf(stderr, "    -noprdb means don't try to determine AFS ID.\n");
-    fprintf(stderr, "    -5 or -4 selects whether to use Kerberos V or Kerberos IV.\n"
-                    "       (default is Kerberos V)\n");
-    fprintf(stderr, "       -m means use krb524d to convert Kerberos V tickets.\n");
+#ifdef HAVE_KRB4
+    fprintf(stderr, "    -5 or -4 selects whether to use Kerberos v5 or Kerberos v4.\n"
+                    "       (default is Kerberos v5)\n");
+    fprintf(stderr, "       -m means use krb524d to convert Kerberos v5 tickets.\n");
+#else
+    fprintf(stderr, "    -5 use Kerberos v5.\n"
+                    "       (only Kerberos v5 is available)\n");
+#endif
     fprintf(stderr, "    No commandline arguments means ");
     fprintf(stderr, "authenticate to the local cell.\n");
     fprintf(stderr, "\n");
-    exit(AKLOG_USAGE);
+    akexit(AKLOG_USAGE);
+}
+
+void
+validate_krb5_availability(void)
+{
+    if (!DelayLoadHeimdal()) {
+        fprintf(stderr, "Kerberos for Windows or Heimdal is not available.\n");
+        akexit(AKLOG_KFW_NOT_INSTALLED);
+    }
+}
+
+void
+validate_krb4_availability(void)
+{
+#ifdef HAVE_KRB4
+    HINSTANCE h = LoadLibrary("krbv4w32.dll");
+    if (h)
+        FreeLibrary(h);
+    else {
+        fprintf(stderr, "Kerberos for Windows library krbv4w32.dll is not available.\n");
+        akexit(AKLOG_KFW_NOT_INSTALLED);
+    }
+#else
+    fprintf(stderr, "Kerberos v4 is not available in this build of aklog.\n");
+    akexit(AKLOG_USAGE);
+#endif
 }
 
 int main(int argc, char *argv[])
@@ -1125,8 +1474,6 @@ int main(int argc, char *argv[])
     linked_list paths;         /* List of paths to log to */
     ll_node *cur_node;
 
-    krb5_context context = 0;
-
     memset(&cellinfo, 0, sizeof(cellinfo));
 
     memset(realm, 0, sizeof(realm));
@@ -1152,17 +1499,19 @@ int main(int argc, char *argv[])
             dflag++;
         else if (strcmp(argv[i], "-5") == 0)
             usev5++;
+#ifdef HAVE_KRB4
         else if (strcmp(argv[i], "-m") == 0)
             use524++;
         else if (strcmp(argv[i], "-4") == 0)
             usev5 = 0;
+#endif
         else if (strcmp(argv[i], "-noprdb") == 0)
             noprdb++;
         else if (strcmp(argv[i], "-force") == 0)
             force++;
         else if (((strcmp(argv[i], "-cell") == 0) ||
                    (strcmp(argv[i], "-c") == 0)) && !pmode)
-        {       
+        {
             if (++i < argc)
             {
                 cmode++;
@@ -1173,7 +1522,7 @@ int main(int argc, char *argv[])
         }
         else if (((strcmp(argv[i], "-path") == 0) ||
                    (strcmp(argv[i], "-p") == 0)) && !cmode)
-        {       
+        {
             if (++i < argc)
             {
                 pmode++;
@@ -1222,14 +1571,14 @@ int main(int argc, char *argv[])
                 else
                 {
                     fprintf(stderr, "%s: failure copying cellinfo.\n", progname);
-                    exit(AKLOG_MISC);
+                    akexit(AKLOG_MISC);
                 }
             }
             else
             {
                 fprintf(stderr, "%s: failure adding cell to cells list.\n",
                          progname);
-                exit(AKLOG_MISC);
+                akexit(AKLOG_MISC);
             }
             memset(&cellinfo, 0, sizeof(cellinfo));
             cmode = FALSE;
@@ -1242,28 +1591,38 @@ int main(int argc, char *argv[])
             if (cur_node = ll_add_node(&paths, ll_tail))
             {
                 char *new_path;
-                if (new_path = copy_string(path))
+                if (new_path = strdup(path))
                     ll_add_data(cur_node, new_path);
                 else
                 {
                     fprintf(stderr, "%s: failure copying path name.\n",
                              progname);
-                    exit(AKLOG_MISC);
+                    akexit(AKLOG_MISC);
                 }
             }
             else
             {
                 fprintf(stderr, "%s: failure adding path to paths list.\n",
                          progname);
-                exit(AKLOG_MISC);
+                akexit(AKLOG_MISC);
             }
             pmode = FALSE;
             memset(path, 0, sizeof(path));
         }
     }
 
-    if(usev5)
-        krb5_init_context(&context);
+    if (!noprdb)
+        initialize_PT_error_table();
+
+    if (usev5) {
+        validate_krb5_availability();
+        if (krb5_init_context(&context))
+            return(AKLOG_KERBEROS);
+        if (krb5_enctype_valid(context, ETYPE_DES_CBC_CRC))
+            krb5_enctype_enable(context, ETYPE_DES_CBC_CRC);
+    } else
+        validate_krb4_availability();
+    afs_set_com_err_hook(redirect_errors);
 
     /* If nothing was given, log to the local cell. */
     if ((cells.nelements + paths.nelements) == 0)
@@ -1274,15 +1633,15 @@ int main(int argc, char *argv[])
         for (cur_node = cells.first; cur_node; cur_node = cur_node->next)
         {
             memcpy(&cellinfo, cur_node->data, sizeof(cellinfo));
-            if (status = auth_to_cell(context, 
+            if (status = auth_to_cell(context,
                                        cellinfo.cell, cellinfo.realm))
                 somethingswrong++;
-        }       
+        }
 
         /* Then, log to all paths in the paths list */
         for (cur_node = paths.first; cur_node; cur_node = cur_node->next)
         {
-            if (status = auth_to_path(context, 
+            if (status = auth_to_path(context,
                                        cur_node->data))
                 somethingswrong++;
         }
@@ -1294,10 +1653,7 @@ int main(int argc, char *argv[])
         */
         if (somethingswrong && ((cells.nelements + paths.nelements) > 1))
             status = AKLOG_SOMETHINGSWRONG;
-    }       
-
-    if(usev5)
-        krb5_free_context(context);
+    }
 
-    exit(status);
-}       
+    akexit(status);
+}