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