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