Fix aklog segfault
[openafs.git] / src / aklog / aklog.c
index f5a62be..d3bb44c 100644 (file)
@@ -88,7 +88,9 @@
 #include <afs/venus.h>
 #include <afs/ptserver.h>
 #include <afs/ptuser.h>
+#include <afs/pterror.h>
 #include <afs/dirpath.h>
+#include <afs/afsutil.h>
 
 #include "aklog.h"
 #include "linked_list.h"
@@ -144,9 +146,6 @@ typedef struct {
     char realm[REALM_SZ];
 } cellinfo_t;
 
-struct afsconf_cell ak_cellconfig; /* General information about the cell */
-static char linkedcell[MAXCELLCHARS+1];
-static char linkedcell2[MAXCELLCHARS+1];
 static krb5_ccache  _krb425_ccache = NULL;
 
 /*
@@ -163,7 +162,7 @@ extern char *afs_realm_of_cell(krb5_context, struct afsconf_cell *, int);
 static int isdir(char *, unsigned char *);
 static krb5_error_code get_credv5(krb5_context context, char *, char *,
                                  char *, krb5_creds **);
-static int get_user_realm(krb5_context, char *);
+static int get_user_realm(krb5_context, char **);
 
 #define TRYAGAIN(x) (x == AKLOG_TRYAGAIN || \
                     x == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN || \
@@ -334,10 +333,17 @@ redirect_errors(const char *who, afs_int32 code, const char *fmt, va_list ap)
     if (code) {
        const char *str = afs_error_message(code);
        if (strncmp(str, "unknown", strlen("unknown")) == 0) {
+#ifdef HAVE_KRB5_SVC_GET_MSG
+           krb5_svc_get_msg(code,&str);
+#else
            str = error_message(code);
+#endif
        }
        fputs(str, stderr);
        fputs(" ", stderr);
+#ifdef HAVE_KRB5_SVC_GET_MSG
+       krb5_free_string(str);
+#endif
     }
     if (fmt) {
        vfprintf(stderr, fmt, ap);
@@ -346,6 +352,16 @@ redirect_errors(const char *who, afs_int32 code, const char *fmt, va_list ap)
     fflush(stderr);
 }
 
+static void
+afs_dprintf(char *fmt, ...) {
+    va_list ap;
+
+    va_start(ap, fmt);
+    if (dflag)
+       vprintf(fmt, ap);
+    va_end(ap);
+}
+
 static char *
 copy_cellinfo(cellinfo_t *cellinfo)
 {
@@ -359,15 +375,20 @@ copy_cellinfo(cellinfo_t *cellinfo)
 
 
 static int
-get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char *local_cell,
-              char *linkedcell)
+get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char **local_cell)
 {
     int status = AKLOG_SUCCESS;
     struct afsconf_dir *configdir;
 
-    memset(local_cell, 0, sizeof(local_cell));
     memset(cellconfig, 0, sizeof(*cellconfig));
 
+    *local_cell = malloc(MAXCELLCHARS);
+    if (*local_cell == NULL) {
+       fprintf(stderr, "%s: can't allocate memory for local cell name\n",
+               progname);
+       exit(AKLOG_AFS);
+    }
+
     if (!(configdir = afsconf_Open(AFSDIR_CLIENT_ETC_DIRPATH))) {
        fprintf(stderr, 
                "%s: can't get afs configuration (afsconf_Open(%s))\n",
@@ -375,75 +396,594 @@ get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char *local_cell,
        exit(AKLOG_AFS);
     }
 
-    if (afsconf_GetLocalCell(configdir, local_cell, MAXCELLCHARS)) {
+    if (afsconf_GetLocalCell(configdir, *local_cell, MAXCELLCHARS)) {
        fprintf(stderr, "%s: can't determine local cell.\n", progname);
        exit(AKLOG_AFS);
     }
 
     if ((cell == NULL) || (cell[0] == 0))
-       cell = local_cell;
+       cell = *local_cell;
 
-    linkedcell[0] = '\0';
+    /* XXX - This function modifies 'cell' by passing it through lcstring */
     if (afsconf_GetCellInfo(configdir, cell, NULL, cellconfig)) {
        fprintf(stderr, "%s: Can't get information about cell %s.\n",
                progname, cell);
        status = AKLOG_AFS;
     }
 
-    if (cellconfig->linkedCell)
-       strncpy(linkedcell,cellconfig->linkedCell,MAXCELLCHARS);
-
     afsconf_Close(configdir);
 
     return(status);
 }
 
