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