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