aklog more error tables
[openafs.git] / src / aklog / aklog.c
1 /* 
2  * $Id$
3  *
4  * Copyright 1990,1991 by the Massachusetts Institute of Technology
5  * For distribution and copying rights, see the file "mit-copyright.h"
6  */
7 /*
8  * Copyright (c) 2005, 2006                                     
9  * The Linux Box Corporation                                    
10  * ALL RIGHTS RESERVED                                          
11  *                                                              
12  * Permission is granted to use, copy, create derivative works  
13  * and redistribute this software and such derivative works     
14  * for any purpose, so long as the name of the Linux Box        
15  * Corporation is not used in any advertising or publicity      
16  * pertaining to the use or distribution of this software       
17  * without specific, written prior authorization.  If the       
18  * above copyright notice or any other identification of the    
19  * Linux Box Corporation is included in any copy of any         
20  * portion of this software, then the disclaimer below must     
21  * also be included.                                            
22  *                                                              
23  * This software is provided as is, without representation      
24  * from the Linux Box Corporation as to its fitness for any     
25  * purpose, and without warranty by the Linux Box Corporation   
26  * of any kind, either express or implied, including            
27  * without limitation the implied warranties of                 
28  * merchantability and fitness for a particular purpose.  The   
29  * regents of the Linux Box Corporation shall not be liable     
30  * for any damages, including special, indirect, incidental, or 
31  * consequential damages, with respect to any claim arising     
32  * out of or in connection with the use of the software, even   
33  * if it has been or is hereafter advised of the possibility of 
34  * such damages.                                                
35  */
36
37 #include <afsconfig.h>
38
39 #include <stdio.h>
40 #include <string.h>
41 #include <ctype.h>
42 #include <sys/types.h>
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46 #ifdef HAVE_STDLIB_H
47 #include <stdlib.h>
48 #endif
49 #ifdef HAVE_MEMORY_H
50 #include <memory.h>
51 #endif
52 #include <errno.h>
53
54 #include <sys/stat.h>
55 #include <fcntl.h>
56
57 #include <sys/param.h>
58 #include <sys/errno.h>
59 #include <netdb.h>
60 #include <sys/socket.h>
61 #include <netinet/in.h>
62 #include <arpa/inet.h>
63 #include <pwd.h>
64
65 #include <afs/stds.h>
66 #include <krb5.h>
67 #if defined(HAVE_ET_COM_ERR_H)
68 #include <et/com_err.h>
69 #else
70 #include <com_err.h>
71 #endif
72
73 #ifndef HAVE_KERBEROSV_HEIM_ERR_H
74 #include <afs/com_err.h>
75 #endif
76
77 #include <afs/param.h>
78 #ifdef AFS_SUN5_ENV
79 #include <sys/ioccom.h>
80 #endif
81
82 /* Prevent inclusion of des.h to avoid conflicts with des types */
83 #define NO_DES_H_INCLUDE
84
85 #include <afs/auth.h>
86 #include <afs/cellconfig.h>
87 #include <afs/vice.h>
88 #include <afs/venus.h>
89 #include <afs/ptserver.h>
90 #include <afs/ptuser.h>
91 #include <afs/dirpath.h>
92 #include <afs/afsutil.h>
93
94 #include "aklog.h"
95 #include "linked_list.h"
96
97 #ifdef HAVE_KRB5_CREDS_KEYBLOCK
98 #define USING_MIT 1
99 #endif
100 #ifdef HAVE_KRB5_CREDS_SESSION
101 #define USING_HEIMDAL 1
102 #endif
103
104 #define AFSKEY "afs"
105 #define AFSINST ""
106
107 #ifndef AFS_TRY_FULL_PRINC
108 #define AFS_TRY_FULL_PRINC 1
109 #endif /* AFS_TRY_FULL_PRINC */
110
111 #define AKLOG_TRYAGAIN -1
112 #define AKLOG_SUCCESS 0
113 #define AKLOG_USAGE 1
114 #define AKLOG_SOMETHINGSWRONG 2
115 #define AKLOG_AFS 3
116 #define AKLOG_KERBEROS 4
117 #define AKLOG_TOKEN 5
118 #define AKLOG_BADPATH 6
119 #define AKLOG_MISC 7
120
121 #ifndef NULL
122 #define NULL 0
123 #endif
124
125 #ifndef TRUE
126 #define TRUE 1
127 #endif
128
129 #ifndef FALSE
130 #define FALSE 0
131 #endif
132
133 #ifndef MAXSYMLINKS
134 /* RedHat 4.x doesn't seem to define this */
135 #define MAXSYMLINKS     5
136 #endif
137
138 #define DIR '/'                 /* Character that divides directories */
139 #define DIRSTRING "/"           /* String form of above */
140 #define VOLMARKER ':'           /* Character separating cellname from mntpt */
141 #define VOLMARKERSTRING ":"     /* String form of above */
142
143 typedef struct {
144     char cell[BUFSIZ];
145     char realm[REALM_SZ];
146 } cellinfo_t;
147
148 static krb5_ccache  _krb425_ccache = NULL;
149
150 /*
151  * Why doesn't AFS provide these prototypes?
152  */
153
154 extern int pioctl(char *, afs_int32, struct ViceIoctl *, afs_int32);
155
156 /*
157  * Other prototypes
158  */
159
160 extern char *afs_realm_of_cell(krb5_context, struct afsconf_cell *, int);
161 static int isdir(char *, unsigned char *);
162 static krb5_error_code get_credv5(krb5_context context, char *, char *,
163                                   char *, krb5_creds **);
164 static int get_user_realm(krb5_context, char **);
165
166 #define TRYAGAIN(x) (x == AKLOG_TRYAGAIN || \
167                      x == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN || \
168                      x == KRB5KRB_ERR_GENERIC)
169
170 #if defined(HAVE_KRB5_PRINC_SIZE) || defined(krb5_princ_size)
171
172 #define get_princ_str(c, p, n) krb5_princ_component(c, p, n)->data
173 #define get_princ_len(c, p, n) krb5_princ_component(c, p, n)->length
174 #define second_comp(c, p) (krb5_princ_size(c, p) > 1)
175 #define realm_data(c, p) krb5_princ_realm(c, p)->data
176 #define realm_len(c, p) krb5_princ_realm(c, p)->length
177
178 #elif defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
179
180 #define get_princ_str(c, p, n) krb5_principal_get_comp_string(c, p, n)
181 #define get_princ_len(c, p, n) strlen(krb5_principal_get_comp_string(c, p, n))
182 #define second_comp(c, p) (krb5_principal_get_comp_string(c, p, 1) != NULL)
183 #define realm_data(c, p) krb5_realm_data(krb5_principal_get_realm(c, p))
184 #define realm_len(c, p) krb5_realm_length(krb5_principal_get_realm(c, p))
185
186 #else
187 #error "Must have either krb5_princ_size or krb5_principal_get_comp_string"
188 #endif
189
190 #if !defined(HAVE_KRB5_ENCRYPT_TKT_PART) && defined(HAVE_ENCODE_KRB5_ENC_TKT_PART) && defined(HAVE_KRB5_C_ENCRYPT) 
191 extern krb5_error_code encode_krb5_enc_tkt_part (const krb5_enc_tkt_part *rep,
192                                                  krb5_data **code);
193
194 krb5_error_code
195 krb5_encrypt_tkt_part(krb5_context context,
196                       const krb5_keyblock *key,
197                       krb5_ticket *ticket)
198 {
199     krb5_data *data = 0;
200     int code;
201     size_t enclen;
202     
203     if ((code = encode_krb5_enc_tkt_part(ticket->enc_part2, &data)))
204         goto Done;
205     if ((code = krb5_c_encrypt_length(context, key->enctype,
206                                       data->length, &enclen)))
207         goto Done;
208     ticket->enc_part.ciphertext.length = enclen;
209     if (!(ticket->enc_part.ciphertext.data = malloc(enclen))) {
210         code = ENOMEM;
211         goto Done;
212     }
213     if ((code = krb5_c_encrypt(context, key, KRB5_KEYUSAGE_KDC_REP_TICKET,
214                                0, data, &ticket->enc_part))) {
215         free(ticket->enc_part.ciphertext.data);
216         ticket->enc_part.ciphertext.data = 0;
217     }
218 Done:
219     if (data) {
220         if (data->data)
221             free(data->data);
222         free(data);
223     }
224     return code;
225 }
226 #endif
227
228 #if defined(HAVE_KRB5_CREDS_KEYBLOCK)
229
230 #define get_cred_keydata(c) c->keyblock.contents
231 #define get_cred_keylen(c) c->keyblock.length
232 #define get_creds_enctype(c) c->keyblock.enctype
233
234 #elif defined(HAVE_KRB5_CREDS_SESSION)
235
236 #define get_cred_keydata(c) c->session.keyvalue.data
237 #define get_cred_keylen(c) c->session.keyvalue.length
238 #define get_creds_enctype(c) c->session.keytype
239
240 #else
241 #error "Must have either keyblock or session member of krb5_creds"
242 #endif
243
244 #if !defined(HAVE_KRB5_524_CONVERT_CREDS) && defined(HAVE_KRB524_CONVERT_CREDS_KDC)
245 #define krb5_524_convert_creds krb524_convert_creds_kdc
246 #elif !defined(HAVE_KRB5_524_CONVERT_CREDS) && !defined(HAVE_KRB524_CONVERT_CREDS_KDC)
247 #define HAVE_NO_KRB5_524
248 #endif
249
250 #if USING_HEIMDAL
251 #define deref_keyblock_enctype(kb)              \
252     ((kb)->keytype)
253
254 #define deref_entry_keyblock(entry)             \
255     entry->keyblock
256
257 #define deref_session_key(creds)                \
258     creds->session
259
260 #define deref_enc_tkt_addrs(tkt)                \
261     tkt->caddr
262
263 #define deref_enc_length(enc)                   \
264     ((enc)->cipher.length)
265
266 #define deref_enc_data(enc)                     \
267     ((enc)->cipher.data)
268
269 #define krb5_free_keytab_entry_contents krb5_kt_free_entry
270
271 #else
272 #define deref_keyblock_enctype(kb)              \
273     ((kb)->enctype)
274
275 #define deref_entry_keyblock(entry)             \
276     entry->key
277
278 #define deref_session_key(creds)                \
279     creds->keyblock
280
281 #define deref_enc_tkt_addrs(tkt)                \
282     tkt->caddrs
283
284 #define deref_enc_length(enc)                   \
285     ((enc)->ciphertext.length)
286
287 #define deref_enc_data(enc)                     \
288     ((enc)->ciphertext.data)
289
290 #endif
291
292 #define deref_entry_enctype(entry)                      \
293     deref_keyblock_enctype(&deref_entry_keyblock(entry))
294
295 /*
296  * Provide a replacement for strerror if we don't have it
297  */
298
299 #ifndef HAVE_STRERROR
300 extern char *sys_errlist[];
301 #define strerror(x) sys_errlist[x]
302 #endif /* HAVE_STRERROR */
303
304 static char *progname = NULL;   /* Name of this program */
305 static int dflag = FALSE;       /* Give debugging information */
306 static int noauth = FALSE;      /* If true, don't try to get tokens */
307 static int zsubs = FALSE;       /* Are we keeping track of zephyr subs? */
308 static int hosts = FALSE;       /* Are we keeping track of hosts? */
309 static int noprdb = FALSE;      /* Skip resolving name to id? */
310 static int linked = FALSE;      /* try for both AFS nodes */
311 static int afssetpag = FALSE;   /* setpag for AFS */
312 static int force = FALSE;       /* Bash identical tokens? */
313 static int do524 = FALSE;       /* Should we do 524 instead of rxkad2b? */
314 static char *keytab = NULL;     /* keytab for akimpersonate */
315 static char *client = NULL;     /* client principal for akimpersonate */
316 static linked_list zsublist;    /* List of zephyr subscriptions */
317 static linked_list hostlist;    /* List of host addresses */
318 static linked_list authedcells; /* List of cells already logged to */
319
320 /* A com_error bodge. The idea here is that this routine lets us lookup
321  * things in the system com_err, if the AFS one just tells us the error
322  * is unknown
323  */
324
325 void
326 redirect_errors(const char *who, afs_int32 code, const char *fmt, va_list ap)
327 {
328     if (who) {
329         fputs(who, stderr);
330         fputs(": ", stderr);
331     }
332     if (code) {
333         const char *str = afs_error_message(code);
334         if (strncmp(str, "unknown", strlen("unknown")) == 0) {
335 #ifdef HAVE_KRB5_SVC_GET_MSG
336             krb5_svc_get_msg(code,&str);
337 #else
338             str = error_message(code);
339 #endif
340         }
341         fputs(str, stderr);
342         fputs(" ", stderr);
343 #ifdef HAVE_KRB5_SVC_GET_MSG
344         krb5_free_string(str);
345 #endif
346     }
347     if (fmt) {
348         vfprintf(stderr, fmt, ap);
349     }
350     putc('\n', stderr);
351     fflush(stderr);
352 }
353
354 static void
355 afs_dprintf(char *fmt, ...) {
356     va_list ap;
357
358     va_start(ap, fmt);
359     if (dflag)
360         vprintf(fmt, ap);
361     va_end(ap);
362 }
363
364 static char *
365 copy_cellinfo(cellinfo_t *cellinfo)
366 {
367     cellinfo_t *new_cellinfo;
368
369     if ((new_cellinfo = (cellinfo_t *)malloc(sizeof(cellinfo_t))))
370         memcpy(new_cellinfo, cellinfo, sizeof(cellinfo_t));
371     
372     return ((char *)new_cellinfo);
373 }
374
375
376 static int
377 get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char **local_cell)
378 {
379     int status = AKLOG_SUCCESS;
380     struct afsconf_dir *configdir;
381
382     memset(cellconfig, 0, sizeof(*cellconfig));
383
384     *local_cell = malloc(MAXCELLCHARS);
385     if (*local_cell == NULL) {
386         fprintf(stderr, "%s: can't allocate memory for local cell name\n",
387                 progname);
388         exit(AKLOG_AFS);
389     }
390
391     if (!(configdir = afsconf_Open(AFSDIR_CLIENT_ETC_DIRPATH))) {
392         fprintf(stderr, 
393                 "%s: can't get afs configuration (afsconf_Open(%s))\n",
394                 progname, AFSDIR_CLIENT_ETC_DIRPATH);
395         exit(AKLOG_AFS);
396     }
397
398     if (afsconf_GetLocalCell(configdir, *local_cell, MAXCELLCHARS)) {
399         fprintf(stderr, "%s: can't determine local cell.\n", progname);
400         exit(AKLOG_AFS);
401     }
402
403     if ((cell == NULL) || (cell[0] == 0))
404         cell = *local_cell;
405
406     /* XXX - This function modifies 'cell' by passing it through lcstring */
407     if (afsconf_GetCellInfo(configdir, cell, NULL, cellconfig)) {
408         fprintf(stderr, "%s: Can't get information about cell %s.\n",
409                 progname, cell);
410         status = AKLOG_AFS;
411     }
412
413     afsconf_Close(configdir);
414
415     return(status);
416 }
417
418 static char *
419 extract_realm(krb5_context context, krb5_principal princ) {
420     int len;
421     char *realm;
422
423     len = realm_len(context, princ);
424     if (len > REALM_SZ-1)
425         len = REALM_SZ-1;
426
427     realm = malloc(sizeof(char) * (len+1));
428     if (realm == NULL)
429         return NULL;
430
431     strncpy(realm, realm_data(context, princ), len);
432     realm[len] = '\0';
433
434     return realm;
435 }
436
437 static int
438 get_realm_from_cred(krb5_context context, krb5_creds *v5cred, char **realm) {
439 #if !defined(HEIMDAL) && defined(HAVE_KRB5_DECODE_TICKET)
440     krb5_error_code code;
441     krb5_ticket *ticket;
442
443     *realm = NULL;
444
445     code = krb5_decode_ticket(&v5cred->ticket, &ticket);
446     if (code)
447         return code;
448
449     *realm = extract_realm(context, ticket->server);
450     if (*realm == NULL)
451         code = ENOMEM;
452
453     krb5_free_ticket(context, ticket);
454
455     return code;
456 #else
457     *realm = NULL;
458     return 0;
459 #endif
460 }
461
462 /*!
463  * Get a Kerberos service ticket to use as the base of an rxkad token for
464  * a given AFS cell.
465  *
466  * @param[in] context
467  *      An initialized Kerberos v5 context
468  * @param[in] realm
469  *      The realm to look in for the service principal. If NULL, then the
470  *      realm is determined from the cell name or the user's credentials
471  *      (see below for the heuristics used)
472  * @param[in] cell
473  *      The cell information for the cell to obtain a ticket for
474  * @param[out] v5cred
475  *      A Kerberos credentials structure containing the ticket acquired
476  *      for the cell. This is a dynamically allocated structure, which
477  *      should be freed by using the appropriate Kerberos API function.
478  * @param[out] realmUsed
479  *      The realm in which the cell's service principal was located. If
480  *      unset, then the principal was located in the same realm as the
481  *      current user. This is a malloc'd string which should be freed
482  *      by the caller.
483  *
484  * @returns
485  *      0 on success, an error value upon failure
486  *
487  * @notes
488  *      This code tries principals in the following, much debated,
489  *      order:
490  *
491  *      If the realm is specified on the command line we do
492  *         - afs/cell@COMMAND-LINE-REALM
493  *         - afs@COMMAND-LINE-REALM
494  *
495  *      Otherwise, we do
496  *         - afs/cell@REALM-FROM-USERS-PRINCIPAL
497  *         - afs/cell@krb5_get_host_realm(db-server)
498  *        Then, if krb5_get_host_realm(db-server) is non-empty
499  *           - afs@ krb5_get_host_realm(db-server)
500  *        Otherwise
501  *           - afs/cell@ upper-case-domain-of-db-server
502  *           - afs@ upper-case-domain-of-db-server
503  *
504  *      In all cases, the 'afs@' variant is only tried where the
505  *      cell and the realm match case-insensitively.
506  */
507
508 static int
509 rxkad_get_ticket(krb5_context context, char *realm,
510                  struct afsconf_cell *cell,
511                  krb5_creds **v5cred, char **realmUsed) {
512     char *realm_of_cell = NULL;
513     char *realm_of_user = NULL;
514     char *realm_from_princ = NULL;
515     int status;
516     int retry;
517
518     *realmUsed = NULL;
519
520     if ((status = get_user_realm(context, &realm_of_user))) {
521         fprintf(stderr, "%s: Couldn't determine realm of user:", progname);
522         afs_com_err(progname, status, " while getting realm");
523         status = AKLOG_KERBEROS;
524         goto out;
525     }
526
527     retry = 1;
528
529     while(retry) {
530         /* Cell on command line - use that one */
531         if (realm && realm[0]) {
532             realm_of_cell = realm;
533             status = AKLOG_TRYAGAIN;
534             afs_dprintf("We were told to authenticate to realm %s.\n", realm);
535         } else {
536             /* Initially, try using afs/cell@USERREALM */
537             afs_dprintf("Trying to authenticate to user's realm %s.\n",
538                     realm_of_user);
539             realm_of_cell = realm_of_user;
540             status = get_credv5(context, AFSKEY, cell->name, realm_of_cell,
541                                 v5cred);
542
543             /* If that failed, try to determine the realm from the name of
544              * one of the DB servers */
545             if (TRYAGAIN(status)) {
546                 realm_of_cell = afs_realm_of_cell(context, cell, FALSE);
547                 if (!realm_of_cell) {
548                     fprintf(stderr, "%s: Couldn't figure out realm for cell "
549                             "%s.\n", progname, cell->name);
550                     exit(AKLOG_MISC);
551                 }
552
553                 if (realm_of_cell[0])
554                     afs_dprintf("We've deduced that we need to authenticate"
555                             " to realm %s.\n", realm_of_cell);
556                     else
557                     afs_dprintf("We've deduced that we need to authenticate "
558                             "using referrals.\n");
559             }
560         }
561
562         if (TRYAGAIN(status)) {
563             /* If we've got the full-princ-first option, or we're in a
564              * different realm from the cell - use the cell name as the
565              * instance */
566             if (AFS_TRY_FULL_PRINC ||
567                 strcasecmp(cell->name, realm_of_cell)!=0) {
568                 status = get_credv5(context, AFSKEY, cell->name,
569                                     realm_of_cell, v5cred);
570
571                 /* If we failed & we've got an empty realm, then try
572                  * calling afs_realm_for_cell again. */
573                 if (TRYAGAIN(status) && !realm_of_cell[0]) {
574                     /* This time, get the realm by taking the domain
575                      * component of the db server and make it upper case */
576                     realm_of_cell = afs_realm_of_cell(context, cell, TRUE);
577                     if (!realm_of_cell) {
578                         fprintf(stderr,
579                                 "%s: Couldn't figure out realm for cell %s.\n",
580                                 progname, cell->name);
581                         exit(AKLOG_MISC);
582                     }
583                     afs_dprintf("We've deduced that we need to authenticate"
584                             " to realm %s.\n", realm_of_cell);
585                 }
586                 status = get_credv5(context, AFSKEY, cell->name,
587                                     realm_of_cell, v5cred);
588             }
589
590             /* If the realm and cell name match, then try without an
591              * instance, but only if realm is non-empty */
592
593             if (TRYAGAIN(status) &&
594                 strcasecmp(cell->name, realm_of_cell) == 0) {
595                 status = get_credv5(context, AFSKEY, NULL, realm_of_cell,
596                                     v5cred);
597                 if (!AFS_TRY_FULL_PRINC && TRYAGAIN(status)) {
598                     status = get_credv5(context, AFSKEY, cell->name,
599                                         realm_of_cell, v5cred);
600                 }
601             }
602         }
603
604         /* Try to find a service principal for this cell.
605          * Some broken MIT libraries return KRB5KRB_AP_ERR_MSG_TYPE upon
606          * the first attempt, so we try twice to be sure */
607
608         if (status == KRB5KRB_AP_ERR_MSG_TYPE && retry == 1)
609             retry++;
610         else
611             retry = 0;
612     }
613
614     if (status != 0) {
615         afs_dprintf("Kerberos error code returned by get_cred : %d\n", status);
616         fprintf(stderr, "%s: Couldn't get %s AFS tickets:\n",
617                 progname, cell->name);
618         afs_com_err(progname, status, "while getting AFS tickets");
619         status = AKLOG_KERBEROS;
620         goto out;
621     }
622
623     /* If we've got a valid ticket, and we still don't know the realm name
624      * try to figure it out from the contents of the ticket
625      */
626     if (strcmp(realm_of_cell, "") == 0) {
627         status = get_realm_from_cred(context, *v5cred, &realm_from_princ);
628         if (status) {
629             fprintf(stderr,
630                     "%s: Couldn't decode ticket to determine realm for "
631                     "cell %s.\n",
632                     progname, cell->name);
633         } else {
634             if (realm_from_princ)
635                 realm_of_cell = realm_from_princ;
636         }
637     }
638
639     /* If the realm of the user and cell differ, then we need to use the
640      * realm when we later construct the user's principal */
641     if (realm_of_cell != NULL && strcmp(realm_of_user, realm_of_cell) != 0)
642         *realmUsed = realm_of_user;
643
644 out:
645     if (realm_from_princ)
646         free(realm_from_princ);
647     if (realm_of_user && *realmUsed == NULL)
648         free(realm_of_user);
649
650     return status;
651 }
652
653 /*!
654  * Build an rxkad token from a Kerberos ticket, using only local tools (that
655  * is, without using a 524 conversion service)
656  *
657  * @param[in] context
658  *      An initialised Kerberos 5 context
659  * @param[in] v5cred
660  *      A Kerberos credentials structure containing a suitable service ticket
661  * @param[out] tokenPtr
662  *      An AFS token structure containing an rxkad token. This is a malloc'd
663  *      structure which should be freed by the caller.
664  * @param[out[ userPtr
665  *      A string containing the principal of the user to whom the token was
666  *      issued. This is a malloc'd block which should be freed by the caller.
667  *
668  * @returns
669  *      0 on success, an error value upon failure
670  */
671 static int
672 rxkad_build_native_token(krb5_context context, krb5_creds *v5cred,
673                          struct ktc_token **tokenPtr, char **userPtr) {
674     char k4name[ANAME_SZ];
675     char k4inst[INST_SZ];
676     char k4realm[REALM_SZ];
677     char username[BUFSIZ];
678     struct ktc_token *token;
679     int status;
680 #ifdef HAVE_NO_KRB5_524
681     char *p;
682     int len;
683 #endif
684
685     afs_dprintf("Using Kerberos V5 ticket natively\n");
686
687     *tokenPtr = NULL;
688     *userPtr = NULL;
689
690 #ifndef HAVE_NO_KRB5_524
691     status = krb5_524_conv_principal (context, v5cred->client,
692                                       (char *) &k4name,
693                                       (char *) &k4inst,
694                                       (char *) &k4realm);
695     if (status) {
696         afs_com_err(progname, status, "while converting principal "
697                     "to Kerberos V4 format");
698         return AKLOG_KERBEROS;
699     }
700     strcpy (username, k4name);
701     if (k4inst[0]) {
702         strcat (username, ".");
703         strcat (username, k4inst);
704     }
705 #else
706     len = min(get_princ_len(context, v5cred->client, 0),
707               second_comp(context, v5cred->client) ?
708               MAXKTCNAMELEN - 2 : MAXKTCNAMELEN - 1);
709     strncpy(username, get_princ_str(context, v5cred->client, 0), len);
710     username[len] = '\0';
711
712     if (second_comp(context, v5cred->client)) {
713         strcat(username, ".");
714         p = username + strlen(username);
715         len = min(get_princ_len(context, v5cred->client, 1),
716                   MAXKTCNAMELEN - strlen(username) - 1);
717         strncpy(p, get_princ_str(context, v5cred->client, 1), len);
718         p[len] = '\0';
719     }
720 #endif
721
722     token = malloc(sizeof(struct ktc_token));
723     if (token == NULL)
724         return ENOMEM;
725
726     memset(token, 0, sizeof(struct ktc_token));
727
728     token->kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
729     token->startTime = v5cred->times.starttime;;
730     token->endTime = v5cred->times.endtime;
731     memcpy(&token->sessionKey, get_cred_keydata(v5cred),
732            get_cred_keylen(v5cred));
733     token->ticketLen = v5cred->ticket.length;
734     memcpy(token->ticket, v5cred->ticket.data, token->ticketLen);
735
736     *tokenPtr = token;
737     *userPtr = strdup(username);
738
739     return 0;
740 }
741
742 /*!
743  * Convert a Keberos ticket to an rxkad token, using information obtained
744  * from an external Kerberos 5->4 conversion service. If the code is built
745  * with HAVE_NO_KRB5_524 then this is a stub function which will always
746  * return success without a token.
747  *
748  * @param[in] context
749  *      An initialised Kerberos 5 context
750  * @param[in] v5cred
751  *      A Kerberos credentials structure containing a suitable service ticket
752  * @param[out] tokenPtr
753  *      An AFS token structure containing an rxkad token. This is a malloc'd
754  *      structure which should be freed by the caller.
755  * @param[out[ userPtr
756  *      A string containing the principal of the user to whom the token was
757  *      issued. This is a malloc'd block which should be freed by the caller.
758  *
759  * @returns
760  *      0 on success, an error value upon failure
761  */
762
763 #ifdef HAVE_NO_KRB5_524
764 static int
765 rxkad_get_converted_token(krb5_context context, krb5_creds *v5cred,
766                           struct ktc_token **tokenPtr, char **userPtr) {
767     *tokenPtr = NULL;
768     *userPtr = NULL;
769
770     return 0;
771 }
772 #else
773 static int
774 rxkad_get_converted_token(krb5_context context, krb5_creds *v5cred,
775                           struct ktc_token **tokenPtr, char **userPtr) {
776     CREDENTIALS cred;
777     char username[BUFSIZ];
778     struct ktc_token *token;
779     int status;
780
781     *tokenPtr = NULL;
782     *userPtr = NULL;
783
784     afs_dprintf("Using Kerberos 524 translator service\n");
785
786     status = krb5_524_convert_creds(context, v5cred, &cred);
787
788     if (status) {
789         afs_com_err(progname, status, "while converting tickets "
790                 "to Kerberos V4 format");
791         return AKLOG_KERBEROS;
792     }
793
794     strcpy (username, cred.pname);
795     if (cred.pinst[0]) {
796         strcat (username, ".");
797         strcat (username, cred.pinst);
798     }
799
800     token = malloc(sizeof(struct ktc_token));
801     memset(token, 0, sizeof(struct ktc_token));
802
803     token->kvno = cred.kvno;
804     token->startTime = cred.issue_date;
805     /*
806      * It seems silly to go through a bunch of contortions to
807      * extract the expiration time, when the v5 credentials already
808      * has the exact time!  Let's use that instead.
809      *
810      * Note that this isn't a security hole, as the expiration time
811      * is also contained in the encrypted token
812      */
813     token->endTime = v5cred->times.endtime;
814     memcpy(&token->sessionKey, cred.session, 8);
815     token->ticketLen = cred.ticket_st.length;
816     memcpy(token->ticket, cred.ticket_st.dat, token->ticketLen);
817
818     return 0;
819 }
820 #endif
821
822 /*!
823  * This function gets an rxkad token for a given cell.
824  *
825  * @param[in] context
826  *      An initialized Kerberos v5 context
827  * @param[in] cell
828  *      The cell information for the cell which we're obtaining a token for
829  * @param[in] realm
830  *      The realm to look in for the service principal. If NULL, then the
831  *      realm is determined from the cell name or the user's credentials
832  *      (see the documentation for rxkad_get_ticket)
833  * @param[out] token
834  *      The rxkad token produced. This is a malloc'd structure which should
835  *      be freed by the caller.
836  * @parma[out] authuser
837  *      A string containing the principal of the user to whom the token was
838  *      issued. This is a malloc'd block which should be freed by the caller.
839  * @param[out] foreign
840  *      Whether the user is considered as 'foreign' to the realm of the cell.
841  *
842  * @returns
843  *      0 on success, an error value upon failuer
844  */
845 static int
846 rxkad_get_token(krb5_context context, struct afsconf_cell *cell, char *realm,
847                 struct ktc_token **token, char **authuser, int *foreign) {
848     krb5_creds *v5cred;
849     char *realmUsed = NULL;
850     char *username = NULL;
851     int status;
852     size_t len;
853
854     *token = NULL;
855     *authuser = NULL;
856     *foreign = 0;
857
858     status = rxkad_get_ticket(context, realm, cell, &v5cred, &realmUsed);
859     if (status)
860         return status;
861
862     if (do524)
863         status = rxkad_get_converted_token(context, v5cred, token, &username);
864     else
865         status = rxkad_build_native_token(context, v5cred, token, &username);
866
867     if (status)
868         goto out;
869
870     /* We now have the username, plus the realm name, so stitch them together
871      * to give us the name that the ptserver will know the user by */
872     if (realmUsed == NULL) {
873         *authuser = username;
874         username = NULL;
875         *foreign = 0;
876     } else {
877         len = strlen(username)+strlen(realmUsed)+2;
878         *authuser = malloc(len);
879         afs_snprintf(*authuser, len, "%s@%s", username, realmUsed);
880         *foreign = 1;
881     }
882
883 out:
884     if (realmUsed)
885         free(realmUsed);
886     if (username)
887         free(username);
888
889     return status;
890 }
891
892 static int
893 get_kernel_token(struct afsconf_cell *cell, struct ktc_token **tokenPtr) {
894     struct ktc_principal client, server;
895     struct ktc_token *token;
896     int ret;
897
898     *tokenPtr = NULL;
899
900     strncpy(server.name, AFSKEY, MAXKTCNAMELEN - 1);
901     strncpy(server.instance, AFSINST, MAXKTCNAMELEN - 1);
902     strncpy(server.cell, cell->name, MAXKTCREALMLEN - 1);
903
904     token = malloc(sizeof(struct ktc_token));
905     if (token == NULL)
906         return ENOMEM;
907
908     memset(token, 0, sizeof(struct ktc_token));
909
910     ret = ktc_GetToken(&server, token, sizeof(struct ktc_token), &client);
911     if (ret) {
912         free(token);
913         return ret;
914     }
915
916     *tokenPtr = token;
917     return 0;
918 }
919
920 static int
921 set_kernel_token(struct afsconf_cell *cell, char *username,
922                  struct ktc_token *token, int setpag)
923 {
924     struct ktc_principal client, server;
925
926     strncpy(client.name, username, MAXKTCNAMELEN - 1);
927     strcpy(client.instance, "");
928     strncpy(client.cell, cell->name, MAXKTCREALMLEN - 1);
929
930     strncpy(server.name, AFSKEY, MAXKTCNAMELEN - 1);
931     strncpy(server.instance, AFSINST, MAXKTCNAMELEN - 1);
932     strncpy(server.cell, cell->name, MAXKTCREALMLEN - 1);
933
934     return ktc_SetToken(&server, token, &client, setpag);
935 }
936
937 static int
938 tokens_equal(struct ktc_token *tokenA, struct ktc_token *tokenB) {
939     return (tokenA != NULL && tokenB != NULL &&
940             tokenA->kvno == tokenB->kvno &&
941             tokenA->ticketLen == tokenB->ticketLen &&
942             !memcmp(&tokenA->sessionKey, &tokenB->sessionKey,
943                     sizeof(tokenA->sessionKey)) &&
944             !memcmp(tokenA->ticket, tokenB->ticket, tokenA->ticketLen));
945 }
946
947 /* 
948  * Log to a cell.  If the cell has already been logged to, return without
949  * doing anything.  Otherwise, log to it and mark that it has been logged
950  * to.
951  */
952 static int
953 auth_to_cell(krb5_context context, char *cell, char *realm, char **linkedcell)
954 {
955     int status = AKLOG_SUCCESS;
956     int isForeign = 0;
957     char *username = NULL;      /* To hold client username structure */
958     afs_int32 viceId;           /* AFS uid of user */
959
960     char *local_cell = NULL;
961     struct ktc_token *token;
962     struct ktc_token *btoken;
963     struct afsconf_cell cellconf;
964
965     /* NULL or empty cell returns information on local cell */
966     if ((status = get_cellconfig(cell, &cellconf, &local_cell)))
967         return(status);
968
969     if (linkedcell != NULL && cellconf.linkedCell != NULL) {
970         *linkedcell = strdup(cellconf.linkedCell);
971         if (*linkedcell == NULL) {
972             status = ENOMEM;
973             goto out;
974         }
975     }
976
977     if (ll_string(&authedcells, ll_s_check, cellconf.name)) {
978         afs_dprintf("Already authenticated to %s (or tried to)\n", cellconf.name);
979         status = AKLOG_SUCCESS;
980         goto out;
981     }
982
983     /* 
984      * Record that we have attempted to log to this cell.  We do this
985      * before we try rather than after so that we will not try
986      * and fail repeatedly for one cell.
987      */
988     ll_string(&authedcells, ll_s_add, cellconf.name);
989
990     /* 
991      * Record this cell in the list of zephyr subscriptions.  We may
992      * want zephyr subscriptions even if authentication fails.
993      * If this is done after we attempt to get tokens, aklog -zsubs
994      * can return something different depending on whether or not we
995      * are in -noauth mode.
996      */
997     if (ll_string(&zsublist, ll_s_add, cellconf.name) == LL_FAILURE) {
998         fprintf(stderr, 
999                 "%s: failure adding cell %s to zephyr subscriptions list.\n",
1000                 progname, cellconf.name);
1001         exit(AKLOG_MISC);
1002     }
1003     if (ll_string(&zsublist, ll_s_add, local_cell) == LL_FAILURE) {
1004         fprintf(stderr, 
1005                 "%s: failure adding cell %s to zephyr subscriptions list.\n",
1006                 progname, local_cell);
1007         exit(AKLOG_MISC);
1008     }
1009
1010     if (!noauth) {
1011         afs_dprintf("Authenticating to cell %s (server %s).\n", cellconf.name,
1012                 cellconf.hostName[0]);
1013
1014         status = rxkad_get_token(context, &cellconf, realm, &token,
1015                                  &username, &isForeign);
1016         if (status)
1017             return status;
1018
1019
1020         if (!force &&
1021             !get_kernel_token(&cellconf, &btoken) &&
1022             tokens_equal(token, btoken)) {
1023             afs_dprintf("Identical tokens already exist; skipping.\n");
1024             status = AKLOG_SUCCESS;
1025             goto out;
1026         }
1027
1028 #ifdef FORCE_NOPRDB
1029         noprdb = 1;
1030 #endif
1031
1032         if (noprdb) {
1033             afs_dprintf("Not resolving name %s to id (-noprdb set)\n", username);
1034         }
1035         else {
1036             afs_dprintf("About to resolve name %s to id in cell %s.\n", username,
1037                     cellconf.name);
1038
1039             if (!pr_Initialize (0,  AFSDIR_CLIENT_ETC_DIRPATH, cellconf.name))
1040                 status = pr_SNameToId (username, &viceId);
1041
1042             if (status)
1043                 afs_dprintf("Error %d\n", status);
1044             else
1045                 afs_dprintf("Id %d\n", (int) viceId);
1046             
1047
1048             /*
1049              * This code is taken from cklog -- it lets people
1050              * automatically register with the ptserver in foreign cells
1051              */
1052
1053 #ifdef ALLOW_REGISTER
1054             if ((status == 0) && (viceId == ANONYMOUSID) && isForeign) {
1055                 afs_dprintf("doing first-time registration of %s at %s\n",
1056                         username, cellconf.name);
1057                 viceId = 0;
1058
1059                 status = set_kernel_token(&cellconf, username, token, 0);
1060                 if (status) {
1061                     afs_com_err(progname, status,
1062                                 "while obtaining tokens for cell %s",
1063                                 cellconf.name);
1064                     status = AKLOG_TOKEN;
1065                 }
1066
1067                 /*
1068                  * In case you're wondering, we don't need to change the
1069                  * filename here because we're still connecting to the
1070                  * same cell -- we're just using a different authentication
1071                  * level
1072                  */
1073
1074                 if ((status = pr_Initialize(1L,  AFSDIR_CLIENT_ETC_DIRPATH,
1075                                             cellconf.name))) {
1076                     printf("Error %d\n", status);
1077                 }
1078
1079                 if ((status = pr_CreateUser(username, &viceId))) {
1080                     fprintf(stderr, "%s: %s so unable to create remote PTS "
1081                             "user %s in cell %s (status: %d).\n", progname,
1082                             afs_error_message(status), username, cellconf.name,
1083                             status);
1084                     viceId = ANONYMOUSID;
1085                 } else {
1086                     printf("created cross-cell entry for %s (Id %d) at %s\n",
1087                            username, viceId, cellconf.name);
1088                 }
1089             }
1090 #endif /* ALLOW_REGISTER */
1091
1092             /*
1093              * This is a crock, but it is Transarc's crock, so we have to play
1094              * along in order to get the functionality.  The way the afs id is
1095              * stored is as a string in the username field of the token.
1096              * Contrary to what you may think by looking at the code for
1097              * tokens, this hack (AFS ID %d) will not work if you change %d
1098              * to something else.
1099              */
1100
1101             if ((status == 0) && (viceId != ANONYMOUSID)) {
1102                 sprintf(username, "AFS ID %d", (int) viceId);
1103             }
1104         }
1105
1106         afs_dprintf("Set username to %s\n", username);
1107
1108         afs_dprintf("Setting tokens. %s @ %s \n", username, cellconf.name);
1109
1110 #ifndef AFS_AIX51_ENV
1111         /* on AIX 4.1.4 with AFS 3.4a+ if a write is not done before
1112          * this routine, it will not add the token. It is not clear what 
1113          * is going on here! So we will do the following operation.
1114          * On AIX 5, it causes the parent program to die, so we won't.
1115          */
1116         write(2,"",0); /* dummy write */
1117 #endif
1118         status = set_kernel_token(&cellconf, username, token, afssetpag);
1119         if (status) {
1120             afs_com_err(progname, status, "while obtaining tokens for cell %s",
1121                         cellconf.name);
1122             status = AKLOG_TOKEN;
1123         }
1124     }
1125     else
1126         afs_dprintf("Noauth mode; not authenticating.\n");
1127
1128 out:
1129     if (local_cell)
1130         free(local_cell);
1131     if (username)
1132         free(username);
1133
1134     return(status);
1135 }
1136
1137 static int
1138 get_afs_mountpoint(char *file, char *mountpoint, int size)
1139 {
1140 #ifdef AFS_SUN_ENV
1141     char V ='V'; /* AFS has problem on Sun with pioctl */
1142 #endif
1143     char our_file[MAXPATHLEN + 1];
1144     char *parent_dir;
1145     char *last_component;
1146     struct ViceIoctl vio;
1147     char cellname[BUFSIZ];
1148
1149     memset(our_file, 0, sizeof(our_file));
1150     strcpy(our_file, file);
1151
1152     if ((last_component = strrchr(our_file, DIR))) {
1153         *last_component++ = 0;
1154         parent_dir = our_file;
1155     }
1156     else {
1157         last_component = our_file;
1158         parent_dir = ".";
1159     }    
1160     
1161     memset(cellname, 0, sizeof(cellname));
1162
1163     vio.in = last_component;
1164     vio.in_size = strlen(last_component)+1;
1165     vio.out_size = size;
1166     vio.out = mountpoint;
1167
1168     if (!pioctl(parent_dir, VIOC_AFS_STAT_MT_PT, &vio, 0)) {
1169         if (strchr(mountpoint, VOLMARKER) == NULL) {
1170             vio.in = file;
1171             vio.in_size = strlen(file) + 1;
1172             vio.out_size = sizeof(cellname);
1173             vio.out = cellname;
1174             
1175             if (!pioctl(file, VIOC_FILE_CELL_NAME, &vio, 1)) {
1176                 strcat(cellname, VOLMARKERSTRING);
1177                 strcat(cellname, mountpoint + 1);
1178                 memset(mountpoint + 1, 0, size - 1);
1179                 strcpy(mountpoint + 1, cellname);
1180             }
1181         }
1182         return(TRUE);
1183     }
1184     else
1185         return(FALSE);
1186 }
1187
1188 /* 
1189  * This routine each time it is called returns the next directory 
1190  * down a pathname.  It resolves all symbolic links.  The first time
1191  * it is called, it should be called with the name of the path
1192  * to be descended.  After that, it should be called with the arguemnt
1193  * NULL.
1194  */
1195 static char *
1196 next_path(char *origpath)
1197 {
1198     static char path[MAXPATHLEN + 1];
1199     static char pathtocheck[MAXPATHLEN + 1];
1200
1201     int link = FALSE;           /* Is this a symbolic link? */
1202     char linkbuf[MAXPATHLEN + 1];
1203     char tmpbuf[MAXPATHLEN + 1];
1204
1205     static char *last_comp;     /* last component of directory name */
1206     static char *elast_comp;    /* End of last component */
1207     char *t;
1208     int len;
1209     
1210     static int symlinkcount = 0; /* We can't exceed MAXSYMLINKS */
1211     
1212     /* If we are given something for origpath, we are initializing only. */
1213     if (origpath) {
1214         memset(path, 0, sizeof(path));
1215         memset(pathtocheck, 0, sizeof(pathtocheck));
1216         strcpy(path, origpath);
1217         last_comp = path;
1218         symlinkcount = 0;
1219         return(NULL);
1220     }
1221
1222     /* We were not given origpath; find then next path to check */
1223     
1224     /* If we've gotten all the way through already, return NULL */
1225     if (last_comp == NULL)
1226         return(NULL);
1227
1228     do {
1229         while (*last_comp == DIR)
1230             strncat(pathtocheck, last_comp++, 1);
1231         len = (elast_comp = strchr(last_comp, DIR)) 
1232             ? elast_comp - last_comp : strlen(last_comp);
1233         strncat(pathtocheck, last_comp, len);
1234         memset(linkbuf, 0, sizeof(linkbuf));
1235         if ((link = (readlink(pathtocheck, linkbuf, 
1236                                     sizeof(linkbuf)) > 0))) {
1237             if (++symlinkcount > MAXSYMLINKS) {
1238                 fprintf(stderr, "%s: %s\n", progname, strerror(ELOOP));
1239                 exit(AKLOG_BADPATH);
1240             }
1241             memset(tmpbuf, 0, sizeof(tmpbuf));
1242             if (elast_comp)
1243                 strcpy(tmpbuf, elast_comp);
1244             if (linkbuf[0] == DIR) {
1245                 /* 
1246                  * If this is a symbolic link to an absolute path, 
1247                  * replace what we have by the absolute path.
1248                  */
1249                 memset(path, 0, strlen(path));
1250                 memcpy(path, linkbuf, sizeof(linkbuf));
1251                 strcat(path, tmpbuf);
1252                 last_comp = path;
1253                 elast_comp = NULL;
1254                 memset(pathtocheck, 0, sizeof(pathtocheck));
1255             }
1256             else {
1257                 /* 
1258                  * If this is a symbolic link to a relative path, 
1259                  * replace only the last component with the link name.
1260                  */
1261                 strncpy(last_comp, linkbuf, strlen(linkbuf) + 1);
1262                 strcat(path, tmpbuf);
1263                 elast_comp = NULL;
1264                 if ((t = strrchr(pathtocheck, DIR))) {
1265                     t++;
1266                     memset(t, 0, strlen(t));
1267                 }
1268                 else
1269                     memset(pathtocheck, 0, sizeof(pathtocheck));
1270             }
1271         }
1272         else
1273             last_comp = elast_comp;
1274     }
1275     while(link);
1276
1277     return(pathtocheck);
1278 }
1279
1280 static void
1281 add_hosts(char *file)
1282 {
1283 #ifdef AFS_SUN_ENV
1284     char V = 'V'; /* AFS has problem on SunOS */
1285 #endif
1286     struct ViceIoctl vio;
1287     char outbuf[BUFSIZ];
1288     long *phosts;
1289     int i;
1290     struct hostent *hp;
1291     struct in_addr in;
1292     
1293     memset(outbuf, 0, sizeof(outbuf));
1294
1295     vio.out_size = sizeof(outbuf);
1296     vio.in_size = 0;
1297     vio.out = outbuf;
1298
1299     afs_dprintf("Getting list of hosts for %s\n", file);
1300
1301     /* Don't worry about errors. */
1302     if (!pioctl(file, VIOCWHEREIS, &vio, 1)) {
1303         phosts = (long *) outbuf;
1304
1305         /*
1306          * Lists hosts that we care about.  If ALLHOSTS is defined,
1307          * then all hosts that you ever may possible go through are
1308          * included in this list.  If not, then only hosts that are
1309          * the only ones appear.  That is, if a volume you must use
1310          * is replaced on only one server, that server is included.
1311          * If it is replicated on many servers, then none are included.
1312          * This is not perfect, but the result is that people don't
1313          * get subscribed to a lot of instances of FILSRV that they
1314          * probably won't need which reduces the instances of 
1315          * people getting messages that don't apply to them.
1316          */
1317 #ifndef ALLHOSTS
1318         if (phosts[1] != '\0')
1319             return;
1320 #endif
1321         for (i = 0; phosts[i]; i++) {
1322             if (hosts) {
1323                 in.s_addr = phosts[i];
1324                 afs_dprintf("Got host %s\n", inet_ntoa(in));
1325                 ll_string(&hostlist, ll_s_add, (char *)inet_ntoa(in));
1326             }
1327             if (zsubs && (hp=gethostbyaddr((char *) &phosts[i],sizeof(long),AF_INET))) {
1328                 afs_dprintf("Got host %s\n", hp->h_name);
1329                 ll_string(&zsublist, ll_s_add, hp->h_name);
1330             }
1331         }
1332     }
1333 }
1334
1335 /*
1336  * This routine descends through a path to a directory, logging to 
1337  * every cell it encounters along the way.
1338  */
1339 static int
1340 auth_to_path(krb5_context context, char *path)
1341 {
1342     int status = AKLOG_SUCCESS;
1343     int auth_status = AKLOG_SUCCESS;
1344
1345     char *nextpath;
1346     char pathtocheck[MAXPATHLEN + 1];
1347     char mountpoint[MAXPATHLEN + 1];
1348
1349     char *cell;
1350     char *endofcell;
1351
1352     u_char isdirectory;
1353
1354     /* Initialize */
1355     if (path[0] == DIR)
1356         strcpy(pathtocheck, path);
1357     else {
1358         if (getcwd(pathtocheck, sizeof(pathtocheck)) == NULL) {
1359             fprintf(stderr, "Unable to find current working directory:\n");
1360             fprintf(stderr, "%s\n", pathtocheck);
1361             fprintf(stderr, "Try an absolute pathname.\n");
1362             exit(AKLOG_BADPATH);
1363         }
1364         else {
1365             strcat(pathtocheck, DIRSTRING);
1366             strcat(pathtocheck, path);
1367         }
1368     }
1369     next_path(pathtocheck);
1370
1371     /* Go on to the next level down the path */
1372     while ((nextpath = next_path(NULL))) {
1373         strcpy(pathtocheck, nextpath);
1374         afs_dprintf("Checking directory %s\n", pathtocheck);
1375         /* 
1376          * If this is an afs mountpoint, determine what cell from 
1377          * the mountpoint name which is of the form 
1378          * #cellname:volumename or %cellname:volumename.
1379          */
1380         if (get_afs_mountpoint(pathtocheck, mountpoint, sizeof(mountpoint))) {
1381             /* skip over the '#' or '%' */
1382             cell = mountpoint + 1;
1383             /* Add this (cell:volumename) to the list of zsubs */
1384             if (zsubs)
1385                 ll_string(&zsublist, ll_s_add, cell);
1386             if (zsubs || hosts)
1387                 add_hosts(pathtocheck);
1388             if ((endofcell = strchr(mountpoint, VOLMARKER))) {
1389                 *endofcell = '\0';
1390                 if ((auth_status = auth_to_cell(context, cell, NULL, NULL))) {
1391                     if (status == AKLOG_SUCCESS)
1392                         status = auth_status;
1393                     else if (status != auth_status)
1394                         status = AKLOG_SOMETHINGSWRONG;
1395                 }
1396             }
1397         }
1398         else {
1399             if (isdir(pathtocheck, &isdirectory) < 0) {
1400                 /*
1401                  * If we've logged and still can't stat, there's
1402                  * a problem... 
1403                  */
1404                 fprintf(stderr, "%s: stat(%s): %s\n", progname, 
1405                         pathtocheck, strerror(errno));
1406                 return(AKLOG_BADPATH);
1407             }
1408             else if (! isdirectory) {
1409                 /* Allow only directories */
1410                 fprintf(stderr, "%s: %s: %s\n", progname, pathtocheck,
1411                         strerror(ENOTDIR));
1412                 return(AKLOG_BADPATH);
1413             }
1414         }
1415     }
1416     
1417
1418     return(status);
1419 }
1420
1421
1422 /* Print usage message and exit */
1423 static void
1424 usage(void)
1425 {
1426     fprintf(stderr, "\nUsage: %s %s%s%s\n", progname,
1427             "[-d] [[-cell | -c] cell [-k krb_realm]] ",
1428             "[[-p | -path] pathname]\n",
1429             "    [-zsubs] [-hosts] [-noauth] [-noprdb] [-force] [-setpag] \n"
1430                 "    [-linked]"
1431 #ifndef HAVE_NO_KRB5_524
1432                 " [-524]"
1433 #endif
1434                 "\n");
1435     fprintf(stderr, "    -d gives debugging information.\n");
1436     fprintf(stderr, "    krb_realm is the kerberos realm of a cell.\n");
1437     fprintf(stderr, "    pathname is the name of a directory to which ");
1438     fprintf(stderr, "you wish to authenticate.\n");
1439     fprintf(stderr, "    -zsubs gives zephyr subscription information.\n");
1440     fprintf(stderr, "    -hosts gives host address information.\n");
1441     fprintf(stderr, "    -noauth does not attempt to get tokens.\n");
1442     fprintf(stderr, "    -noprdb means don't try to determine AFS ID.\n");
1443     fprintf(stderr, "    -force means replace identical tickets. \n");
1444     fprintf(stderr, "    -linked means if AFS node is linked, try both. \n");
1445     fprintf(stderr, "    -setpag set the AFS process authentication group.\n");
1446 #ifndef HAVE_NO_KRB5_524
1447     fprintf(stderr, "    -524 means use the 524 converter instead of V5 directly\n");
1448 #endif
1449     fprintf(stderr, "    No commandline arguments means ");
1450     fprintf(stderr, "authenticate to the local cell.\n");
1451     fprintf(stderr, "\n");
1452     exit(AKLOG_USAGE);
1453 }
1454
1455 int
1456 main(int argc, char *argv[])
1457 {
1458     krb5_context context;
1459     int status = AKLOG_SUCCESS;
1460     int i;
1461     int somethingswrong = FALSE;
1462
1463     cellinfo_t cellinfo;
1464
1465     extern char *progname;      /* Name of this program */
1466
1467     int cmode = FALSE;          /* Cellname mode */
1468     int pmode = FALSE;          /* Path name mode */
1469
1470     char realm[REALM_SZ];       /* Kerberos realm of afs server */
1471     char cell[BUFSIZ];          /* Cell to which we are authenticating */
1472     char path[MAXPATHLEN + 1];          /* Path length for path mode */
1473
1474     linked_list cells;          /* List of cells to log to */
1475     linked_list paths;          /* List of paths to log to */
1476     ll_node *cur_node;
1477     char *linkedcell;
1478
1479     memset(&cellinfo, 0, sizeof(cellinfo));
1480
1481     memset(realm, 0, sizeof(realm));
1482     memset(cell, 0, sizeof(cell));
1483     memset(path, 0, sizeof(path));
1484
1485     ll_init(&cells);
1486     ll_init(&paths);
1487
1488     ll_init(&zsublist);
1489     ll_init(&hostlist);
1490
1491     /* Store the program name here for error messages */
1492     if ((progname = strrchr(argv[0], DIR)))
1493         progname++;
1494     else
1495         progname = argv[0];
1496
1497     krb5_init_context(&context);
1498     initialize_KTC_error_table ();
1499     initialize_U_error_table();
1500     initialize_RXK_error_table();
1501     initialize_ACFG_error_table();
1502     initialize_PT_error_table();
1503     afs_set_com_err_hook(redirect_errors);
1504
1505     /*
1506      * Enable DES enctypes, which are currently still required for AFS.
1507      * krb5_allow_weak_crypto is MIT Kerberos 1.8.  krb5_enctype_enable is
1508      * Heimdal.
1509      */
1510 #if defined(HAVE_KRB5_ALLOW_WEAK_CRYPTO)
1511     krb5_allow_weak_crypto(context, 1);
1512 #elif defined(HAVE_KRB5_ENCTYPE_ENABLE)
1513     i = krb5_enctype_valid(context, ETYPE_DES_CBC_CRC);
1514     if (i)
1515         krb5_enctype_enable(context, ETYPE_DES_CBC_CRC);
1516 #endif
1517
1518     /* Initialize list of cells to which we have authenticated */
1519     ll_init(&authedcells);
1520
1521     /* Parse commandline arguments and make list of what to do. */
1522     for (i = 1; i < argc; i++) {
1523         if (strcmp(argv[i], "-d") == 0)
1524             dflag++;
1525         else if (strcmp(argv[i], "-noauth") == 0) 
1526             noauth++;
1527         else if (strcmp(argv[i], "-zsubs") == 0)
1528             zsubs++;
1529         else if (strcmp(argv[i], "-hosts") == 0)
1530             hosts++;
1531         else if (strcmp(argv[i], "-noprdb") == 0)
1532             noprdb++;
1533         else if (strcmp(argv[i], "-linked") == 0)
1534                 linked++;
1535         else if (strcmp(argv[i], "-force") == 0)
1536             force++;
1537 #ifndef HAVE_NO_KRB5_524
1538         else if (strcmp(argv[i], "-524") == 0)
1539             do524++;
1540 #endif
1541     else if (strcmp(argv[i], "-setpag") == 0)
1542             afssetpag++;
1543         else if (((strcmp(argv[i], "-cell") == 0) ||
1544                   (strcmp(argv[i], "-c") == 0)) && !pmode)
1545             if (++i < argc) {
1546                 cmode++;
1547                 strcpy(cell, argv[i]);
1548             }
1549             else
1550                 usage();
1551         else if ((strcmp(argv[i], "-keytab") == 0))
1552             if (++i < argc) {
1553                 keytab = argv[i];
1554             }
1555             else
1556                 usage();
1557         else if ((strcmp(argv[i], "-principal") == 0))
1558             if (++i < argc) {
1559                 client = argv[i];
1560             }
1561             else
1562                 usage();
1563         else if (((strcmp(argv[i], "-path") == 0) ||
1564                   (strcmp(argv[i], "-p") == 0)) && !cmode)
1565             if (++i < argc) {
1566                 pmode++;
1567                 strcpy(path, argv[i]);
1568             }
1569             else
1570                 usage();
1571             
1572         else if (argv[i][0] == '-')
1573             usage();
1574         else if (!pmode && !cmode) {
1575             if (strchr(argv[i], DIR) || (strcmp(argv[i], ".") == 0) ||
1576                 (strcmp(argv[i], "..") == 0)) {
1577                 pmode++;
1578                 strcpy(path, argv[i]);
1579             }
1580             else { 
1581                 cmode++;
1582                 strcpy(cell, argv[i]);
1583             }
1584         }
1585         else
1586             usage();
1587
1588         if (cmode) {
1589             if (((i + 1) < argc) && (strcmp(argv[i + 1], "-k") == 0)) {
1590                 i+=2;
1591                 if (i < argc)
1592                     strcpy(realm, argv[i]);
1593                 else
1594                     usage();
1595             }
1596             /* Add this cell to list of cells */
1597             strcpy(cellinfo.cell, cell);
1598             strcpy(cellinfo.realm, realm);
1599             if ((cur_node = ll_add_node(&cells, ll_tail))) {
1600                 char *new_cellinfo;
1601                 if ((new_cellinfo = copy_cellinfo(&cellinfo)))
1602                     ll_add_data(cur_node, new_cellinfo);
1603                 else {
1604                     fprintf(stderr, 
1605                             "%s: failure copying cellinfo.\n", progname);
1606                     exit(AKLOG_MISC);
1607                 }
1608             }
1609             else {
1610                 fprintf(stderr, "%s: failure adding cell to cells list.\n",
1611                         progname);
1612                 exit(AKLOG_MISC);
1613             }
1614             memset(&cellinfo, 0, sizeof(cellinfo));
1615             cmode = FALSE;
1616             memset(cell, 0, sizeof(cell));
1617             memset(realm, 0, sizeof(realm));
1618         }
1619         else if (pmode) {
1620             /* Add this path to list of paths */
1621             if ((cur_node = ll_add_node(&paths, ll_tail))) {
1622                 char *new_path;
1623                 if ((new_path = strdup(path)))
1624                     ll_add_data(cur_node, new_path);
1625                 else {
1626                     fprintf(stderr, "%s: failure copying path name.\n",
1627                             progname);
1628                     exit(AKLOG_MISC);
1629                 }
1630             }
1631             else {
1632                 fprintf(stderr, "%s: failure adding path to paths list.\n",
1633                         progname);
1634                 exit(AKLOG_MISC);
1635             }
1636             pmode = FALSE;
1637             memset(path, 0, sizeof(path));
1638         }
1639     }
1640
1641     /* If nothing was given, log to the local cell. */
1642     if ((cells.nelements + paths.nelements) == 0) {
1643         struct passwd *pwd;
1644
1645         status = auth_to_cell(context, NULL, NULL, &linkedcell);
1646         
1647         /* If this cell is linked to a DCE cell, and user requested -linked,
1648          * get tokens for both. This is very useful when the AFS cell is
1649          * linked to a DFS cell and this system does not also have DFS.
1650          */
1651
1652         if (!status && linked && linkedcell != NULL) {
1653             afs_dprintf("Linked cell: %s\n", linkedcell);
1654             status = auth_to_cell(context, linkedcell, NULL, NULL);
1655         }
1656         if (linkedcell) {
1657             free(linkedcell);
1658             linkedcell = NULL;
1659         }
1660
1661         /*
1662          * Local hack - if the person has a file in their home
1663          * directory called ".xlog", read that for a list of
1664          * extra cells to authenticate to
1665          */
1666
1667         if ((pwd = getpwuid(getuid())) != NULL) {
1668             struct stat sbuf;
1669             FILE *f;
1670             char fcell[100], xlog_path[512];
1671
1672             strcpy(xlog_path, pwd->pw_dir);
1673             strcat(xlog_path, "/.xlog");
1674
1675             if ((stat(xlog_path, &sbuf) == 0) &&
1676                 ((f = fopen(xlog_path, "r")) != NULL)) {
1677
1678                 afs_dprintf("Reading %s for cells to authenticate to.\n",
1679                         xlog_path);
1680
1681                 while (fgets(fcell, 100, f) != NULL) {
1682                     int auth_status;
1683
1684                     fcell[strlen(fcell) - 1] = '\0';
1685
1686                     afs_dprintf("Found cell %s in %s.\n", fcell, xlog_path);
1687
1688                     auth_status = auth_to_cell(context, fcell, NULL, NULL);
1689                     if (status == AKLOG_SUCCESS)
1690                         status = auth_status;
1691                     else
1692                         status = AKLOG_SOMETHINGSWRONG;
1693                 }
1694             }
1695         }
1696     }
1697     else {
1698         /* Log to all cells in the cells list first */
1699         for (cur_node = cells.first; cur_node; cur_node = cur_node->next) {
1700             memcpy((char *)&cellinfo, cur_node->data, sizeof(cellinfo));
1701             if ((status = auth_to_cell(context, cellinfo.cell, cellinfo.realm,
1702                                        &linkedcell)))
1703                 somethingswrong++;
1704             else {
1705                 if (linked && linkedcell != NULL) {
1706                     afs_dprintf("Linked cell: %s\n", linkedcell);
1707                     if ((status = auth_to_cell(context, linkedcell,
1708                                                cellinfo.realm, NULL)))
1709                         somethingswrong++;
1710                 }
1711                 if (linkedcell != NULL) {
1712                     free(linkedcell);
1713                     linkedcell = NULL;
1714                 }
1715             }
1716         }
1717
1718         /* Then, log to all paths in the paths list */
1719         for (cur_node = paths.first; cur_node; cur_node = cur_node->next) {
1720             if ((status = auth_to_path(context, cur_node->data)))
1721                 somethingswrong++;
1722         }
1723         
1724         /* 
1725          * If only one thing was logged to, we'll return the status 
1726          * of the single call.  Otherwise, we'll return a generic
1727          * something failed status.
1728          */
1729         if (somethingswrong && ((cells.nelements + paths.nelements) > 1))
1730             status = AKLOG_SOMETHINGSWRONG;
1731     }
1732
1733     /* If we are keeping track of zephyr subscriptions, print them. */
1734     if (zsubs) 
1735         for (cur_node = zsublist.first; cur_node; cur_node = cur_node->next) {
1736             printf("zsub: %s\n", cur_node->data);
1737         }
1738
1739     /* If we are keeping track of host information, print it. */
1740     if (hosts)
1741         for (cur_node = hostlist.first; cur_node; cur_node = cur_node->next) {
1742             printf("host: %s\n", cur_node->data);
1743         }
1744
1745     exit(status);
1746 }
1747
1748 static int
1749 isdir(char *path, unsigned char *val)
1750 {
1751     struct stat statbuf;
1752
1753     if (lstat(path, &statbuf) < 0)
1754         return (-1);
1755     else {
1756         if ((statbuf.st_mode & S_IFMT) == S_IFDIR) 
1757             *val = TRUE;
1758         else
1759             *val = FALSE;
1760         return (0);
1761     }  
1762 }
1763
1764 static krb5_error_code
1765 get_credv5_akimpersonate(krb5_context context,
1766                          char* keytab,
1767                          krb5_principal service_principal,
1768                          krb5_principal client_principal,
1769                          time_t starttime,
1770                          time_t endtime,
1771                          int *allowed_enctypes,
1772                          int *paddress,
1773                          krb5_creds** out_creds /* out */ )
1774 {
1775 #if defined(USING_HEIMDAL) || (defined(HAVE_ENCODE_KRB5_ENC_TKT) && defined(HAVE_ENCODE_KRB5_TICKET) && defined(HAVE_KRB5_C_ENCRYPT))
1776     krb5_error_code code;
1777     krb5_keytab kt = 0;
1778     krb5_kt_cursor cursor[1];
1779     krb5_keytab_entry entry[1];
1780     krb5_ccache cc = 0;
1781     krb5_creds *creds = 0;
1782     krb5_enctype enctype;
1783     krb5_kvno kvno;
1784     krb5_keyblock session_key[1];
1785 #if USING_HEIMDAL
1786     Ticket ticket_reply[1];
1787     EncTicketPart enc_tkt_reply[1];
1788     krb5_address address[30];
1789     krb5_addresses faddr[1];
1790     int temp_vno[1];
1791     time_t temp_time[2];
1792 #else
1793     krb5_ticket ticket_reply[1];
1794     krb5_enc_tkt_part enc_tkt_reply[1];
1795     krb5_address address[30], *faddr[30];
1796 #endif
1797     krb5_data * temp;
1798     int i;
1799     static int any_enctype[] = {0};
1800     *out_creds = 0;
1801     if (!(creds = malloc(sizeof *creds))) {
1802         code = ENOMEM;
1803         goto cleanup;
1804     }
1805     if (!allowed_enctypes)
1806         allowed_enctypes = any_enctype;
1807
1808     cc = 0;
1809     enctype = 0; /* AKIMPERSONATE_IGNORE_ENCTYPE */
1810     kvno = 0; /* AKIMPERSONATE_IGNORE_VNO */
1811     memset((char*)creds, 0, sizeof *creds);
1812     memset((char*)entry, 0, sizeof *entry);
1813     memset((char*)session_key, 0, sizeof *session_key);
1814     memset((char*)ticket_reply, 0, sizeof *ticket_reply);
1815     memset((char*)enc_tkt_reply, 0, sizeof *enc_tkt_reply);
1816     code = krb5_kt_resolve(context, keytab, &kt);
1817     if (code) {
1818         if (keytab)
1819             afs_com_err(progname, code, "while resolving keytab %s", keytab);
1820         else
1821             afs_com_err(progname, code, "while resolving default keytab");
1822         goto cleanup;
1823     }
1824
1825     if (service_principal) {
1826         for (i = 0; (enctype = allowed_enctypes[i]) || !i; ++i) {
1827             code = krb5_kt_get_entry(context,
1828                                      kt,
1829                                      service_principal,
1830                                      kvno,
1831                                      enctype,
1832                                      entry);
1833             if (!code) {
1834                 if (allowed_enctypes[i])
1835                     deref_keyblock_enctype(session_key) = allowed_enctypes[i];
1836                 break;
1837             }
1838         }
1839         if (code) {
1840             afs_com_err(progname, code,"while scanning keytab entries");
1841             goto cleanup;
1842         }
1843     } else {
1844         krb5_keytab_entry new[1];
1845         int best = -1;
1846         memset(new, 0, sizeof *new);
1847         if ((code == krb5_kt_start_seq_get(context, kt, cursor))) {
1848             afs_com_err(progname, code, "while starting keytab scan");
1849             goto cleanup;
1850         }
1851         while (!(code = krb5_kt_next_entry(context, kt, new, cursor))) {
1852             for (i = 0;
1853                     allowed_enctypes[i] && allowed_enctypes[i]
1854                      != deref_entry_enctype(new); ++i)
1855                 ;
1856             if ((!i || allowed_enctypes[i]) &&
1857                 (best < 0 || best > i)) {
1858                 krb5_free_keytab_entry_contents(context, entry);
1859                 *entry = *new;
1860                 memset(new, 0, sizeof *new);
1861             } else krb5_free_keytab_entry_contents(context, new);
1862         }
1863         if ((i = krb5_kt_end_seq_get(context, kt, cursor))) {
1864             afs_com_err(progname, i, "while ending keytab scan");
1865             code = i;
1866             goto cleanup;
1867         }
1868         if (best < 0) {
1869             afs_com_err(progname, code, "while scanning keytab");
1870             goto cleanup;
1871         }
1872         deref_keyblock_enctype(session_key) = deref_entry_enctype(entry);
1873     }
1874
1875     /* Make Ticket */
1876
1877 #if USING_HEIMDAL
1878     if ((code = krb5_generate_random_keyblock(context,
1879                                               deref_keyblock_enctype(session_key), session_key))) {
1880         afs_com_err(progname, code, "while making session key");
1881         goto cleanup;
1882     }
1883     enc_tkt_reply->flags.initial = 1;
1884     enc_tkt_reply->transited.tr_type = DOMAIN_X500_COMPRESS;
1885     enc_tkt_reply->cname = client_principal->name;
1886     enc_tkt_reply->crealm = client_principal->realm;
1887     enc_tkt_reply->key = *session_key;
1888     {
1889         static krb5_data empty_string;
1890         enc_tkt_reply->transited.contents = empty_string;
1891     }
1892     enc_tkt_reply->authtime = starttime;
1893     enc_tkt_reply->starttime = temp_time;
1894     *enc_tkt_reply->starttime = starttime;
1895 #if 0
1896     enc_tkt_reply->renew_till = temp_time + 1;
1897     *enc_tkt_reply->renew_till = endtime;
1898 #endif
1899     enc_tkt_reply->endtime = endtime;
1900 #else
1901     if ((code = krb5_c_make_random_key(context,
1902                                        deref_keyblock_enctype(session_key), session_key))) {
1903         afs_com_err(progname, code, "while making session key");
1904         goto cleanup;
1905     }
1906     enc_tkt_reply->magic = KV5M_ENC_TKT_PART;
1907 #define DATACAST        (unsigned char *)
1908     enc_tkt_reply->flags |= TKT_FLG_INITIAL;
1909     enc_tkt_reply->transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;
1910     enc_tkt_reply->session = session_key;
1911     enc_tkt_reply->client = client_principal;
1912     {
1913         static krb5_data empty_string;
1914         enc_tkt_reply->transited.tr_contents = empty_string;
1915     }
1916     enc_tkt_reply->times.authtime = starttime;
1917     enc_tkt_reply->times.starttime = starttime; /* krb524init needs this */
1918     enc_tkt_reply->times.endtime = endtime;
1919 #endif  /* USING_HEIMDAL */
1920     /* NB:  We will discard address for now--ignoring caddr field               
1921        in any case.  MIT branch does what it always did. */
1922
1923     if (paddress && *paddress) {
1924         deref_enc_tkt_addrs(enc_tkt_reply) = faddr;
1925 #if USING_HEIMDAL
1926         faddr->len = 0;
1927         faddr->val = address;
1928 #endif
1929         for (i = 0; paddress[i]; ++i) {
1930 #if USING_HEIMDAL
1931             address[i].addr_type = KRB5_ADDRESS_INET;
1932             address[i].address.data = (void*)(paddress+i);
1933             address[i].address.length = sizeof(paddress[i]);
1934 #else
1935 #if !USING_SSL
1936             address[i].magic = KV5M_ADDRESS;
1937             address[i].addrtype = ADDRTYPE_INET;
1938 #else
1939             address[i].addrtype = AF_INET;
1940 #endif
1941             address[i].contents = (void*)(paddress+i);
1942             address[i].length = sizeof(int);
1943             faddr[i] = address+i;
1944 #endif
1945         }
1946 #if USING_HEIMDAL
1947         faddr->len = i;
1948 #else
1949         faddr[i] = 0;
1950 #endif
1951     }
1952
1953 #if USING_HEIMDAL
1954     ticket_reply->sname = service_principal->name;
1955     ticket_reply->realm = service_principal->realm;
1956
1957     { /* crypto block */
1958         krb5_crypto crypto = 0;
1959         unsigned char *buf = 0;
1960         size_t buf_size, buf_len;
1961         char *what;
1962
1963         ASN1_MALLOC_ENCODE(EncTicketPart, buf, buf_size,
1964                            enc_tkt_reply, &buf_len, code);
1965         if(code) {
1966             afs_com_err(progname, code, "while encoding ticket");
1967             goto cleanup;
1968         }
1969
1970         if(buf_len != buf_size) {
1971             afs_com_err(progname, code,
1972                     "%d != %d while encoding ticket (internal ASN.1 encoder error",
1973                     buf_len, buf_size);
1974             goto cleanup;
1975         }
1976         what = "krb5_crypto_init";
1977         code = krb5_crypto_init(context,
1978                                 &deref_entry_keyblock(entry),
1979                                 deref_entry_enctype(entry),
1980                                 &crypto);
1981         if(!code) {
1982             what = "krb5_encrypt";
1983             code = krb5_encrypt_EncryptedData(context, crypto, KRB5_KU_TICKET,
1984                                               buf, buf_len, entry->vno, &(ticket_reply->enc_part));
1985         }
1986         if (buf) free(buf);
1987         if (crypto) krb5_crypto_destroy(context, crypto);
1988         if(code) {
1989             afs_com_err(progname, code, "while %s", what);
1990             goto cleanup;
1991         }
1992     } /* crypto block */
1993     ticket_reply->enc_part.etype = deref_entry_enctype(entry);
1994     ticket_reply->enc_part.kvno = temp_vno;
1995     *ticket_reply->enc_part.kvno = entry->vno;
1996     ticket_reply->tkt_vno = 5;
1997 #else
1998     ticket_reply->server = service_principal;
1999     ticket_reply->enc_part2 = enc_tkt_reply;
2000     if ((code = krb5_encrypt_tkt_part(context, &deref_entry_keyblock(entry), ticket_reply))) {
2001         afs_com_err(progname, code, "while making ticket");
2002         goto cleanup;
2003     }
2004     ticket_reply->enc_part.kvno = entry->vno;
2005 #endif
2006
2007     /* Construct Creds */
2008
2009     if ((code = krb5_copy_principal(context, service_principal,
2010                                     &creds->server))) {
2011         afs_com_err(progname, code, "while copying service principal");
2012         goto cleanup;
2013     }
2014     if ((code = krb5_copy_principal(context, client_principal,
2015                                     &creds->client))) {
2016         afs_com_err(progname, code, "while copying client principal");
2017         goto cleanup;
2018     }
2019     if ((code = krb5_copy_keyblock_contents(context, session_key,
2020                                             &deref_session_key(creds)))) {
2021         afs_com_err(progname, code, "while copying session key");
2022         goto cleanup;
2023     }
2024
2025 #if USING_HEIMDAL
2026     creds->times.authtime = enc_tkt_reply->authtime;
2027     creds->times.starttime = *(enc_tkt_reply->starttime);
2028     creds->times.endtime = enc_tkt_reply->endtime;
2029     creds->times.renew_till = 0; /* *(enc_tkt_reply->renew_till) */
2030     creds->flags.b = enc_tkt_reply->flags;
2031 #else
2032     creds->times = enc_tkt_reply->times;
2033     creds->ticket_flags = enc_tkt_reply->flags;
2034 #endif
2035     if (!deref_enc_tkt_addrs(enc_tkt_reply))
2036         ;
2037     else if ((code = krb5_copy_addresses(context,
2038                                          deref_enc_tkt_addrs(enc_tkt_reply), &creds->addresses))) {
2039         afs_com_err(progname, code, "while copying addresses");
2040         goto cleanup;
2041     }
2042
2043 #if USING_HEIMDAL
2044     {
2045         size_t creds_tkt_len;
2046         ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length,
2047                            ticket_reply, &creds_tkt_len, code);
2048         if(code) {
2049             afs_com_err(progname, code, "while encoding ticket");
2050             goto cleanup;
2051         }
2052     }
2053 #else
2054     if ((code = encode_krb5_ticket(ticket_reply, &temp))) {
2055         afs_com_err(progname, code, "while encoding ticket");
2056         goto cleanup;
2057     }
2058     creds->ticket = *temp;
2059     free(temp);
2060 #endif
2061     /* return creds */
2062     *out_creds = creds;
2063     creds = 0;
2064 cleanup:
2065     if (deref_enc_data(&ticket_reply->enc_part))
2066         free(deref_enc_data(&ticket_reply->enc_part));
2067     krb5_free_keytab_entry_contents(context, entry);
2068     if (client_principal)
2069         krb5_free_principal(context, client_principal);
2070     if (service_principal)
2071         krb5_free_principal(context, service_principal);
2072     if (cc)
2073         krb5_cc_close(context, cc);
2074     if (kt)
2075         krb5_kt_close(context, kt);
2076     if (creds) krb5_free_creds(context, creds);
2077     krb5_free_keyblock_contents(context, session_key);
2078 out:
2079     return code;
2080 #else
2081     return -1;
2082 #endif
2083 }
2084
2085
2086 static krb5_error_code
2087 get_credv5(krb5_context context, char *name, char *inst, char *realm,
2088            krb5_creds **creds)
2089 {
2090     krb5_creds increds;
2091     krb5_error_code r;
2092     static krb5_principal client_principal = 0;
2093
2094     afs_dprintf("Getting tickets: %s%s%s@%s\n", name,
2095             (inst && inst[0]) ? "/" : "", inst ? inst : "", realm);
2096     
2097     memset(&increds, 0, sizeof(increds));
2098 /* ANL - instance may be ptr to a null string. Pass null then */
2099     if ((r = krb5_build_principal(context, &increds.server,
2100                                   strlen(realm), realm,
2101                                   name,
2102                                   (inst && strlen(inst)) ? inst : (void *) NULL,
2103                                   (void *) NULL))) {
2104         return r;
2105     }
2106     
2107
2108     if (!_krb425_ccache) {
2109         r = krb5_cc_default(context, &_krb425_ccache);
2110         if (r)
2111             return r;
2112     }
2113     if (!client_principal) {
2114         if (client) {
2115             r = krb5_parse_name(context, client,  &client_principal);
2116         } else {
2117             r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
2118         }
2119         if (r)
2120             return r;
2121     }
2122     
2123     increds.client = client_principal;
2124     increds.times.endtime = 0;
2125     /* Ask for DES since that is what V4 understands */
2126     get_creds_enctype((&increds)) = ENCTYPE_DES_CBC_CRC;
2127     
2128     if (keytab) {
2129         int allowed_enctypes[] = {
2130             ENCTYPE_DES_CBC_CRC, 0
2131         };
2132
2133         r = get_credv5_akimpersonate(context,
2134                                      keytab,
2135                                      increds.server,
2136                                      increds.client,
2137                                      300, ((~0U)>>1),
2138                                      allowed_enctypes,
2139                                      0 /* paddress */,
2140                                      creds /* out */);
2141     } else {
2142         r = krb5_get_credentials(context, 0, _krb425_ccache, &increds, creds);
2143     }    
2144     return r;
2145 }
2146
2147
2148 static int
2149 get_user_realm(krb5_context context, char **realm)
2150 {
2151     static krb5_principal client_principal = 0;
2152     krb5_error_code r = 0;
2153
2154     *realm = NULL;
2155
2156     if (!_krb425_ccache)
2157         krb5_cc_default(context, &_krb425_ccache);
2158     if (!client_principal) {
2159         if (client) {
2160             r = krb5_parse_name(context, client,  &client_principal);
2161         } else {
2162             r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
2163         }
2164         if (r)
2165             return r;
2166     }
2167
2168     *realm = extract_realm(context, client_principal);
2169     if (*realm == NULL)
2170         return ENOMEM;
2171
2172     return(r);
2173 }