+static char *
+extract_realm(krb5_context context, krb5_principal princ) {
+    int len;
+    char *realm;
+
+    len = realm_len(context, princ);
+    if (len > REALM_SZ-1)
+       len = REALM_SZ-1;
+
+    realm = malloc(sizeof(char) * (len+1));
+    if (realm == NULL)
+       return NULL;
+
+    strncpy(realm, realm_data(context, princ), len);
+    realm[len] = '\0';
+
+    return realm;
+}
+
+static int
+get_realm_from_cred(krb5_context context, krb5_creds *v5cred, char **realm) {
+#if !defined(HEIMDAL) && defined(HAVE_KRB5_DECODE_TICKET)
+    krb5_error_code code;
+    krb5_ticket *ticket;
+
+    *realm = NULL;
+
+    code = krb5_decode_ticket(&v5cred->ticket, &ticket);
+    if (code)
+       return code;
+
+    *realm = extract_realm(context, ticket->server);
+    if (*realm == NULL)
+       code = ENOMEM;
+
+    krb5_free_ticket(context, ticket);
+
+    return code;
+#else
+    *realm = NULL;
+    return 0;
+#endif
+}
+
+/*!
+ * Get a Kerberos service ticket to use as the base of an rxkad token for
+ * a given AFS cell.
+ *
+ * @param[in] context
+ *     An initialized Kerberos v5 context
+ * @param[in] realm
+ *     The realm to look in for the service principal. If NULL, then the
+ *     realm is determined from the cell name or the user's credentials
+ *     (see below for the heuristics used)
+ * @param[in] cell
+ *     The cell information for the cell to obtain a ticket for
+ * @param[out] v5cred
+ *     A Kerberos credentials structure containing the ticket acquired
+ *     for the cell. This is a dynamically allocated structure, which
+ *     should be freed by using the appropriate Kerberos API function.
+ * @param[out] realmUsed
+ *     The realm in which the cell's service principal was located. If
+ *     unset, then the principal was located in the same realm as the
+ *     current user. This is a malloc'd string which should be freed
+ *     by the caller.
+ *
+ * @returns
+ *     0 on success, an error value upon failure
+ *
+ * @notes
+ *     This code tries principals in the following, much debated,
+ *     order:
+ *
+ *     If the realm is specified on the command line we do
+ *        - afs/cell@COMMAND-LINE-REALM
+ *        - afs@COMMAND-LINE-REALM
+ *
+ *     Otherwise, we do
+ *        - afs/cell@REALM-FROM-USERS-PRINCIPAL
+ *        - afs/cell@krb5_get_host_realm(db-server)
+ *       Then, if krb5_get_host_realm(db-server) is non-empty
+ *          - afs@ krb5_get_host_realm(db-server)
+ *       Otherwise
+ *          - afs/cell@ upper-case-domain-of-db-server
+ *          - afs@ upper-case-domain-of-db-server
+ *
+ *     In all cases, the 'afs@' variant is only tried where the
+ *     cell and the realm match case-insensitively.
+ */
+
+static int
+rxkad_get_ticket(krb5_context context, char *realm,
+                struct afsconf_cell *cell,
+                krb5_creds **v5cred, char **realmUsed) {
+    char *realm_of_cell = NULL;
+    char *realm_of_user = NULL;
+    char *realm_from_princ = NULL;
+    int status;
+    int retry;
+
+    *realmUsed = NULL;
+
+    if ((status = get_user_realm(context, &realm_of_user))) {
+       fprintf(stderr, "%s: Couldn't determine realm of user:", progname);
+       afs_com_err(progname, status, " while getting realm");
+       status = AKLOG_KERBEROS;
+       goto out;
+    }
+
+    retry = 1;
+
+    while(retry) {
+       /* Cell on command line - use that one */
+       if (realm && realm[0]) {
+           realm_of_cell = realm;
+           status = AKLOG_TRYAGAIN;
+           afs_dprintf("We were told to authenticate to realm %s.\n", realm);
+       } else {
+           /* Initially, try using afs/cell@USERREALM */
+           afs_dprintf("Trying to authenticate to user's realm %s.\n",
+                   realm_of_user);
+           realm_of_cell = realm_of_user;
+           status = get_credv5(context, AFSKEY, cell->name, realm_of_cell,
+                               v5cred);
+
+           /* If that failed, try to determine the realm from the name of
+            * one of the DB servers */
+           if (TRYAGAIN(status)) {
+               realm_of_cell = afs_realm_of_cell(context, cell, FALSE);
+               if (!realm_of_cell) {
+                   fprintf(stderr, "%s: Couldn't figure out realm for cell "
+                           "%s.\n", progname, cell->name);
+                   exit(AKLOG_MISC);
+               }
+
+               if (realm_of_cell[0])
+                   afs_dprintf("We've deduced that we need to authenticate"
+                           " to realm %s.\n", realm_of_cell);
+                   else
+                   afs_dprintf("We've deduced that we need to authenticate "
+                           "using referrals.\n");
+           }
+       }
+
+       if (TRYAGAIN(status)) {
+           /* If we've got the full-princ-first option, or we're in a
+            * different realm from the cell - use the cell name as the
+            * instance */
+           if (AFS_TRY_FULL_PRINC ||
+               strcasecmp(cell->name, realm_of_cell)!=0) {
+               status = get_credv5(context, AFSKEY, cell->name,
+                                   realm_of_cell, v5cred);
+
+               /* If we failed & we've got an empty realm, then try
+                * calling afs_realm_for_cell again. */
+               if (TRYAGAIN(status) && !realm_of_cell[0]) {
+                   /* This time, get the realm by taking the domain
+                    * component of the db server and make it upper case */
+                   realm_of_cell = afs_realm_of_cell(context, cell, TRUE);
+                   if (!realm_of_cell) {
+                       fprintf(stderr,
+                               "%s: Couldn't figure out realm for cell %s.\n",
+                               progname, cell->name);
+                       exit(AKLOG_MISC);
+                   }
+                   afs_dprintf("We've deduced that we need to authenticate"
+                           " to realm %s.\n", realm_of_cell);
+               }
+               status = get_credv5(context, AFSKEY, cell->name,
+                                   realm_of_cell, v5cred);
+           }
+
+           /* If the realm and cell name match, then try without an
+            * instance, but only if realm is non-empty */
+
+           if (TRYAGAIN(status) &&
+               strcasecmp(cell->name, realm_of_cell) == 0) {
+               status = get_credv5(context, AFSKEY, NULL, realm_of_cell,
+                                   v5cred);
+               if (!AFS_TRY_FULL_PRINC && TRYAGAIN(status)) {
+                   status = get_credv5(context, AFSKEY, cell->name,
+                                       realm_of_cell, v5cred);
+               }
+           }
+       }
+
+       /* Try to find a service principal for this cell.
+        * Some broken MIT libraries return KRB5KRB_AP_ERR_MSG_TYPE upon
+        * the first attempt, so we try twice to be sure */
+
+       if (status == KRB5KRB_AP_ERR_MSG_TYPE && retry == 1)
+           retry++;
+       else
+           retry = 0;
+    }
+
+    if (status != 0) {
+       afs_dprintf("Kerberos error code returned by get_cred : %d\n", status);
+       fprintf(stderr, "%s: Couldn't get %s AFS tickets:\n",
+               progname, cell->name);
+       afs_com_err(progname, status, "while getting AFS tickets");
+       status = AKLOG_KERBEROS;
+       goto out;
+    }
+
+    /* If we've got a valid ticket, and we still don't know the realm name
+     * try to figure it out from the contents of the ticket
+     */
+    if (strcmp(realm_of_cell, "") == 0) {
+       status = get_realm_from_cred(context, *v5cred, &realm_from_princ);
+       if (status) {
+           fprintf(stderr,
+                   "%s: Couldn't decode ticket to determine realm for "
+                   "cell %s.\n",
+                   progname, cell->name);
+       } else {
+           if (realm_from_princ)
+               realm_of_cell = realm_from_princ;
+       }
+    }
+
+    /* If the realm of the user and cell differ, then we need to use the
+     * realm when we later construct the user's principal */
+    if (realm_of_cell != NULL && strcmp(realm_of_user, realm_of_cell) != 0)
+       *realmUsed = realm_of_user;
+
+out:
+    if (realm_from_princ)
+       free(realm_from_princ);
+    if (realm_of_user && *realmUsed == NULL)
+       free(realm_of_user);
+
+    return status;
+}
+
+/*!
+ * Build an rxkad token from a Kerberos ticket, using only local tools (that
+ * is, without using a 524 conversion service)
+ *
+ * @param[in] context
+ *     An initialised Kerberos 5 context
+ * @param[in] v5cred
+ *     A Kerberos credentials structure containing a suitable service ticket
+ * @param[out] tokenPtr
+ *     An AFS token structure containing an rxkad token. This is a malloc'd
+ *     structure which should be freed by the caller.
+ * @param[out[ userPtr
+ *     A string containing the principal of the user to whom the token was
+ *     issued. This is a malloc'd block which should be freed by the caller.
+ *
+ * @returns
+ *     0 on success, an error value upon failure
+ */
+static int
+rxkad_build_native_token(krb5_context context, krb5_creds *v5cred,
+                        struct ktc_token **tokenPtr, char **userPtr) {
+    char username[BUFSIZ];
+    struct ktc_token *token;
+#ifdef HAVE_NO_KRB5_524
+    char *p;
+    int len;
+#else
+    int status;
+    char k4name[ANAME_SZ];
+    char k4inst[INST_SZ];
+    char k4realm[REALM_SZ];
+#endif
+
+    afs_dprintf("Using Kerberos V5 ticket natively\n");
+
+    *tokenPtr = NULL;
+    *userPtr = NULL;
+
+#ifndef HAVE_NO_KRB5_524
+    status = krb5_524_conv_principal (context, v5cred->client,
+                                     (char *) &k4name,
+                                     (char *) &k4inst,
+                                     (char *) &k4realm);
+    if (status) {
+       afs_com_err(progname, status, "while converting principal "
+                   "to Kerberos V4 format");
+       return AKLOG_KERBEROS;
+    }
+    strcpy (username, k4name);
+    if (k4inst[0]) {
+       strcat (username, ".");
+       strcat (username, k4inst);
+    }
+#else
+    len = min(get_princ_len(context, v5cred->client, 0),
+             second_comp(context, v5cred->client) ?
+             MAXKTCNAMELEN - 2 : MAXKTCNAMELEN - 1);
+    strncpy(username, get_princ_str(context, v5cred->client, 0), len);
+    username[len] = '\0';
+
+    if (second_comp(context, v5cred->client)) {
+       strcat(username, ".");
+       p = username + strlen(username);
+       len = min(get_princ_len(context, v5cred->client, 1),
+                 MAXKTCNAMELEN - strlen(username) - 1);
+       strncpy(p, get_princ_str(context, v5cred->client, 1), len);
+       p[len] = '\0';
+    }
+#endif
+
+    token = malloc(sizeof(struct ktc_token));
+    if (token == NULL)
+       return ENOMEM;
+
+    memset(token, 0, sizeof(struct ktc_token));
+
+    token->kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
+    token->startTime = v5cred->times.starttime;;
+    token->endTime = v5cred->times.endtime;
+    memcpy(&token->sessionKey, get_cred_keydata(v5cred),
+          get_cred_keylen(v5cred));
+    token->ticketLen = v5cred->ticket.length;
+    memcpy(token->ticket, v5cred->ticket.data, token->ticketLen);
+
+    *tokenPtr = token;
+    *userPtr = strdup(username);
+
+    return 0;
+}
+
+/*!
+ * Convert a Keberos ticket to an rxkad token, using information obtained
+ * from an external Kerberos 5->4 conversion service. If the code is built
+ * with HAVE_NO_KRB5_524 then this is a stub function which will always
+ * return success without a token.
+ *
+ * @param[in] context
+ *     An initialised Kerberos 5 context
+ * @param[in] v5cred
+ *     A Kerberos credentials structure containing a suitable service ticket
+ * @param[out] tokenPtr
+ *     An AFS token structure containing an rxkad token. This is a malloc'd
+ *     structure which should be freed by the caller.
+ * @param[out[ userPtr
+ *     A string containing the principal of the user to whom the token was
+ *     issued. This is a malloc'd block which should be freed by the caller.
+ *
+ * @returns
+ *     0 on success, an error value upon failure
+ */
+
+#ifdef HAVE_NO_KRB5_524
+static int
+rxkad_get_converted_token(krb5_context context, krb5_creds *v5cred,
+                         struct ktc_token **tokenPtr, char **userPtr) {
+    *tokenPtr = NULL;
+    *userPtr = NULL;
+
+    return 0;
+}
+#else
+static int
+rxkad_get_converted_token(krb5_context context, krb5_creds *v5cred,
+                         struct ktc_token **tokenPtr, char **userPtr) {
+    CREDENTIALS cred;
+    char username[BUFSIZ];
+    struct ktc_token *token;
+    int status;
+
+    *tokenPtr = NULL;
+    *userPtr = NULL;
+
+    afs_dprintf("Using Kerberos 524 translator service\n");
+
+    status = krb5_524_convert_creds(context, v5cred, &cred);
+
+    if (status) {
+       afs_com_err(progname, status, "while converting tickets "
+               "to Kerberos V4 format");
+       return AKLOG_KERBEROS;
+    }
+
+    strcpy (username, cred.pname);
+    if (cred.pinst[0]) {
+       strcat (username, ".");
+       strcat (username, cred.pinst);
+    }
+
+    token = malloc(sizeof(struct ktc_token));
+    memset(token, 0, sizeof(struct ktc_token));
+
+    token->kvno = cred.kvno;
+    token->startTime = cred.issue_date;
+    /*
+     * It seems silly to go through a bunch of contortions to
+     * extract the expiration time, when the v5 credentials already
+     * has the exact time!  Let's use that instead.
+     *
+     * Note that this isn't a security hole, as the expiration time
+     * is also contained in the encrypted token
+     */
+    token->endTime = v5cred->times.endtime;
+    memcpy(&token->sessionKey, cred.session, 8);
+    token->ticketLen = cred.ticket_st.length;
+    memcpy(token->ticket, cred.ticket_st.dat, token->ticketLen);
+
+    return 0;
+}
+#endif
+
+/*!
+ * This function gets an rxkad token for a given cell.
+ *
+ * @param[in] context
+ *     An initialized Kerberos v5 context
+ * @param[in] cell
+ *     The cell information for the cell which we're obtaining a token for
+ * @param[in] realm
+ *     The realm to look in for the service principal. If NULL, then the
+ *     realm is determined from the cell name or the user's credentials
+ *     (see the documentation for rxkad_get_ticket)
+ * @param[out] token
+ *     The rxkad token produced. This is a malloc'd structure which should
+ *     be freed by the caller.
+ * @parma[out] authuser
+ *     A string containing the principal of the user to whom the token was
+ *     issued. This is a malloc'd block which should be freed by the caller.
+ * @param[out] foreign
+ *     Whether the user is considered as 'foreign' to the realm of the cell.
+ *
+ * @returns
+ *     0 on success, an error value upon failuer
+ */
+static int
+rxkad_get_token(krb5_context context, struct afsconf_cell *cell, char *realm,
+               struct ktc_token **token, char **authuser, int *foreign) {
+    krb5_creds *v5cred;
+    char *realmUsed = NULL;
+    char *username = NULL;
+    int status;
+    size_t len;
+
+    *token = NULL;
+    *authuser = NULL;
+    *foreign = 0;
+
+    status = rxkad_get_ticket(context, realm, cell, &v5cred, &realmUsed);
+    if (status)
+       return status;
+
+    if (do524)
+       status = rxkad_get_converted_token(context, v5cred, token, &username);
+    else
+       status = rxkad_build_native_token(context, v5cred, token, &username);
+
+    if (status)
+       goto out;
+
+    /* We now have the username, plus the realm name, so stitch them together
+     * to give us the name that the ptserver will know the user by */
+    if (realmUsed == NULL) {
+       *authuser = username;
+       username = NULL;
+       *foreign = 0;
+    } else {
+       len = strlen(username)+strlen(realmUsed)+2;
+       *authuser = malloc(len);
+       afs_snprintf(*authuser, len, "%s@%s", username, realmUsed);
+       *foreign = 1;
+    }
+
+out:
+    if (realmUsed)
+       free(realmUsed);
+    if (username)
+       free(username);
+
+    return status;
+}
+
+static int
+get_kernel_token(struct afsconf_cell *cell, struct ktc_token **tokenPtr) {
+    struct ktc_principal client, server;
+    struct ktc_token *token;
+    int ret;
+
+    *tokenPtr = NULL;
+
+    strncpy(server.name, AFSKEY, MAXKTCNAMELEN - 1);
+    strncpy(server.instance, AFSINST, MAXKTCNAMELEN - 1);
+    strncpy(server.cell, cell->name, MAXKTCREALMLEN - 1);
+
+    token = malloc(sizeof(struct ktc_token));
+    if (token == NULL)
+       return ENOMEM;
+
+    memset(token, 0, sizeof(struct ktc_token));
+
+    ret = ktc_GetToken(&server, token, sizeof(struct ktc_token), &client);
+    if (ret) {
+       free(token);
+       return ret;
+    }
+
+    *tokenPtr = token;
+    return 0;
+}
+
+static int
+set_kernel_token(struct afsconf_cell *cell, char *username,
+                struct ktc_token *token, int setpag)
+{
+    struct ktc_principal client, server;
+
+    strncpy(client.name, username, MAXKTCNAMELEN - 1);
+    strcpy(client.instance, "");
+    strncpy(client.cell, cell->name, MAXKTCREALMLEN - 1);
+
+    strncpy(server.name, AFSKEY, MAXKTCNAMELEN - 1);
+    strncpy(server.instance, AFSINST, MAXKTCNAMELEN - 1);
+    strncpy(server.cell, cell->name, MAXKTCREALMLEN - 1);
+
+    return ktc_SetToken(&server, token, &client, setpag);
+}
+
+static int
+tokens_equal(struct ktc_token *tokenA, struct ktc_token *tokenB) {
+    return (tokenA != NULL && tokenB != NULL &&
+           tokenA->kvno == tokenB->kvno &&
+           tokenA->ticketLen == tokenB->ticketLen &&
+           !memcmp(&tokenA->sessionKey, &tokenB->sessionKey,
+                   sizeof(tokenA->sessionKey)) &&
+           !memcmp(tokenA->ticket, tokenB->ticket, tokenA->ticketLen));
+}
+
 /* 
  * 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
  * to.
  */
 static int
