aklog-no-dummy-write-on-aix5-20071209
[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 ((status == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN || status == KRB5KRB_ERR_GENERIC) &&
663             !realm_of_cell[0]) {
664             char *afs_realm = afs_realm_of_cell(context, &ak_cellconfig, TRUE);
665
666             if (!afs_realm) {
667                 fprintf(stderr, 
668                         "%s: Couldn't figure out realm for cell %s.\n",
669                         progname, cell_to_use);
670                 exit(AKLOG_MISC);
671             }
672
673             strcpy(realm_of_cell, afs_realm);
674
675             if (strcasecmp(cell_to_use, realm_of_cell) == 0) {
676                 try_secondary = 1;
677                 secondary_instance[0] = '\0';
678             }
679
680             if (dflag) {
681                 printf("We've deduced that we need to authenticate to"
682                         " realm %s.\n", realm_of_cell);
683                 printf("Getting tickets: %s%s%s@%s\n", name,
684                         primary_instance[0] ? "/" : "", 
685                         primary_instance, realm_of_cell);
686             }
687
688             status = get_credv5(context, name, primary_instance, realm_of_cell,
689                                  &v5cred);
690
691         }
692         if (status == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN || status == KRB5KRB_ERR_GENERIC) {
693             if (try_secondary) {
694                 if (dflag) {
695                     printf("Principal not found, trying alternate "
696                            "service name: %s%s%s@%s\n", name,
697                             secondary_instance[0] ? "/" : "",
698                             secondary_instance, realm_of_cell);
699                 }
700                 status = get_credv5(context, name, secondary_instance,
701                                     realm_of_cell, &v5cred);
702             }
703         }
704
705         if (status) {
706             if (dflag) {
707                 printf("Kerberos error code returned by get_cred: %d\n",
708                         status);
709             }
710             fprintf(stderr, "%s: Couldn't get %s AFS tickets:\n",
711                     progname, cell_to_use);
712                 afs_com_err(progname, status, "while getting AFS tickets");
713             return(AKLOG_KERBEROS);
714         }
715
716         strncpy(aserver.name, AFSKEY, MAXKTCNAMELEN - 1);
717         strncpy(aserver.instance, AFSINST, MAXKTCNAMELEN - 1);
718         strncpy(aserver.cell, cell_to_use, MAXKTCREALMLEN - 1);
719
720         /*
721          * The default is to use rxkad2b, which means we put in a full
722          * V5 ticket.  If the user specifies -524, we talk to the
723          * 524 ticket converter.
724          */
725
726         if (! do524) {
727             char *p;
728             int len;
729
730             if (dflag)
731                 printf("Using Kerberos V5 ticket natively\n");
732
733             len = min(get_princ_len(context, v5cred->client, 0),
734                       second_comp(context, v5cred->client) ?
735                                         MAXKTCNAMELEN - 2 : MAXKTCNAMELEN - 1);
736             strncpy(username, get_princ_str(context, v5cred->client, 0), len);
737             username[len] = '\0';
738
739             if (second_comp(context, v5cred->client)) {
740                 strcat(username, ".");
741                 p = username + strlen(username);
742                 len = min(get_princ_len(context, v5cred->client, 1),
743                           MAXKTCNAMELEN - strlen(username) - 1);
744                 strncpy(p, get_princ_str(context, v5cred->client, 1), len);
745                 p[len] = '\0';
746             }
747
748             memset(&atoken, 0, sizeof(atoken));
749             atoken.kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
750             atoken.startTime = v5cred->times.starttime;;
751             atoken.endTime = v5cred->times.endtime;
752             memcpy(&atoken.sessionKey, get_cred_keydata(v5cred),
753                    get_cred_keylen(v5cred));
754             atoken.ticketLen = v5cred->ticket.length;
755             memcpy(atoken.ticket, v5cred->ticket.data, atoken.ticketLen);
756 #ifndef HAVE_NO_KRB5_524
757         } else {
758             CREDENTIALS cred;
759
760             if (dflag)
761                 printf("Using Kerberos 524 translator service\n");
762
763             status = krb5_524_convert_creds(context, v5cred, &cred);
764
765             if (status) {
766                 afs_com_err(progname, status, "while converting tickets "
767                         "to Kerberos V4 format");
768                 return(AKLOG_KERBEROS);
769             }
770
771             strcpy (username, cred.pname);
772             if (cred.pinst[0]) {
773                 strcat (username, ".");
774                 strcat (username, cred.pinst);
775             }
776
777             atoken.kvno = cred.kvno;
778             atoken.startTime = cred.issue_date;
779             /*
780              * It seems silly to go through a bunch of contortions to
781              * extract the expiration time, when the v5 credentials already
782              * has the exact time!  Let's use that instead.
783              *
784              * Note that this isn't a security hole, as the expiration time
785              * is also contained in the encrypted token
786              */
787             atoken.endTime = v5cred->times.endtime;
788             memcpy(&atoken.sessionKey, cred.session, 8);
789             atoken.ticketLen = cred.ticket_st.length;
790             memcpy(atoken.ticket, cred.ticket_st.dat, atoken.ticketLen);
791 #endif /* HAVE_NO_KRB5_524 */
792         }
793         
794         if (!force &&
795             !ktc_GetToken(&aserver, &btoken, sizeof(btoken), &aclient) &&
796             atoken.kvno == btoken.kvno &&
797             atoken.ticketLen == btoken.ticketLen &&
798             !memcmp(&atoken.sessionKey, &btoken.sessionKey, sizeof(atoken.sessionKey)) &&
799             !memcmp(atoken.ticket, btoken.ticket, atoken.ticketLen)) {
800
801             if (dflag) {
802                 printf("Identical tokens already exist; skipping.\n");
803             }
804             return 0;
805         }
806
807 #ifdef FORCE_NOPRDB
808         noprdb = 1;
809 #endif
810
811 #ifndef WINDOWS
812         if (noprdb) {
813 #endif
814             if (dflag) {
815                 printf("Not resolving name %s to id (-noprdb set)\n",
816                         username);
817             }
818 #ifndef WINDOWS
819         }
820         else {
821             if ((status = get_user_realm(context, realm_of_user))) {
822                 fprintf(stderr, "%s: Couldn't determine realm of user:)",
823                         progname);
824                 afs_com_err(progname, status, " while getting realm");
825                 return(AKLOG_KERBEROS);
826             }
827             if (strcmp(realm_of_user, realm_of_cell)) {
828                 strcat(username, "@");
829                 strcat(username, realm_of_user);
830             }
831
832             if (dflag) {
833                 printf("About to resolve name %s to id in cell %s.\n", 
834                         username, aserver.cell);
835             }
836
837             strcpy(lastcell, aserver.cell);
838
839             if (!pr_Initialize (0, confname, aserver.cell))
840                     status = pr_SNameToId (username, &viceId);
841             
842             if (dflag) {
843                 if (status) 
844                     printf("Error %d\n", status);
845                 else
846                     printf("Id %d\n", (int) viceId);
847             }
848             
849                 /*
850                  * This is a crock, but it is Transarc's crock, so
851                  * we have to play along in order to get the
852                  * functionality.  The way the afs id is stored is
853                  * as a string in the username field of the token.
854                  * Contrary to what you may think by looking at
855                  * the code for tokens, this hack (AFS ID %d) will
856                  * not work if you change %d to something else.
857                  */
858
859                 /*
860                  * This code is taken from cklog -- it lets people
861                  * automatically register with the ptserver in foreign cells
862                  */
863
864 #ifdef ALLOW_REGISTER
865         if (status == 0) {
866             if (viceId != ANONYMOUSID) {
867 #else /* ALLOW_REGISTER */
868             if ((status == 0) && (viceId != ANONYMOUSID))
869 #endif /* ALLOW_REGISTER */
870                 sprintf (username, "AFS ID %d", (int) viceId);
871 #ifdef ALLOW_REGISTER
872             } else if (strcmp(realm_of_user, realm_of_cell) != 0) {
873                 if (dflag) {
874                     printf("doing first-time registration of %s "
875                             "at %s\n", username, cell_to_use);
876                 }
877                 id = 0;
878                 strncpy(aclient.name, username, MAXKTCNAMELEN - 1);
879                 strcpy(aclient.instance, "");
880                 strncpy(aclient.cell, realm_of_user, MAXKTCREALMLEN - 1);
881                 if ((status = ktc_SetToken(&aserver, &atoken, &aclient, 0))) {
882                     fprintf(stderr, "%s: unable to obtain tokens for cell %s "
883                             "(status: %d).\n", progname, cell_to_use, status);
884                     status = AKLOG_TOKEN;
885                 }
886
887                 /*
888                  * In case you're wondering, we don't need to change the
889                  * filename here because we're still connecting to the
890                  * same cell -- we're just using a different authentication
891                  * level
892                  */
893
894                 if ((status = pr_Initialize(1L, confname, aserver.cell))) {
895                     printf("Error %d\n", status);
896                 }
897
898                 if ((status = pr_CreateUser(username, &id))) {
899                     fprintf(stderr, "%s: %s so unable to create remote PTS "
900                             "user %s in cell %s (status: %d).\n", progname,
901                             error_message(status), username, cell_to_use,
902                             status);
903                 } else {
904                     printf("created cross-cell entry for %s (Id %d) at %s\n",
905                            username, id, cell_to_use);
906                     sprintf(username, "AFS ID %d", (int) id);
907                 }
908             }
909         }
910 #endif /* ALLOW_REGISTER */
911
912         }
913 #endif /* !WINDOWS */
914
915         if (dflag) {
916             fprintf(stdout, "Set username to %s\n", username);
917         }
918
919         /* Reset the "aclient" structure before we call ktc_SetToken.
920          * This structure was first set by the ktc_GetToken call when
921          * we were comparing whether identical tokens already existed.
922          */
923         strncpy(aclient.name, username, MAXKTCNAMELEN - 1);
924         strcpy(aclient.instance, "");
925         strncpy(aclient.cell, realm_of_user, MAXKTCREALMLEN - 1);
926
927         if (dflag) {
928             printf("Setting tokens. %s / %s @ %s \n",
929                     aclient.name, aclient.instance, aclient.cell );
930         }
931 #ifndef AFS_AIX51_ENV
932         /* on AIX 4.1.4 with AFS 3.4a+ if a write is not done before 
933          * this routine, it will not add the token. It is not clear what 
934          * is going on here! So we will do the following operation.
935          * On AIX 5, it causes the parent program to die, so we won't.
936          */
937         write(2,"",0); /* dummy write */
938 #endif
939 #ifndef WINDOWS
940         if ((status = ktc_SetToken(&aserver, &atoken, &aclient, afssetpag))) {
941             fprintf(stderr, 
942                     "%s: unable to obtain tokens for cell %s (status: %d).\n",
943                     progname, cell_to_use, status);
944             status = AKLOG_TOKEN;
945         }
946 #else /* WINDOWS */
947         /* Note switched 2nd and 3rd args */
948         if ((status = ktc_SetToken(&aserver, &atoken, &aclient, afssetpag))) {
949             switch(status) {
950             case KTC_INVAL:
951                 fprintf(stderr, "%s: Bad ticket length", progname);
952                 break;
953             case KTC_PIOCTLFAIL:
954                 fprintf(stderr, "%s: Unknown error contacting AFS service",
955                         progname);
956                 break;
957             case KTC_NOCELL:
958                 fprintf(stderr, "%s: Cell name (%s) not recognized by AFS service",
959                         progname, realm_of_cell);
960                 break;
961             case KTC_NOCM:
962                 fprintf(stderr, "%s: AFS service is unavailable", progname);
963                 break;
964             default:
965                 fprintf(stderr, "%s: Undocumented error (%d) contacting AFS service", progname, status);
966                 break;  
967             }
968             status = AKLOG_TOKEN;           
969         }
970 #endif /* !WINDOWS */
971     }
972     else
973         if (dflag) {
974             printf("Noauth mode; not authenticating.\n");
975         }
976         
977     return(status);
978 }
979
980 #ifndef WINDOWS /* struct ViceIoctl missing */
981
982 static int get_afs_mountpoint(char *file, char *mountpoint, int size)
983 {
984 #ifdef AFS_SUN_ENV
985         char V ='V'; /* AFS has problem on Sun with pioctl */
986 #endif
987     char our_file[MAXPATHLEN + 1];
988     char *parent_dir;
989     char *last_component;
990     struct ViceIoctl vio;
991     char cellname[BUFSIZ];
992
993     memset(our_file, 0, sizeof(our_file));
994     strcpy(our_file, file);
995
996     if ((last_component = strrchr(our_file, DIR))) {
997         *last_component++ = 0;
998         parent_dir = our_file;
999     }
1000     else {
1001         last_component = our_file;
1002         parent_dir = ".";
1003     }    
1004     
1005     memset(cellname, 0, sizeof(cellname));
1006
1007     vio.in = last_component;
1008     vio.in_size = strlen(last_component)+1;
1009     vio.out_size = size;
1010     vio.out = mountpoint;
1011
1012     if (!pioctl(parent_dir, VIOC_AFS_STAT_MT_PT, &vio, 0)) {
1013         if (strchr(mountpoint, VOLMARKER) == NULL) {
1014             vio.in = file;
1015             vio.in_size = strlen(file) + 1;
1016             vio.out_size = sizeof(cellname);
1017             vio.out = cellname;
1018             
1019             if (!pioctl(file, VIOC_FILE_CELL_NAME, &vio, 1)) {
1020                 strcat(cellname, VOLMARKERSTRING);
1021                 strcat(cellname, mountpoint + 1);
1022                 memset(mountpoint + 1, 0, size - 1);
1023                 strcpy(mountpoint + 1, cellname);
1024             }
1025         }
1026         return(TRUE);
1027     }
1028     else
1029         return(FALSE);
1030 }
1031
1032 /* 
1033  * This routine each time it is called returns the next directory 
1034  * down a pathname.  It resolves all symbolic links.  The first time
1035  * it is called, it should be called with the name of the path
1036  * to be descended.  After that, it should be called with the arguemnt
1037  * NULL.
1038  */
1039 static char *next_path(char *origpath)
1040 {
1041     static char path[MAXPATHLEN + 1];
1042     static char pathtocheck[MAXPATHLEN + 1];
1043
1044     int link = FALSE;           /* Is this a symbolic link? */
1045     char linkbuf[MAXPATHLEN + 1];
1046     char tmpbuf[MAXPATHLEN + 1];
1047
1048     static char *last_comp;     /* last component of directory name */
1049     static char *elast_comp;    /* End of last component */
1050     char *t;
1051     int len;
1052     
1053     static int symlinkcount = 0; /* We can't exceed MAXSYMLINKS */
1054     
1055     /* If we are given something for origpath, we are initializing only. */
1056     if (origpath) {
1057         memset(path, 0, sizeof(path));
1058         memset(pathtocheck, 0, sizeof(pathtocheck));
1059         strcpy(path, origpath);
1060         last_comp = path;
1061         symlinkcount = 0;
1062         return(NULL);
1063     }
1064
1065     /* We were not given origpath; find then next path to check */
1066     
1067     /* If we've gotten all the way through already, return NULL */
1068     if (last_comp == NULL)
1069         return(NULL);
1070
1071     do {
1072         while (*last_comp == DIR)
1073             strncat(pathtocheck, last_comp++, 1);
1074         len = (elast_comp = strchr(last_comp, DIR)) 
1075             ? elast_comp - last_comp : strlen(last_comp);
1076         strncat(pathtocheck, last_comp, len);
1077         memset(linkbuf, 0, sizeof(linkbuf));
1078         if (link = (readlink(pathtocheck, linkbuf, 
1079                                     sizeof(linkbuf)) > 0)) {
1080             if (++symlinkcount > MAXSYMLINKS) {
1081                 fprintf(stderr, "%s: %s\n", progname, strerror(ELOOP));
1082                 exit(AKLOG_BADPATH);
1083             }
1084             memset(tmpbuf, 0, sizeof(tmpbuf));
1085             if (elast_comp)
1086                 strcpy(tmpbuf, elast_comp);
1087             if (linkbuf[0] == DIR) {
1088                 /* 
1089                  * If this is a symbolic link to an absolute path, 
1090                  * replace what we have by the absolute path.
1091                  */
1092                 memset(path, 0, strlen(path));
1093                 memcpy(path, linkbuf, sizeof(linkbuf));
1094                 strcat(path, tmpbuf);
1095                 last_comp = path;
1096                 elast_comp = NULL;
1097                 memset(pathtocheck, 0, sizeof(pathtocheck));
1098             }
1099             else {
1100                 /* 
1101                  * If this is a symbolic link to a relative path, 
1102                  * replace only the last component with the link name.
1103                  */
1104                 strncpy(last_comp, linkbuf, strlen(linkbuf) + 1);
1105                 strcat(path, tmpbuf);
1106                 elast_comp = NULL;
1107                 if ((t = strrchr(pathtocheck, DIR))) {
1108                     t++;
1109                     memset(t, 0, strlen(t));
1110                 }
1111                 else
1112                     memset(pathtocheck, 0, sizeof(pathtocheck));
1113             }
1114         }
1115         else
1116             last_comp = elast_comp;
1117     }
1118     while(link);
1119
1120     return(pathtocheck);
1121 }
1122
1123 #endif /* WINDOWS */
1124
1125 #if 0
1126 /*****************************************/
1127 int dee_gettokens()
1128 {
1129 #ifdef AFS_SUN_ENV
1130         char V = 'V'; /* AFS has problem on SunOS */
1131 #endif
1132    struct ViceIoctl vio;
1133    char outbuf[BUFSIZ];
1134    long ind;
1135    int fd;
1136
1137    memset(outbuf, 0, sizeof(outbuf));
1138
1139    vio.out_size = sizeof(outbuf);
1140    vio.in_size = sizeof(ind);
1141    vio.out = outbuf;
1142    vio.in = &ind;
1143
1144    ind = 0;
1145    fd = open("dee.tok",O_WRONLY);
1146    while(!pioctl(0,VIOCGETTOK,&vio,0)) {
1147         write(fd,&outbuf,sizeof(outbuf)); 
1148        ind++;
1149    }
1150    close(fd);
1151 }
1152 /*****************************************/
1153 #endif
1154
1155 #ifndef WINDOWS /* struct ViceIoctl missing */
1156
1157 static void add_hosts(char *file)
1158 {
1159 #ifdef AFS_SUN_ENV
1160         char V = 'V'; /* AFS has problem on SunOS */
1161 #endif
1162     struct ViceIoctl vio;
1163     char outbuf[BUFSIZ];
1164     long *phosts;
1165     int i;
1166     struct hostent *hp;
1167     struct in_addr in;
1168     
1169     memset(outbuf, 0, sizeof(outbuf));
1170
1171     vio.out_size = sizeof(outbuf);
1172     vio.in_size = 0;
1173     vio.out = outbuf;
1174
1175     if (dflag) {
1176         printf("Getting list of hosts for %s\n", file);
1177     }
1178     /* Don't worry about errors. */
1179     if (!pioctl(file, VIOCWHEREIS, &vio, 1)) {
1180         phosts = (long *) outbuf;
1181
1182         /*
1183          * Lists hosts that we care about.  If ALLHOSTS is defined,
1184          * then all hosts that you ever may possible go through are
1185          * included in this list.  If not, then only hosts that are
1186          * the only ones appear.  That is, if a volume you must use
1187          * is replaced on only one server, that server is included.
1188          * If it is replicated on many servers, then none are included.
1189          * This is not perfect, but the result is that people don't
1190          * get subscribed to a lot of instances of FILSRV that they
1191          * probably won't need which reduces the instances of 
1192          * people getting messages that don't apply to them.
1193          */
1194 #ifndef ALLHOSTS
1195         if (phosts[1] != '\0')
1196             return;
1197 #endif
1198         for (i = 0; phosts[i]; i++) {
1199             if (hosts) {
1200                 in.s_addr = phosts[i];
1201                 if (dflag) {
1202                     printf("Got host %s\n", inet_ntoa(in));
1203                 }
1204                 ll_string(&hostlist, ll_s_add, (char *)inet_ntoa(in));
1205             }
1206             if (zsubs && (hp=gethostbyaddr((char *) &phosts[i],sizeof(long),AF_INET))) {
1207                 if (dflag) {
1208                     printf("Got host %s\n", hp->h_name);
1209                 }
1210                 ll_string(&zsublist, ll_s_add, hp->h_name);
1211             }
1212         }
1213     }
1214 }
1215
1216 #endif /* WINDOWS */
1217
1218 #ifndef WINDOWS /* next_path(), get_afs_mountpoint() */
1219
1220 /*
1221  * This routine descends through a path to a directory, logging to 
1222  * every cell it encounters along the way.
1223  */
1224 static int auth_to_path(krb5_context context, char *path)
1225 {
1226     int status = AKLOG_SUCCESS;
1227     int auth_to_cell_status = AKLOG_SUCCESS;
1228
1229     char *nextpath;
1230     char pathtocheck[MAXPATHLEN + 1];
1231     char mountpoint[MAXPATHLEN + 1];
1232
1233     char *cell;
1234     char *endofcell;
1235
1236     u_char isdirectory;
1237
1238     /* Initialize */
1239     if (path[0] == DIR)
1240         strcpy(pathtocheck, path);
1241     else {
1242         if (getcwd(pathtocheck, sizeof(pathtocheck)) == NULL) {
1243             fprintf(stderr, "Unable to find current working directory:\n");
1244             fprintf(stderr, "%s\n", pathtocheck);
1245             fprintf(stderr, "Try an absolute pathname.\n");
1246             exit(AKLOG_BADPATH);
1247         }
1248         else {
1249             strcat(pathtocheck, DIRSTRING);
1250             strcat(pathtocheck, path);
1251         }
1252     }
1253     next_path(pathtocheck);
1254
1255     /* Go on to the next level down the path */
1256     while ((nextpath = next_path(NULL))) {
1257         strcpy(pathtocheck, nextpath);
1258         if (dflag) {
1259             printf("Checking directory %s\n", pathtocheck);
1260         }
1261         /* 
1262          * If this is an afs mountpoint, determine what cell from 
1263          * the mountpoint name which is of the form 
1264          * #cellname:volumename or %cellname:volumename.
1265          */
1266         if (get_afs_mountpoint(pathtocheck, mountpoint, sizeof(mountpoint))) {
1267             /* skip over the '#' or '%' */
1268             cell = mountpoint + 1;
1269             /* Add this (cell:volumename) to the list of zsubs */
1270             if (zsubs)
1271                 ll_string(&zsublist, ll_s_add, cell);
1272             if (zsubs || hosts)
1273                 add_hosts(pathtocheck);
1274             if ((endofcell = strchr(mountpoint, VOLMARKER))) {
1275                 *endofcell = '\0';
1276                 if ((auth_to_cell_status = auth_to_cell(context, cell, NULL))) {
1277                     if (status == AKLOG_SUCCESS)
1278                         status = auth_to_cell_status;
1279                     else if (status != auth_to_cell_status)
1280                         status = AKLOG_SOMETHINGSWRONG;
1281                 }
1282             }
1283         }
1284         else {
1285             if (isdir(pathtocheck, &isdirectory) < 0) {
1286                 /*
1287                  * If we've logged and still can't stat, there's
1288                  * a problem... 
1289                  */
1290                 fprintf(stderr, "%s: stat(%s): %s\n", progname, 
1291                         pathtocheck, strerror(errno));
1292                 return(AKLOG_BADPATH);
1293             }
1294             else if (! isdirectory) {
1295                 /* Allow only directories */
1296                 fprintf(stderr, "%s: %s: %s\n", progname, pathtocheck,
1297                         strerror(ENOTDIR));
1298                 return(AKLOG_BADPATH);
1299             }
1300         }
1301     }
1302     
1303
1304     return(status);
1305 }
1306
1307 #endif /* WINDOWS */
1308
1309
1310 /* Print usage message and exit */
1311 static void usage(void)
1312 {
1313     fprintf(stderr, "\nUsage: %s %s%s%s\n", progname,
1314             "[-d] [[-cell | -c] cell [-k krb_realm]] ",
1315             "[[-p | -path] pathname]\n",
1316             "    [-zsubs] [-hosts] [-noauth] [-noprdb] [-force] [-setpag] \n"
1317                 "    [-linked]"
1318 #ifndef HAVE_NO_KRB5_524
1319                 " [-524]"
1320 #endif
1321                 "\n");
1322     fprintf(stderr, "    -d gives debugging information.\n");
1323     fprintf(stderr, "    krb_realm is the kerberos realm of a cell.\n");
1324     fprintf(stderr, "    pathname is the name of a directory to which ");
1325     fprintf(stderr, "you wish to authenticate.\n");
1326     fprintf(stderr, "    -zsubs gives zephyr subscription information.\n");
1327     fprintf(stderr, "    -hosts gives host address information.\n");
1328     fprintf(stderr, "    -noauth does not attempt to get tokens.\n");
1329     fprintf(stderr, "    -noprdb means don't try to determine AFS ID.\n");
1330     fprintf(stderr, "    -force means replace identical tickets. \n");
1331     fprintf(stderr, "    -linked means if AFS node is linked, try both. \n");
1332     fprintf(stderr, "    -setpag set the AFS process authentication group.\n");
1333 #ifndef HAVE_NO_KRB5_524
1334     fprintf(stderr, "    -524 means use the 524 converter instead of V5 directly\n");
1335 #endif
1336     fprintf(stderr, "    No commandline arguments means ");
1337     fprintf(stderr, "authenticate to the local cell.\n");
1338     fprintf(stderr, "\n");
1339     exit(AKLOG_USAGE);
1340 }
1341
1342 void aklog(int argc, char *argv[])
1343 {
1344         krb5_context context;
1345     int status = AKLOG_SUCCESS;
1346     int i;
1347     int somethingswrong = FALSE;
1348
1349     cellinfo_t cellinfo;
1350
1351     extern char *progname;      /* Name of this program */
1352
1353     extern int dflag;           /* Debug mode */
1354
1355     int cmode = FALSE;          /* Cellname mode */
1356     int pmode = FALSE;          /* Path name mode */
1357
1358     char realm[REALM_SZ];       /* Kerberos realm of afs server */
1359     char cell[BUFSIZ];          /* Cell to which we are authenticating */
1360     char path[MAXPATHLEN + 1];          /* Path length for path mode */
1361
1362     linked_list cells;          /* List of cells to log to */
1363     linked_list paths;          /* List of paths to log to */
1364     ll_node *cur_node;
1365
1366     memset(&cellinfo, 0, sizeof(cellinfo));
1367
1368     memset(realm, 0, sizeof(realm));
1369     memset(cell, 0, sizeof(cell));
1370     memset(path, 0, sizeof(path));
1371
1372     ll_init(&cells);
1373     ll_init(&paths);
1374
1375     ll_init(&zsublist);
1376     ll_init(&hostlist);
1377
1378     /* Store the program name here for error messages */
1379     if ((progname = strrchr(argv[0], DIR)))
1380         progname++;
1381     else
1382         progname = argv[0];
1383
1384     krb5_init_context(&context);
1385 #ifndef WINDOWS
1386         initialize_ktc_error_table ();
1387 #endif
1388
1389     /* Initialize list of cells to which we have authenticated */
1390     (void)ll_init(&authedcells);
1391
1392     /* Parse commandline arguments and make list of what to do. */
1393     for (i = 1; i < argc; i++) {
1394         if (strcmp(argv[i], "-d") == 0)
1395             dflag++;
1396         else if (strcmp(argv[i], "-noauth") == 0) 
1397             noauth++;
1398         else if (strcmp(argv[i], "-zsubs") == 0)
1399             zsubs++;
1400         else if (strcmp(argv[i], "-hosts") == 0)
1401             hosts++;
1402         else if (strcmp(argv[i], "-noprdb") == 0)
1403             noprdb++;
1404         else if (strcmp(argv[i], "-linked") == 0)
1405                 linked++;
1406         else if (strcmp(argv[i], "-force") == 0)
1407             force++;
1408 #ifndef HAVE_NO_KRB5_524
1409         else if (strcmp(argv[i], "-524") == 0)
1410             do524++;
1411 #endif
1412     else if (strcmp(argv[i], "-setpag") == 0)
1413             afssetpag++;
1414         else if (((strcmp(argv[i], "-cell") == 0) ||
1415                   (strcmp(argv[i], "-c") == 0)) && !pmode)
1416             if (++i < argc) {
1417                 cmode++;
1418                 strcpy(cell, argv[i]);
1419             }
1420             else
1421                 usage();
1422         else if ((strcmp(argv[i], "-keytab") == 0))
1423             if (++i < argc) {
1424                 keytab = argv[i];
1425             }
1426             else
1427                 usage();
1428         else if ((strcmp(argv[i], "-principal") == 0))
1429             if (++i < argc) {
1430                 client = argv[i];
1431             }
1432             else
1433                 usage();
1434         else if (((strcmp(argv[i], "-path") == 0) ||
1435                   (strcmp(argv[i], "-p") == 0)) && !cmode)
1436 #ifndef WINDOWS
1437             if (++i < argc) {
1438                 pmode++;
1439                 strcpy(path, argv[i]);
1440             }
1441             else
1442                 usage();
1443 #else /* WINDOWS */
1444         {
1445             fprintf(stderr, "%s: path mode not supported.\n", progname);
1446             exit(AKLOG_MISC);
1447         }
1448 #endif /* WINDOWS */
1449             
1450         else if (argv[i][0] == '-')
1451             usage();
1452         else if (!pmode && !cmode) {
1453             if (strchr(argv[i], DIR) || (strcmp(argv[i], ".") == 0) ||
1454                 (strcmp(argv[i], "..") == 0)) {
1455 #ifndef WINDOWS
1456                 pmode++;
1457                 strcpy(path, argv[i]);
1458 #else /* WINDOWS */
1459                 fprintf(stderr, "%s: path mode not supported.\n", progname);
1460                 exit(AKLOG_MISC);
1461 #endif /* WINDOWS */
1462             }
1463             else { 
1464                 cmode++;
1465                 strcpy(cell, argv[i]);
1466             }
1467         }
1468         else
1469             usage();
1470
1471         if (cmode) {
1472             if (((i + 1) < argc) && (strcmp(argv[i + 1], "-k") == 0)) {
1473                 i+=2;
1474                 if (i < argc)
1475                     strcpy(realm, argv[i]);
1476                 else
1477                     usage();
1478             }
1479             /* Add this cell to list of cells */
1480             strcpy(cellinfo.cell, cell);
1481             strcpy(cellinfo.realm, realm);
1482             if ((cur_node = ll_add_node(&cells, ll_tail))) {
1483                 char *new_cellinfo;
1484                 if ((new_cellinfo = copy_cellinfo(&cellinfo)))
1485                     ll_add_data(cur_node, new_cellinfo);
1486                 else {
1487                     fprintf(stderr, 
1488                             "%s: failure copying cellinfo.\n", progname);
1489                     exit(AKLOG_MISC);
1490                 }
1491             }
1492             else {
1493                 fprintf(stderr, "%s: failure adding cell to cells list.\n",
1494                         progname);
1495                 exit(AKLOG_MISC);
1496             }
1497             memset(&cellinfo, 0, sizeof(cellinfo));
1498             cmode = FALSE;
1499             memset(cell, 0, sizeof(cell));
1500             memset(realm, 0, sizeof(realm));
1501         }
1502 #ifndef WINDOWS
1503         else if (pmode) {
1504             /* Add this path to list of paths */
1505             if ((cur_node = ll_add_node(&paths, ll_tail))) {
1506                 char *new_path;
1507                 if ((new_path = strdup(path)))
1508                     ll_add_data(cur_node, new_path);
1509                 else {
1510                     fprintf(stderr, "%s: failure copying path name.\n",
1511                             progname);
1512                     exit(AKLOG_MISC);
1513                 }
1514             }
1515             else {
1516                 fprintf(stderr, "%s: failure adding path to paths list.\n",
1517                         progname);
1518                 exit(AKLOG_MISC);
1519             }
1520             pmode = FALSE;
1521             memset(path, 0, sizeof(path));
1522         }
1523 #endif /* WINDOWS */
1524     }
1525
1526     /*
1527      * The code that _used_ to be here called setpag().  When you think
1528      * about this, doing this makes no sense!  setpag() allocates a PAG
1529      * only for the current process, so the token installed would have
1530      * not be usable in the parent!  Since ktc_SetToken() now takes a
1531      * 4th argument to control whether or not we're going to allocate
1532      * a PAG (and since when you do it _that_ way, it modifies the cred
1533      * structure of your parent)), why don't we use that instead?
1534      */
1535
1536 #if 0
1537     if (afssetpag) {
1538            status = setpag();
1539            if (dflag) { 
1540              int i,j;
1541                  int gidsetlen = 50;
1542          int gidset[50];
1543
1544                  printf("setpag %d\n",status);
1545              j = getgroups(gidsetlen,gidset);
1546          printf("Groups(%d):",j);
1547          for (i = 0; i<j; i++) {
1548            printf("%d",gidset[i]);
1549            if((i+1)<j) printf(",");
1550          }
1551          printf("\n");
1552            }
1553         }
1554 #endif
1555     /* If nothing was given, log to the local cell. */
1556     if ((cells.nelements + paths.nelements) == 0) {
1557                 struct passwd *pwd;
1558
1559                 status = auth_to_cell(context, NULL, NULL);
1560         
1561                 /* If this cell is linked to a DCE cell, and user 
1562                  * requested -linked, get tokens for both 
1563                  * This is very usefull when the AFS cell is linked to a DFS 
1564                  * cell and this system does not also have DFS. 
1565                  */
1566
1567                 if (!status && linked && linkedcell[0]) {
1568                                 strncpy(linkedcell2,linkedcell,MAXCELLCHARS);
1569                             if (dflag) {
1570                                 printf("Linked cell: %s\n", linkedcell);
1571                             }
1572                                 status = auth_to_cell(context, linkedcell2, NULL);
1573                 }
1574
1575 #ifndef WINDOWS
1576                 /*
1577                  * Local hack - if the person has a file in their home
1578                  * directory called ".xlog", read that for a list of
1579                  * extra cells to authenticate to
1580                  */
1581
1582                 if ((pwd = getpwuid(getuid())) != NULL) {
1583                     struct stat sbuf;
1584                     FILE *f;
1585                     char fcell[100], xlog_path[512];
1586
1587                     strcpy(xlog_path, pwd->pw_dir);
1588                     strcat(xlog_path, "/.xlog");
1589
1590                     if ((stat(xlog_path, &sbuf) == 0) &&
1591                         ((f = fopen(xlog_path, "r")) != NULL)) {
1592
1593                         if (dflag) {
1594                             printf("Reading %s for cells to "
1595                                     "authenticate to.\n", xlog_path);
1596                         }
1597
1598                         while (fgets(fcell, 100, f) != NULL) {
1599                             int auth_status;
1600
1601                             fcell[strlen(fcell) - 1] = '\0';
1602
1603                             if (dflag) {
1604                                 printf("Found cell %s in %s.\n",
1605                                         fcell, xlog_path);
1606                             }
1607
1608                             auth_status = auth_to_cell(context, fcell, NULL);
1609                             if (status == AKLOG_SUCCESS)
1610                                 status = auth_status;
1611                             else
1612                                 status = AKLOG_SOMETHINGSWRONG;
1613                         }
1614                     }
1615                 }
1616 #endif /* WINDOWS */
1617         }
1618     else {
1619         /* Log to all cells in the cells list first */
1620         for (cur_node = cells.first; cur_node; cur_node = cur_node->next) {
1621             memcpy((char *)&cellinfo, cur_node->data, sizeof(cellinfo));
1622             if ((status = auth_to_cell(context, cellinfo.cell, cellinfo.realm)))
1623                 somethingswrong++;
1624                 else {
1625                         if (linked && linkedcell[0]) {
1626                                 strncpy(linkedcell2,linkedcell,MAXCELLCHARS);
1627                 if (dflag) {
1628                     printf("Linked cell: %s\n",
1629                         linkedcell);
1630                 }
1631                                 if ((status = auth_to_cell(context,linkedcell2,
1632                                                          cellinfo.realm)))
1633                                 somethingswrong++;
1634                         }
1635                 }
1636         }
1637         
1638 #ifndef WINDOWS
1639         /* Then, log to all paths in the paths list */
1640         for (cur_node = paths.first; cur_node; cur_node = cur_node->next) {
1641             if ((status = auth_to_path(context, cur_node->data)))
1642                 somethingswrong++;
1643         }
1644 #endif /* WINDOWS */
1645         
1646         /* 
1647          * If only one thing was logged to, we'll return the status 
1648          * of the single call.  Otherwise, we'll return a generic
1649          * something failed status.
1650          */
1651         if (somethingswrong && ((cells.nelements + paths.nelements) > 1))
1652             status = AKLOG_SOMETHINGSWRONG;
1653     }
1654
1655     /* If we are keeping track of zephyr subscriptions, print them. */
1656     if (zsubs) 
1657         for (cur_node = zsublist.first; cur_node; cur_node = cur_node->next) {
1658             printf("zsub: %s\n", cur_node->data);
1659         }
1660
1661     /* If we are keeping track of host information, print it. */
1662     if (hosts)
1663         for (cur_node = hostlist.first; cur_node; cur_node = cur_node->next) {
1664             printf("host: %s\n", cur_node->data);
1665         }
1666
1667     exit(status);
1668 }
1669
1670 static int isdir(char *path, unsigned char *val)
1671 {
1672     struct stat statbuf;
1673
1674     if (lstat(path, &statbuf) < 0)
1675         return (-1);
1676     else {
1677         if ((statbuf.st_mode & S_IFMT) == S_IFDIR) 
1678             *val = TRUE;
1679         else
1680             *val = FALSE;
1681         return (0);
1682     }  
1683 }
1684
1685 static krb5_error_code get_credv5_akimpersonate(krb5_context context,
1686                                                 char* keytab,
1687                                                 krb5_principal service_principal,
1688                                                 krb5_principal client_principal,
1689                                                 time_t starttime,
1690                                                 time_t endtime,
1691                                                 int *allowed_enctypes,
1692                                                 int *paddress,
1693                                                 krb5_creds** out_creds /* out */ )
1694 {
1695 #if defined(USING_HEIMDAL) || (defined(HAVE_ENCODE_KRB5_ENC_TKT) && defined(HAVE_ENCODE_KRB5_TICKET) && defined(HAVE_KRB5_C_ENCRYPT))
1696     krb5_error_code code;
1697     krb5_keytab kt = 0;
1698     krb5_kt_cursor cursor[1];
1699     krb5_keytab_entry entry[1];
1700     krb5_ccache cc = 0;
1701     krb5_creds *creds = 0;
1702     krb5_enctype enctype;
1703     krb5_kvno kvno;
1704     krb5_keyblock session_key[1];
1705 #if USING_HEIMDAL
1706     Ticket ticket_reply[1];
1707     EncTicketPart enc_tkt_reply[1];
1708     krb5_address address[30];
1709     krb5_addresses faddr[1];
1710     int temp_vno[1];
1711     time_t temp_time[2];
1712 #else
1713     krb5_ticket ticket_reply[1];
1714     krb5_enc_tkt_part enc_tkt_reply[1];
1715     krb5_address address[30], *faddr[30];
1716 #endif
1717     krb5_data * temp;
1718     int i;
1719     static int any_enctype[] = {0};
1720     *out_creds = 0;
1721     if (!(creds = malloc(sizeof *creds))) {
1722         code = ENOMEM;
1723         goto cleanup;
1724     }
1725     if (!allowed_enctypes)
1726         allowed_enctypes = any_enctype;
1727
1728     cc = 0;
1729     enctype = 0; /* AKIMPERSONATE_IGNORE_ENCTYPE */
1730     kvno = 0; /* AKIMPERSONATE_IGNORE_VNO */
1731     memset((char*)creds, 0, sizeof *creds);
1732     memset((char*)entry, 0, sizeof *entry);
1733     memset((char*)session_key, 0, sizeof *session_key);
1734     memset((char*)ticket_reply, 0, sizeof *ticket_reply);
1735     memset((char*)enc_tkt_reply, 0, sizeof *enc_tkt_reply);
1736     code = krb5_kt_resolve(context, keytab, &kt);
1737     if (code) {
1738         if (keytab)
1739             afs_com_err(progname, code, "while resolving keytab %s", keytab);
1740         else
1741             afs_com_err(progname, code, "while resolving default keytab");
1742         goto cleanup;
1743     }
1744
1745     if (service_principal) {
1746         for (i = 0; (enctype = allowed_enctypes[i]) || !i; ++i) {
1747             code = krb5_kt_get_entry(context,
1748                                      kt,
1749                                      service_principal,
1750                                      kvno,
1751                                      enctype,
1752                                      entry);
1753             if (!code) {
1754                 if (allowed_enctypes[i])
1755                     deref_keyblock_enctype(session_key) = allowed_enctypes[i];
1756                 break;
1757             }
1758         }
1759         if (code) {
1760             afs_com_err(progname, code,"while scanning keytab entries");
1761             goto cleanup;
1762         }
1763     } else {
1764         krb5_keytab_entry new[1];
1765         int best = -1;
1766         memset(new, 0, sizeof *new);
1767         if ((code == krb5_kt_start_seq_get(context, kt, cursor))) {
1768             afs_com_err(progname, code, "while starting keytab scan");
1769             goto cleanup;
1770         }
1771         while (!(code = krb5_kt_next_entry(context, kt, new, cursor))) {
1772             for (i = 0;
1773                     allowed_enctypes[i] && allowed_enctypes[i]
1774                      != deref_entry_enctype(new); ++i)
1775                 ;
1776             if ((!i || allowed_enctypes[i]) &&
1777                 (best < 0 || best > i)) {
1778                 krb5_free_keytab_entry_contents(context, entry);
1779                 *entry = *new;
1780                 memset(new, 0, sizeof *new);
1781             } else krb5_free_keytab_entry_contents(context, new);
1782         }
1783         if ((i = krb5_kt_end_seq_get(context, kt, cursor))) {
1784             afs_com_err(progname, i, "while ending keytab scan");
1785             code = i;
1786             goto cleanup;
1787         }
1788         if (best < 0) {
1789             afs_com_err(progname, code, "while scanning keytab");
1790             goto cleanup;
1791         }
1792         deref_keyblock_enctype(session_key) = deref_entry_enctype(entry);
1793     }
1794
1795     /* Make Ticket */
1796
1797 #if USING_HEIMDAL
1798     if ((code = krb5_generate_random_keyblock(context,
1799                                               deref_keyblock_enctype(session_key), session_key))) {
1800         afs_com_err(progname, code, "while making session key");
1801         goto cleanup;
1802     }
1803     enc_tkt_reply->flags.initial = 1;
1804     enc_tkt_reply->transited.tr_type = DOMAIN_X500_COMPRESS;
1805     enc_tkt_reply->cname = client_principal->name;
1806     enc_tkt_reply->crealm = client_principal->realm;
1807     enc_tkt_reply->key = *session_key;
1808     {
1809         static krb5_data empty_string;
1810         enc_tkt_reply->transited.contents = empty_string;
1811     }
1812     enc_tkt_reply->authtime = starttime;
1813     enc_tkt_reply->starttime = temp_time;
1814     *enc_tkt_reply->starttime = starttime;
1815 #if 0
1816     enc_tkt_reply->renew_till = temp_time + 1;
1817     *enc_tkt_reply->renew_till = endtime;
1818 #endif
1819     enc_tkt_reply->endtime = endtime;
1820 #else
1821     if ((code = krb5_c_make_random_key(context,
1822                                        deref_keyblock_enctype(session_key), session_key))) {
1823         afs_com_err(progname, code, "while making session key");
1824         goto cleanup;
1825     }
1826     enc_tkt_reply->magic = KV5M_ENC_TKT_PART;
1827 #define DATACAST        (unsigned char *)
1828     enc_tkt_reply->flags |= TKT_FLG_INITIAL;
1829     enc_tkt_reply->transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;
1830     enc_tkt_reply->session = session_key;
1831     enc_tkt_reply->client = client_principal;
1832     {
1833         static krb5_data empty_string;
1834         enc_tkt_reply->transited.tr_contents = empty_string;
1835     }
1836     enc_tkt_reply->times.authtime = starttime;
1837     enc_tkt_reply->times.starttime = starttime; /* krb524init needs this */
1838     enc_tkt_reply->times.endtime = endtime;
1839 #endif  /* USING_HEIMDAL */
1840     /* NB:  We will discard address for now--ignoring caddr field               
1841        in any case.  MIT branch does what it always did. */
1842
1843     if (paddress && *paddress) {
1844         deref_enc_tkt_addrs(enc_tkt_reply) = faddr;
1845 #if USING_HEIMDAL
1846         faddr->len = 0;
1847         faddr->val = address;
1848 #endif
1849         for (i = 0; paddress[i]; ++i) {
1850 #if USING_HEIMDAL
1851             address[i].addr_type = KRB5_ADDRESS_INET;
1852             address[i].address.data = (void*)(paddress+i);
1853             address[i].address.length = sizeof(paddress[i]);
1854 #else
1855 #if !USING_SSL
1856             address[i].magic = KV5M_ADDRESS;
1857             address[i].addrtype = ADDRTYPE_INET;
1858 #else
1859             address[i].addrtype = AF_INET;
1860 #endif
1861             address[i].contents = (void*)(paddress+i);
1862             address[i].length = sizeof(int);
1863             faddr[i] = address+i;
1864 #endif
1865         }
1866 #if USING_HEIMDAL
1867         faddr->len = i;
1868 #else
1869         faddr[i] = 0;
1870 #endif
1871     }
1872
1873 #if USING_HEIMDAL
1874     ticket_reply->sname = service_principal->name;
1875     ticket_reply->realm = service_principal->realm;
1876
1877     { /* crypto block */
1878         krb5_crypto crypto = 0;
1879         unsigned char *buf = 0;
1880         size_t buf_size, buf_len;
1881         char *what;
1882
1883         ASN1_MALLOC_ENCODE(EncTicketPart, buf, buf_size,
1884                            enc_tkt_reply, &buf_len, code);
1885         if(code) {
1886             afs_com_err(progname, code, "while encoding ticket");
1887             goto cleanup;
1888         }
1889
1890         if(buf_len != buf_size) {
1891             afs_com_err(progname, code,
1892                     "%d != %d while encoding ticket (internal ASN.1 encoder error",
1893                     buf_len, buf_size);
1894             goto cleanup;
1895         }
1896         what = "krb5_crypto_init";
1897         code = krb5_crypto_init(context,
1898                                 &deref_entry_keyblock(entry),
1899                                 deref_entry_enctype(entry),
1900                                 &crypto);
1901         if(!code) {
1902             what = "krb5_encrypt";
1903             code = krb5_encrypt_EncryptedData(context, crypto, KRB5_KU_TICKET,
1904                                               buf, buf_len, entry->vno, &(ticket_reply->enc_part));
1905         }
1906         if (buf) free(buf);
1907         if (crypto) krb5_crypto_destroy(context, crypto);
1908         if(code) {
1909             afs_com_err(progname, code, "while %s", what);
1910             goto cleanup;
1911         }
1912     } /* crypto block */
1913     ticket_reply->enc_part.etype = deref_entry_enctype(entry);
1914     ticket_reply->enc_part.kvno = temp_vno;
1915     *ticket_reply->enc_part.kvno = entry->vno;
1916     ticket_reply->tkt_vno = 5;
1917 #else
1918     ticket_reply->server = service_principal;
1919     ticket_reply->enc_part2 = enc_tkt_reply;
1920     if ((code = krb5_encrypt_tkt_part(context, &deref_entry_keyblock(entry), ticket_reply))) {
1921         afs_com_err(progname, code, "while making ticket");
1922         goto cleanup;
1923     }
1924     ticket_reply->enc_part.kvno = entry->vno;
1925 #endif
1926
1927     /* Construct Creds */
1928
1929     if ((code = krb5_copy_principal(context, service_principal,
1930                                     &creds->server))) {
1931         afs_com_err(progname, code, "while copying service principal");
1932         goto cleanup;
1933     }
1934     if ((code = krb5_copy_principal(context, client_principal,
1935                                     &creds->client))) {
1936         afs_com_err(progname, code, "while copying client principal");
1937         goto cleanup;
1938     }
1939     if ((code = krb5_copy_keyblock_contents(context, session_key,
1940                                             &deref_session_key(creds)))) {
1941         afs_com_err(progname, code, "while copying session key");
1942         goto cleanup;
1943     }
1944
1945 #if USING_HEIMDAL
1946     creds->times.authtime = enc_tkt_reply->authtime;
1947     creds->times.starttime = *(enc_tkt_reply->starttime);
1948     creds->times.endtime = enc_tkt_reply->endtime;
1949     creds->times.renew_till = 0; /* *(enc_tkt_reply->renew_till) */
1950     creds->flags.b = enc_tkt_reply->flags;
1951 #else
1952     creds->times = enc_tkt_reply->times;
1953     creds->ticket_flags = enc_tkt_reply->flags;
1954 #endif
1955     if (!deref_enc_tkt_addrs(enc_tkt_reply))
1956         ;
1957     else if ((code = krb5_copy_addresses(context,
1958                                          deref_enc_tkt_addrs(enc_tkt_reply), &creds->addresses))) {
1959         afs_com_err(progname, code, "while copying addresses");
1960         goto cleanup;
1961     }
1962
1963 #if USING_HEIMDAL
1964     {
1965         size_t creds_tkt_len;
1966         ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length,
1967                            ticket_reply, &creds_tkt_len, code);
1968         if(code) {
1969             afs_com_err(progname, code, "while encoding ticket");
1970             goto cleanup;
1971         }
1972     }
1973 #else
1974     if ((code = encode_krb5_ticket(ticket_reply, &temp))) {
1975         afs_com_err(progname, code, "while encoding ticket");
1976         goto cleanup;
1977     }
1978     creds->ticket = *temp;
1979     free(temp);
1980 #endif
1981     /* return creds */
1982     *out_creds = creds;
1983     creds = 0;
1984 cleanup:
1985     if (deref_enc_data(&ticket_reply->enc_part))
1986         free(deref_enc_data(&ticket_reply->enc_part));
1987     krb5_free_keytab_entry_contents(context, entry);
1988     if (client_principal)
1989         krb5_free_principal(context, client_principal);
1990     if (service_principal)
1991         krb5_free_principal(context, service_principal);
1992     if (cc)
1993         krb5_cc_close(context, cc);
1994     if (kt)
1995         krb5_kt_close(context, kt);
1996     if (creds) krb5_free_creds(context, creds);
1997     krb5_free_keyblock_contents(context, session_key);
1998 out:
1999     return code;
2000 #else
2001     return -1;
2002 #endif
2003 }
2004
2005
2006 static krb5_error_code get_credv5(krb5_context context, 
2007                                   char *name, char *inst, char *realm,
2008                                   krb5_creds **creds)
2009 {
2010     krb5_creds increds;
2011     krb5_error_code r;
2012     static krb5_principal client_principal = 0;
2013     
2014     memset((char *)&increds, 0, sizeof(increds));
2015 /* ANL - instance may be ptr to a null string. Pass null then */
2016     if ((r = krb5_build_principal(context, &increds.server,
2017                                   strlen(realm), realm,
2018                                   name,
2019                                   (inst && strlen(inst)) ? inst : (void *) NULL,
2020                                   (void *) NULL))) {
2021         return r;
2022     }
2023     
2024
2025     if (!_krb425_ccache) {
2026         r = krb5_cc_default(context, &_krb425_ccache);
2027         if (r)
2028             return r;
2029     }
2030     if (!client_principal) {
2031         if (client) {
2032             r = krb5_parse_name(context, client,  &client_principal);
2033         } else {
2034             r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
2035         }
2036         if (r)
2037             return r;
2038     }
2039     
2040     increds.client = client_principal;
2041     increds.times.endtime = 0;
2042     /* Ask for DES since that is what V4 understands */
2043     get_creds_enctype((&increds)) = ENCTYPE_DES_CBC_CRC;
2044     
2045     if (keytab) {
2046         int allowed_enctypes[] = {
2047             ENCTYPE_DES_CBC_CRC, 0
2048         };
2049
2050         r = get_credv5_akimpersonate(context,
2051                                      keytab,
2052                                      increds.server,
2053                                      increds.client,
2054                                      300, ((~0U)>>1),
2055                                      allowed_enctypes,
2056                                      0 /* paddress */,
2057                                      creds /* out */);
2058     } else {
2059         r = krb5_get_credentials(context, 0, _krb425_ccache, &increds, creds);
2060     }    
2061     return r;
2062 }
2063
2064
2065 static int get_user_realm(krb5_context context, char *realm)
2066 {
2067     static krb5_principal client_principal = 0;
2068     int i;
2069     krb5_error_code r = 0;
2070
2071     if (!_krb425_ccache)
2072         krb5_cc_default(context, &_krb425_ccache);
2073     if (!client_principal) {
2074         if (client) {
2075             r = krb5_parse_name(context, client,  &client_principal);
2076         } else {
2077             r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
2078         }
2079         if (r)
2080             return r;
2081     }
2082
2083     i = realm_len(context, client_principal);
2084     if (i > REALM_SZ-1) i = REALM_SZ-1;
2085     strncpy(realm,realm_data(context, client_principal), i);
2086     realm[i] = 0;
2087
2088     return(r);
2089 }