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