-auth_to_cell(krb5_context context, char *cell, char *realm)
+auth_to_cell(krb5_context context, char *cell, char *realm, char **linkedcell)
 {
     int status = AKLOG_SUCCESS;
-    char username[BUFSIZ];     /* To hold client username structure */
+    int isForeign = 0;
+    char *username = NULL;     /* To hold client username structure */
     afs_int32 viceId;          /* AFS uid of user */
 
-    char realm_of_user[REALM_SZ]; /* Kerberos realm of user */
-    char *realm_from_princ = 0 ;  /* Calculated realm data */
-    char *realm_of_cell = 0;     /* Pointer to realm we're using */    
-    int retry;                   /* round, and round we go ... */
-    
-    char local_cell[MAXCELLCHARS+1];
-    char cell_to_use[MAXCELLCHARS+1]; /* Cell to authenticate to */
-    static char confname[512] = { 0 };
-    krb5_creds *v5cred = NULL;
-    struct ktc_principal aserver;
-    struct ktc_principal aclient;
-    struct ktc_token atoken, btoken;
-
-    memset(realm_of_user, 0, sizeof(realm_of_user));
-
-    if (confname[0] == '\0') {
-       strncpy(confname, AFSDIR_CLIENT_ETC_DIRPATH, sizeof(confname));
-       confname[sizeof(confname) - 2] = '\0';
-    }
+    char *local_cell = NULL;
+    struct ktc_token *token;
+    struct ktc_token *btoken;
+    struct afsconf_cell cellconf;
 
     /* NULL or empty cell returns information on local cell */
-    if ((status = get_cellconfig(cell, &ak_cellconfig,
-                        local_cell, linkedcell)))
+    if ((status = get_cellconfig(cell, &cellconf, &local_cell)))
        return(status);
 
-    strncpy(cell_to_use, ak_cellconfig.name, MAXCELLCHARS);
-    cell_to_use[MAXCELLCHARS] = 0;
-
-    if (ll_string(&authedcells, ll_s_check, cell_to_use)) {
-       if (dflag) {
-           printf("Already authenticated to %s (or tried to)\n", 
-                  cell_to_use);
+    if (linkedcell != NULL) {
+       if (cellconf.linkedCell != NULL) {
+           *linkedcell = strdup(cellconf.linkedCell);
+           if (*linkedcell == NULL) {
+               status = ENOMEM;
+               goto out;
+           }
+       } else {
+           *linkedcell = NULL;
        }
-       return(AKLOG_SUCCESS);
+    }
+
+    if (ll_string(&authedcells, ll_s_check, cellconf.name)) {
+       afs_dprintf("Already authenticated to %s (or tried to)\n", cellconf.name);
+       status = AKLOG_SUCCESS;
+       goto out;
     }
 
     /* 
@@ -451,7 +991,7 @@ auth_to_cell(krb5_context context, char *cell, char *realm)
      * before we try rather than after so that we will not try
      * and fail repeatedly for one cell.
      */
-    ll_string(&authedcells, ll_s_add, cell_to_use);
+    ll_string(&authedcells, ll_s_add, cellconf.name);
 
     /* 
      * Record this cell in the list of zephyr subscriptions.  We may
@@ -460,10 +1000,10 @@ auth_to_cell(krb5_context context, char *cell, char *realm)
      * can return something different depending on whether or not we
      * are in -noauth mode.
      */
-    if (ll_string(&zsublist, ll_s_add, cell_to_use) == LL_FAILURE) {
+    if (ll_string(&zsublist, ll_s_add, cellconf.name) == LL_FAILURE) {
        fprintf(stderr, 
                "%s: failure adding cell %s to zephyr subscriptions list.\n",
-               progname, cell_to_use);
+               progname, cellconf.name);
        exit(AKLOG_MISC);
     }
     if (ll_string(&zsublist, ll_s_add, local_cell) == LL_FAILURE) {
@@ -474,292 +1014,21 @@ auth_to_cell(krb5_context context, char *cell, char *realm)
     }
 
     if (!noauth) {
-       if (dflag) {
-           printf("Authenticating to cell %s (server %s).\n",
-                  cell_to_use, ak_cellconfig.hostName[0]);
-       }
-
-       if ((status = get_user_realm(context, realm_of_user))) {
-           fprintf(stderr, "%s: Couldn't determine realm of user:)",
-                   progname);
-           afs_com_err(progname, status, " while getting realm");
-           return(AKLOG_KERBEROS);
-       }
-
-       retry = 1;
-       
-       while(retry) {
-
-           /* This code tries principals in the following, much debated,
-            * order:
-            * 
-            * If the realm is specified on the command line we do
-            *    - afs/cell@COMMAND-LINE-REALM
-            *    - afs@COMMAND-LINE-REALM
-            * 
-            * Otherwise, we do
-            *    - afs/cell@REALM-FROM-USERS-PRINCIPAL
-            *    - afs/cell@krb5_get_host_realm(db-server)
-            *   Then, if krb5_get_host_realm(db-server) is non-empty
-            *      - afs@ krb5_get_host_realm(db-server)
-            *   Otherwise
-            *      - afs/cell@ upper-case-domain-of-db-server
-            *      - afs@ upper-case-domain-of-db-server
-            * 
-            * In all cases, the 'afs@' variant is only tried where the
-            * cell and the realm match case-insensitively.
-            */
-               
-           /* Cell on command line - use that one */
-           if (realm && realm[0]) {
-               realm_of_cell = realm;
-               status = AKLOG_TRYAGAIN;
-               if (dflag) {
-                   printf("We were told to authenticate to realm %s.\n", 
-                          realm);
-               }
-           } else {
-               /* Initially, try using afs/cell@USERREALM */
-               if (dflag) {
-                   printf("Trying to authenticate to user's realm %s.\n",
-                          realm_of_user);
-               }
-               
-               realm_of_cell = realm_of_user;
-               status = get_credv5(context, AFSKEY, cell_to_use, 
-                                   realm_of_cell, &v5cred);
-           
-               /* If that failed, try to determine the realm from the name of 
-                * one of the DB servers */
-               if (TRYAGAIN(status)) {
-                   realm_of_cell = afs_realm_of_cell(context, &ak_cellconfig, 
-                                                     FALSE);
-                   if (!realm_of_cell) {
-                       fprintf(stderr, 
-                               "%s: Couldn't figure out realm for cell %s.\n",
-                               progname, cell_to_use);
-                       exit(AKLOG_MISC);
-                   }
-
-                   if (dflag) {
-                       if (realm_of_cell[0])
-                           printf("We've deduced that we need to authenticate"
-                                  " to realm %s.\n", realm_of_cell);
-                   else
-                       printf("We've deduced that we need to authenticate "
-                              "using referrals.\n");
-                   }
-               }
-           }
-       
-           if (TRYAGAIN(status)) {
-               /* If we've got the full-princ-first option, or we're in a
-                * different realm from the cell - use the cell name as the
-                * instance */
-               if (AFS_TRY_FULL_PRINC || 
-                   strcasecmp(cell_to_use, realm_of_cell)!=0) {
-                   status = get_credv5(context, AFSKEY, cell_to_use, 
-                                       realm_of_cell, &v5cred);
-
-                   /* If we failed & we've got an empty realm, then try 
-                    * calling afs_realm_for_cell again. */
-                   if (TRYAGAIN(status) && !realm_of_cell[0]) {
-                       /* This time, get the realm by taking the domain 
-                        * component of the db server and make it upper case */
-                       realm_of_cell = afs_realm_of_cell(context, 
-                                                         &ak_cellconfig, TRUE);
-                       if (!realm_of_cell) {
-                           fprintf(stderr,
-                                   "%s: Couldn't figure out realm for cell "
-                                   "%s.\n", progname, cell_to_use);
-                           exit(AKLOG_MISC);
-                       }
-                       if (dflag) {
-                           printf("We've deduced that we need to authenticate"
-                                  " to realm %s.\n", realm_of_cell);
-                       }
-                   }
-                   status = get_credv5(context, AFSKEY, cell_to_use, 
-                                       realm_of_cell, &v5cred);
-               }
-          
-               /* If the realm and cell name match, then try without an 
-                * instance, but only if realm is non-empty */
-               
-               if (TRYAGAIN(status) && 
-                   strcasecmp(cell_to_use, realm_of_cell) == 0) {
-                   status = get_credv5(context, AFSKEY, NULL, 
-                                       realm_of_cell, &v5cred);
-                   if (!AFS_TRY_FULL_PRINC && TRYAGAIN(status)) {
-                       status = get_credv5(context, AFSKEY, cell_to_use,
-                                           realm_of_cell, &v5cred);
-                   }
-               }
-           }
-
-           /* Try to find a service principal for this cell.
-            * Some broken MIT libraries return KRB5KRB_AP_ERR_MSG_TYPE upon 
-            * the first attempt, so we try twice to be sure */
-
-           if (status == KRB5KRB_AP_ERR_MSG_TYPE && retry == 1)
-               retry++;
-           else
-               retry = 0;
-       } 
-       
-       if (status != 0) {
-           if (dflag) {
-               printf("Kerberos error code returned by get_cred : %d\n",
-                      status);
-           }
-           fprintf(stderr, "%s: Couldn't get %s AFS tickets:\n",
-                   progname, cell_to_use);
-           afs_com_err(progname, status, "while getting AFS tickets");
-           return(AKLOG_KERBEROS);
-       }
-       
-       /* If we've got a valid ticket, and we still don't know the realm name
-        * try to figure it out from the contents of the ticket
-        */
-#if !defined(USING_HEIMDAL) && defined(HAVE_KRB5_DECODE_TICKET)
-       if (strcmp(realm_of_cell, "") == 0) {
-           krb5_error_code code;
-           krb5_ticket *ticket;
-
-           code = krb5_decode_ticket(&v5cred->ticket, &ticket);
-
-           if (code != 0) {
-               fprintf(stderr,
-                       "%s: Couldn't decode ticket to determine realm for "
-                       "cell %s.\n",
-                       progname, cell_to_use);
-           } else {
-               int len = realm_len(context, ticket->server);
-               /* This really shouldn't happen. */
-               if (len > REALM_SZ-1)
-                   len = REALM_SZ-1;
-
-               realm_from_princ = (char *) malloc(sizeof(char) * (len+1));
-               
-               strncpy(realm_from_princ, realm_data(context, ticket->server), 
-                       len);
-               realm_from_princ[len] = 0;
-               realm_of_cell = realm_from_princ;
-               
-               krb5_free_ticket(context, ticket);
-           }
-       }
-#endif
-
-       strncpy(aserver.name, AFSKEY, MAXKTCNAMELEN - 1);
-       strncpy(aserver.instance, AFSINST, MAXKTCNAMELEN - 1);
-       strncpy(aserver.cell, cell_to_use, MAXKTCREALMLEN - 1);
-
-       /*
-        * The default is to use rxkad2b, which means we put in a full
-        * V5 ticket.  If the user specifies -524, we talk to the
-        * 524 ticket converter.
-        */
-
-       if (! do524) {
-           char k4name[ANAME_SZ], k4inst[INST_SZ], k4realm[REALM_SZ];
-#ifdef HAVE_NO_KRB5_524
-           char *p;
-           int len;
-#endif
-
-           if (dflag)
-               printf("Using Kerberos V5 ticket natively\n");
-
-#ifndef HAVE_NO_KRB5_524
-           status = krb5_524_conv_principal (context, v5cred->client,
-                                             (char *) &k4name,
-                                             (char *) &k4inst,
-                                             (char *) &k4realm);
-           if (status) {
-               afs_com_err(progname, status, "while converting principal "
-                       "to Kerberos V4 format");
-               return(AKLOG_KERBEROS);
-           }
-           strcpy (username, k4name);
-           if (k4inst[0]) {
-               strcat (username, ".");
-               strcat (username, k4inst);
-           }
-#else
-           len = min(get_princ_len(context, v5cred->client, 0),
-                     second_comp(context, v5cred->client) ?
-                     MAXKTCNAMELEN - 2 : MAXKTCNAMELEN - 1);
-           strncpy(username, get_princ_str(context, v5cred->client, 0), len);
-           username[len] = '\0';
-           
-           if (second_comp(context, v5cred->client)) {
-               strcat(username, ".");
-               p = username + strlen(username);
-               len = min(get_princ_len(context, v5cred->client, 1),
-                         MAXKTCNAMELEN - strlen(username) - 1);
-               strncpy(p, get_princ_str(context, v5cred->client, 1), len);
-               p[len] = '\0';
-           }
-#endif
+       afs_dprintf("Authenticating to cell %s (server %s).\n", cellconf.name,
+               cellconf.hostName[0]);
 
-           memset(&atoken, 0, sizeof(atoken));
-           atoken.kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
-           atoken.startTime = v5cred->times.starttime;;
-           atoken.endTime = v5cred->times.endtime;
-           memcpy(&atoken.sessionKey, get_cred_keydata(v5cred),
-                  get_cred_keylen(v5cred));
-           atoken.ticketLen = v5cred->ticket.length;
-           memcpy(atoken.ticket, v5cred->ticket.data, atoken.ticketLen);
-#ifndef HAVE_NO_KRB5_524
-       } else {
-           CREDENTIALS cred;
+       status = rxkad_get_token(context, &cellconf, realm, &token,
+                                &username, &isForeign);
+       if (status)
+           return status;
 
-           if (dflag)
-               printf("Using Kerberos 524 translator service\n");
 
-           status = krb5_524_convert_creds(context, v5cred, &cred);
-
-           if (status) {
-               afs_com_err(progname, status, "while converting tickets "
-                       "to Kerberos V4 format");
-               return(AKLOG_KERBEROS);
-           }
-
-           strcpy (username, cred.pname);
-           if (cred.pinst[0]) {
-               strcat (username, ".");
-               strcat (username, cred.pinst);
-           }
-
-           atoken.kvno = cred.kvno;
-           atoken.startTime = cred.issue_date;
-           /*
-            * It seems silly to go through a bunch of contortions to
-            * extract the expiration time, when the v5 credentials already
-            * has the exact time!  Let's use that instead.
-            *
-            * Note that this isn't a security hole, as the expiration time
-            * is also contained in the encrypted token
-            */
-           atoken.endTime = v5cred->times.endtime;
-           memcpy(&atoken.sessionKey, cred.session, 8);
-           atoken.ticketLen = cred.ticket_st.length;
-           memcpy(atoken.ticket, cred.ticket_st.dat, atoken.ticketLen);
-#endif /* HAVE_NO_KRB5_524 */
-       }
-       
        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)) {
-
-           if (dflag) {
-               printf("Identical tokens already exist; skipping.\n");
-           }
-           return 0;
+           !get_kernel_token(&cellconf, &btoken) &&
+           tokens_equal(token, btoken)) {
+           afs_dprintf("Identical tokens already exist; skipping.\n");
+           status = AKLOG_SUCCESS;
+           goto out;
        }
 
 #ifdef FORCE_NOPRDB
@@ -767,31 +1036,19 @@ auth_to_cell(krb5_context context, char *cell, char *realm)
 #endif
 
        if (noprdb) {
-           if (dflag) {
-               printf("Not resolving name %s to id (-noprdb set)\n",
-                       username);
-           }
+           afs_dprintf("Not resolving name %s to id (-noprdb set)\n", username);
        }
        else {
-           if (strcmp(realm_of_user, realm_of_cell)) {
-               strcat(username, "@");
-               strcat(username, realm_of_user);
-           }
+           afs_dprintf("About to resolve name %s to id in cell %s.\n", username,
+                   cellconf.name);
 
-           if (dflag) {
-               printf("About to resolve name %s to id in cell %s.\n", 
-                       username, aserver.cell);
-           }
+           if (!pr_Initialize (0,  AFSDIR_CLIENT_ETC_DIRPATH, cellconf.name))
+               status = pr_SNameToId (username, &viceId);
 
-           if (!pr_Initialize (0, confname, aserver.cell))
-                   status = pr_SNameToId (username, &viceId);
-           
-           if (dflag) {
-               if (status) 
-                   printf("Error %d\n", status);
-               else
-                   printf("Id %d\n", (int) viceId);
-           }
+           if (status)
+               afs_dprintf("Error %d\n", status);
+           else
+               afs_dprintf("Id %d\n", (int) viceId);
            
 
            /*
@@ -800,20 +1057,16 @@ auth_to_cell(krb5_context context, char *cell, char *realm)
             */
 
 #ifdef ALLOW_REGISTER
-           if ((status == 0) && (viceId == ANONYMOUSID) &&
-               (strcmp(realm_of_user, realm_of_cell) != 0)) {
-               if (dflag) {
-                   printf("doing first-time registration of %s "
-                           "at %s\n", username, cell_to_use);
-               }
+           if ((status == 0) && (viceId == ANONYMOUSID) && isForeign) {
+               afs_dprintf("doing first-time registration of %s at %s\n",
+                       username, cellconf.name);
                viceId = 0;
-               strncpy(aclient.name, username, MAXKTCNAMELEN - 1);
-               strcpy(aclient.instance, "");
-               strncpy(aclient.cell, realm_of_user, MAXKTCREALMLEN - 1);
-               if ((status = ktc_SetToken(&aserver, &atoken, &aclient, 0))) {
+
+               status = set_kernel_token(&cellconf, username, token, 0);
+               if (status) {
                    afs_com_err(progname, status,
                                "while obtaining tokens for cell %s",
-                               cell_to_use);
+                               cellconf.name);
                    status = AKLOG_TOKEN;
                }
 
@@ -824,19 +1077,20 @@ auth_to_cell(krb5_context context, char *cell, char *realm)
                 * level
                 */
 
-               if ((status = pr_Initialize(1L, confname, aserver.cell))) {
+               if ((status = pr_Initialize(1L,  AFSDIR_CLIENT_ETC_DIRPATH,
+                                           cellconf.name))) {
                    printf("Error %d\n", status);
                }
 
                if ((status = pr_CreateUser(username, &viceId))) {
                    fprintf(stderr, "%s: %s so unable to create remote PTS "
                            "user %s in cell %s (status: %d).\n", progname,
-                           afs_error_message(status), username, cell_to_use,
+                           afs_error_message(status), username, cellconf.name,
                            status);
                    viceId = ANONYMOUSID;
                } else {
                    printf("created cross-cell entry for %s (Id %d) at %s\n",
-                          username, viceId, cell_to_use);
+                          username, viceId, cellconf.name);
                }
            }
 #endif /* ALLOW_REGISTER */
@@ -851,45 +1105,43 @@ auth_to_cell(krb5_context context, char *cell, char *realm)
             */
 
            if ((status == 0) && (viceId != ANONYMOUSID)) {
-               sprintf(username, "AFS ID %d", (int) viceId);
+               free(username);
+               if (afs_asprintf(&username, "AFS ID %d", (int) viceId) < 0) {
+                   status = ENOMEM;
+                   username = NULL;
+                   goto out;
+               }
            }
        }
 
-       if (dflag) {
-           fprintf(stdout, "Set username to %s\n", username);
-       }
+       afs_dprintf("Set username to %s\n", username);
 
-       /* Reset the "aclient" structure before we call ktc_SetToken.
-        * This structure was first set by the ktc_GetToken call when
-        * we were comparing whether identical tokens already existed.
-        */
-       strncpy(aclient.name, username, MAXKTCNAMELEN - 1);
-       strcpy(aclient.instance, "");
-       strncpy(aclient.cell, realm_of_user, MAXKTCREALMLEN - 1);
+       afs_dprintf("Setting tokens. %s @ %s \n", username, cellconf.name);
 
-       if (dflag) {
-           printf("Setting tokens. %s / %s @ %s \n",
-                   aclient.name, aclient.instance, aclient.cell );
-       }
 #ifndef AFS_AIX51_ENV
-       /* on AIX 4.1.4 with AFS 3.4a+ if a write is not done before 
+       /* on AIX 4.1.4 with AFS 3.4a+ if a write is not done before
         * this routine, it will not add the token. It is not clear what 
         * is going on here! So we will do the following operation.
         * On AIX 5, it causes the parent program to die, so we won't.
         */
        write(2,"",0); /* dummy write */
 #endif
-       if ((status = ktc_SetToken(&aserver, &atoken, &aclient, afssetpag))) {
+       status = set_kernel_token(&cellconf, username, token, afssetpag);
+       if (status) {
            afs_com_err(progname, status, "while obtaining tokens for cell %s",
-                       cell_to_use);
+                       cellconf.name);
            status = AKLOG_TOKEN;
        }
     }
     else
-       if (dflag) {
-           printf("Noauth mode; not authenticating.\n");
-       }
-       
+       afs_dprintf("Noauth mode; not authenticating.\n");
+
+out:
+    if (local_cell)
+       free(local_cell);
+    if (username)
+       free(username);
+
     return(status);
 }
 
@@ -1055,9 +1307,8 @@ add_hosts(char *file)
     vio.in_size = 0;
     vio.out = outbuf;
 
-    if (dflag) {
-       printf("Getting list of hosts for %s\n", file);
-    }
+    afs_dprintf("Getting list of hosts for %s\n", file);
+
     /* Don't worry about errors. */
     if (!pioctl(file, VIOCWHEREIS, &vio, 1)) {
        phosts = (long *) outbuf;
@@ -1081,15 +1332,11 @@ add_hosts(char *file)
        for (i = 0; phosts[i]; i++) {
            if (hosts) {
                in.s_addr = phosts[i];
-               if (dflag) {
-                   printf("Got host %s\n", inet_ntoa(in));
-               }
+               afs_dprintf("Got host %s\n", inet_ntoa(in));
                ll_string(&hostlist, ll_s_add, (char *)inet_ntoa(in));
            }
            if (zsubs && (hp=gethostbyaddr((char *) &phosts[i],sizeof(long),AF_INET))) {
-               if (dflag) {
-                   printf("Got host %s\n", hp->h_name);
-               }
+               afs_dprintf("Got host %s\n", hp->h_name);
                ll_string(&zsublist, ll_s_add, hp->h_name);
            }
        }
@@ -1104,7 +1351,7 @@ static int
 auth_to_path(krb5_context context, char *path)
 {
     int status = AKLOG_SUCCESS;
-    int auth_to_cell_status = AKLOG_SUCCESS;
+    int auth_status = AKLOG_SUCCESS;
 
     char *nextpath;
     char pathtocheck[MAXPATHLEN + 1];
@@ -1135,9 +1382,7 @@ auth_to_path(krb5_context context, char *path)
     /* Go on to the next level down the path */
     while ((nextpath = next_path(NULL))) {
        strcpy(pathtocheck, nextpath);
-       if (dflag) {
-           printf("Checking directory %s\n", pathtocheck);
-       }
+       afs_dprintf("Checking directory %s\n", pathtocheck);
        /* 
         * If this is an afs mountpoint, determine what cell from 
         * the mountpoint name which is of the form 
@@ -1153,10 +1398,10 @@ auth_to_path(krb5_context context, char *path)
                add_hosts(pathtocheck);
            if ((endofcell = strchr(mountpoint, VOLMARKER))) {
                *endofcell = '\0';
-               if ((auth_to_cell_status = auth_to_cell(context, cell, NULL))) {
+               if ((auth_status = auth_to_cell(context, cell, NULL, NULL))) {
                    if (status == AKLOG_SUCCESS)
-                       status = auth_to_cell_status;
-                   else if (status != auth_to_cell_status)
+                       status = auth_status;
+                   else if (status != auth_status)
                        status = AKLOG_SOMETHINGSWRONG;
                }
            }
@@ -1230,8 +1475,6 @@ main(int argc, char *argv[])
 
     extern char *progname;     /* Name of this program */
 
-    extern int dflag;          /* Debug mode */
-
     int cmode = FALSE;         /* Cellname mode */
     int pmode = FALSE;         /* Path name mode */
 
@@ -1242,6 +1485,7 @@ main(int argc, char *argv[])
     linked_list cells;         /* List of cells to log to */
     linked_list paths;         /* List of paths to log to */
     ll_node *cur_node;
+    char *linkedcell;
 
     memset(&cellinfo, 0, sizeof(cellinfo));
 
@@ -1262,7 +1506,11 @@ main(int argc, char *argv[])
        progname = argv[0];
 
     krb5_init_context(&context);
-    initialize_ktc_error_table ();
+    initialize_KTC_error_table ();
+    initialize_U_error_table();
+    initialize_RXK_error_table();
+    initialize_ACFG_error_table();
+    initialize_PT_error_table();
     afs_set_com_err_hook(redirect_errors);
 
     /*
@@ -1405,19 +1653,20 @@ main(int argc, char *argv[])
     if ((cells.nelements + paths.nelements) == 0) {
        struct passwd *pwd;
 
-       status = auth_to_cell(context, NULL, NULL);
+       status = auth_to_cell(context, NULL, NULL, &linkedcell);
        
        /* If this cell is linked to a DCE cell, and user requested -linked,
         * get tokens for both. This is very useful when the AFS cell is
         * linked to a DFS cell and this system does not also have DFS.
         */
 
-       if (!status && linked && linkedcell[0]) {
-           strncpy(linkedcell2,linkedcell,MAXCELLCHARS);
-           if (dflag) {
-               printf("Linked cell: %s\n", linkedcell);
-           }
-           status = auth_to_cell(context, linkedcell2, NULL);
+       if (!status && linked && linkedcell != NULL) {
+           afs_dprintf("Linked cell: %s\n", linkedcell);
+           status = auth_to_cell(context, linkedcell, NULL, NULL);
+       }
+       if (linkedcell) {
+           free(linkedcell);
+           linkedcell = NULL;
        }
 
        /*
@@ -1437,21 +1686,17 @@ main(int argc, char *argv[])
            if ((stat(xlog_path, &sbuf) == 0) &&
                ((f = fopen(xlog_path, "r")) != NULL)) {
 
-               if (dflag) {
-                   printf("Reading %s for cells to authenticate to.\n",
-                          xlog_path);
-               }
+               afs_dprintf("Reading %s for cells to authenticate to.\n",
+                       xlog_path);
 
                while (fgets(fcell, 100, f) != NULL) {
                    int auth_status;
 
                    fcell[strlen(fcell) - 1] = '\0';
 
-                   if (dflag) {
-                       printf("Found cell %s in %s.\n", fcell, xlog_path);
-                   }
+                   afs_dprintf("Found cell %s in %s.\n", fcell, xlog_path);
 
-                   auth_status = auth_to_cell(context, fcell, NULL);
+                   auth_status = auth_to_cell(context, fcell, NULL, NULL);
                    if (status == AKLOG_SUCCESS)
                        status = auth_status;
                    else
@@ -1464,18 +1709,20 @@ main(int argc, char *argv[])
        /* Log to all cells in the cells list first */
        for (cur_node = cells.first; cur_node; cur_node = cur_node->next) {
            memcpy((char *)&cellinfo, cur_node->data, sizeof(cellinfo));
-           if ((status = auth_to_cell(context, cellinfo.cell, cellinfo.realm)))
+           if ((status = auth_to_cell(context, cellinfo.cell, cellinfo.realm,
+                                      &linkedcell)))
                somethingswrong++;
            else {
-               if (linked && linkedcell[0]) {
-                   strncpy(linkedcell2,linkedcell,MAXCELLCHARS);
-                   if (dflag) {
-                       printf("Linked cell: %s\n", linkedcell);
-                    }
-                   if ((status = auth_to_cell(context,linkedcell2,
-                                              cellinfo.realm)))
+               if (linked && linkedcell != NULL) {
+                   afs_dprintf("Linked cell: %s\n", linkedcell);
+                   if ((status = auth_to_cell(context, linkedcell,
+                                              cellinfo.realm, NULL)))
                        somethingswrong++;
                }
+               if (linkedcell != NULL) {
+                   free(linkedcell);
+                   linkedcell = NULL;
+               }
            }
        }
 
@@ -1557,8 +1804,8 @@ get_credv5_akimpersonate(krb5_context context,
     krb5_ticket ticket_reply[1];
     krb5_enc_tkt_part enc_tkt_reply[1];
     krb5_address address[30], *faddr[30];
-#endif
     krb5_data * temp;
+#endif
     int i;
     static int any_enctype[] = {0};
     *out_creds = 0;
@@ -1839,7 +2086,6 @@ cleanup:
         krb5_kt_close(context, kt);
     if (creds) krb5_free_creds(context, creds);
     krb5_free_keyblock_contents(context, session_key);
-out:
     return code;
 #else
     return -1;
@@ -1855,10 +2101,8 @@ get_credv5(krb5_context context, char *name, char *inst, char *realm,
     krb5_error_code r;
     static krb5_principal client_principal = 0;
 
-    if (dflag) {
-       printf("Getting tickets: %s%s%s@%s\n", name, (inst && inst[0])
-              ? "/" : "", inst ? inst : "", realm);
-    }
+    afs_dprintf("Getting tickets: %s%s%s@%s\n", name,
+           (inst && inst[0]) ? "/" : "", inst ? inst : "", realm);
     
     memset(&increds, 0, sizeof(increds));
 /* ANL - instance may be ptr to a null string. Pass null then */
@@ -1912,12 +2156,13 @@ get_credv5(krb5_context context, char *name, char *inst, char *realm,
 
 
 static int
-get_user_realm(krb5_context context, char *realm)
+get_user_realm(krb5_context context, char **realm)
 {
     static krb5_principal client_principal = 0;
-    int i;
     krb5_error_code r = 0;
 
+    *realm = NULL;
+
     if (!_krb425_ccache)
         krb5_cc_default(context, &_krb425_ccache);
     if (!client_principal) {
@@ -1930,10 +2175,9 @@ get_user_realm(krb5_context context, char *realm)
            return r;
     }
 
-    i = realm_len(context, client_principal);
-    if (i > REALM_SZ-1) i = REALM_SZ-1;
-    strncpy(realm,realm_data(context, client_principal), i);
-    realm[i] = 0;
+    *realm = extract_realm(context, client_principal);
+    if (*realm == NULL)
+       return ENOMEM;
 
     return(r);
 }