DEVEL15-aklog-stds-krb5-order-20060802
[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 #if !defined(lint) && !defined(SABER)
9 static char *rcsid =
10         "$Id$";
11 #endif /* lint || SABER */
12
13 #include <afsconfig.h>
14 #include <stdio.h>
15 #include <string.h>
16 #include <ctype.h>
17 #include <sys/types.h>
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #ifdef HAVE_STDLIB_H
22 #include <stdlib.h>
23 #endif
24 #ifdef HAVE_MEMORY_H
25 #include <memory.h>
26 #endif
27 #include <errno.h>
28
29 #include <sys/stat.h>
30 #include <fcntl.h>
31
32 #ifndef WINDOWS
33 #include <sys/param.h>
34 #include <sys/errno.h>
35 #include <netdb.h>
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39 #include <pwd.h>
40 #endif /* WINDOWS */
41
42 /* on AIX AFS has an unresolved reference to osi_audit. We will define
43  * it here as extern. It also trys to call the ntohl and htonl routines
44  * as routines rather then macros. We need a real routine here. 
45  * We do this before the ntohl and htonl macros are defined in net/in.h
46  */
47 int osi_audit()
48     { return(0);}
49
50 #if 0
51 #ifdef _AIX
52 u_long htonl(u_long x)
53     { return(x);}
54
55 u_long ntohl(u_long x)
56     { return(x);}
57 #endif
58
59 #include <netinet/in.h>
60 /* #include <krb.h> */
61 #endif /* 0 */
62
63 #include <afs/stds.h>
64 #include <krb5.h>
65
66 #ifdef WINDOWS
67
68 #include <afs/auth.h>
69 #include <rx/rxkad.h>
70 #include <afs/dirpath.h>
71
72 #else /* !WINDOWS */
73 #ifndef HAVE_KERBEROSV_HEIM_ERR_H
74 #include <afs/com_err.h>
75 #endif
76
77 #include <afs/param.h>
78 #ifdef AFS_SUN5_ENV
79 #include <sys/ioccom.h>
80 #endif
81 #include <afs/auth.h>
82 #include <afs/cellconfig.h>
83 #include <afs/vice.h>
84 #include <afs/venus.h>
85 #include <afs/ptserver.h>
86 #include <afs/ptuser.h>
87 #include <afs/dirpath.h>
88 #endif /* WINDOWS */
89
90 #include "aklog.h"
91 #include "linked_list.h"
92
93 #define AFSKEY "afs"
94 #define AFSINST ""
95
96 #ifndef AFS_TRY_FULL_PRINC
97 #define AFS_TRY_FULL_PRINC 1
98 #endif /* AFS_TRY_FULL_PRINC */
99
100 #define AKLOG_SUCCESS 0
101 #define AKLOG_USAGE 1
102 #define AKLOG_SOMETHINGSWRONG 2
103 #define AKLOG_AFS 3
104 #define AKLOG_KERBEROS 4
105 #define AKLOG_TOKEN 5
106 #define AKLOG_BADPATH 6
107 #define AKLOG_MISC 7
108
109 #ifndef NULL
110 #define NULL 0
111 #endif
112
113 #ifndef TRUE
114 #define TRUE 1
115 #endif
116
117 #ifndef FALSE
118 #define FALSE 0
119 #endif
120
121 #ifndef MAXSYMLINKS
122 /* RedHat 4.x doesn't seem to define this */
123 #define MAXSYMLINKS     5
124 #endif
125
126 #define DIR '/'                 /* Character that divides directories */
127 #define DIRSTRING "/"           /* String form of above */
128 #define VOLMARKER ':'           /* Character separating cellname from mntpt */
129 #define VOLMARKERSTRING ":"     /* String form of above */
130
131 typedef struct {
132     char cell[BUFSIZ];
133     char realm[REALM_SZ];
134 } cellinfo_t;
135
136 struct afsconf_cell ak_cellconfig; /* General information about the cell */
137 static char linkedcell[MAXCELLCHARS+1];
138 static char linkedcell2[MAXCELLCHARS+1];
139 static krb5_ccache  _krb425_ccache = NULL;
140
141 #ifdef WINDOWS
142
143 /* libafsconf.dll */
144 extern long cm_GetRootCellName();
145 extern long cm_SearchCellFile();
146
147 static long cm_SearchCellFile_CallBack();
148
149 #else /* !WINDOWS */
150
151 /*
152  * Why doesn't AFS provide these prototypes?
153  */
154
155 extern int pioctl(char *, afs_int32, struct ViceIoctl *, afs_int32);
156
157 /*
158  * Other prototypes
159  */
160
161 extern char *afs_realm_of_cell(krb5_context, struct afsconf_cell *);
162 static int isdir(char *, unsigned char *);
163 static krb5_error_code get_credv5(krb5_context context, char *, char *,
164                                   char *, krb5_creds **);
165 static int get_user_realm(krb5_context, char *);
166
167 #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_CREDS_KEYBLOCK)
188
189 #define get_cred_keydata(c) c->keyblock.contents
190 #define get_cred_keylen(c) c->keyblock.length
191 #define get_creds_enctype(c) c->keyblock.enctype
192
193 #elif defined(HAVE_KRB5_CREDS_SESSION)
194
195 #define get_cred_keydata(c) c->session.keyvalue.data
196 #define get_cred_keylen(c) c->session.keyvalue.length
197 #define get_creds_enctype(c) c->session.keytype
198
199 #else
200 #error "Must have either keyblock or session member of krb5_creds"
201 #endif
202
203 #if !defined(HAVE_KRB5_524_CONVERT_CREDS) && defined(HAVE_KRB524_CONVERT_CREDS_KDC)
204 #define krb5_524_convert_creds krb524_convert_creds_kdc
205 #elif !defined(HAVE_KRB5_524_CONVERT_CREDS) && !defined(HAVE_KRB524_CONVERT_CREDS_KDC)
206 #error "You must have one of krb5_524_convert_creds or krb524_convert_creds_kdc available"
207 #endif
208
209 #endif /* WINDOWS */
210
211 /*
212  * Provide a replacement for strerror if we don't have it
213  */
214
215 #ifndef HAVE_STRERROR
216 extern char *sys_errlist[];
217 #define strerror(x) sys_errlist[x]
218 #endif /* HAVE_STRERROR */
219
220 static char *progname = NULL;   /* Name of this program */
221 static int dflag = FALSE;       /* Give debugging information */
222 static int noauth = FALSE;      /* If true, don't try to get tokens */
223 static int zsubs = FALSE;       /* Are we keeping track of zephyr subs? */
224 static int hosts = FALSE;       /* Are we keeping track of hosts? */
225 static int noprdb = FALSE;      /* Skip resolving name to id? */
226 static int linked = FALSE;  /* try for both AFS nodes */
227 static int afssetpag = FALSE; /* setpag for AFS */
228 static int force = FALSE;       /* Bash identical tokens? */
229 static int do524 = FALSE;       /* Should we do 524 instead of rxkad2b? */
230 static linked_list zsublist;    /* List of zephyr subscriptions */
231 static linked_list hostlist;    /* List of host addresses */
232 static linked_list authedcells; /* List of cells already logged to */
233
234 /* ANL - CMU lifetime convert routine */
235 /* for K5.4.1 don't use this for now. Need to see if it is needed */
236 /* maybe needed in the krb524d module as well */
237 /* extern unsigned long krb_life_to_time(); */
238
239 static char *copy_cellinfo(cellinfo_t *cellinfo)
240 {
241     cellinfo_t *new_cellinfo;
242
243     if ((new_cellinfo = (cellinfo_t *)malloc(sizeof(cellinfo_t))))
244         memcpy(new_cellinfo, cellinfo, sizeof(cellinfo_t));
245     
246     return ((char *)new_cellinfo);
247 }
248
249
250 static char *copy_string(char *string)    
251 {
252     char *new_string;
253
254     if ((new_string = (char *)calloc(strlen(string) + 1, sizeof(char))))
255         (void) strcpy(new_string, string);
256
257     return (new_string);
258 }
259
260
261 static int get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char *local_cell, char *linkedcell)
262 {
263     int status = AKLOG_SUCCESS;
264     struct afsconf_dir *configdir;
265
266     memset(local_cell, 0, sizeof(local_cell));
267     memset((char *)cellconfig, 0, sizeof(*cellconfig));
268
269 #ifndef WINDOWS
270
271     if (!(configdir = afsconf_Open(AFSDIR_CLIENT_ETC_DIRPATH))) {
272         fprintf(stderr, 
273                 "%s: can't get afs configuration (afsconf_Open(%s))\n",
274                 progname, AFSDIR_CLIENT_ETC_DIRPATH);
275         exit(AKLOG_AFS);
276     }
277
278     if (afsconf_GetLocalCell(configdir, local_cell, MAXCELLCHARS)) {
279         fprintf(stderr, "%s: can't determine local cell.\n", progname);
280         exit(AKLOG_AFS);
281     }
282
283     if ((cell == NULL) || (cell[0] == 0))
284         cell = local_cell;
285
286         linkedcell[0] = '\0';
287     if (afsconf_GetCellInfo(configdir, cell, NULL, cellconfig)) {
288         fprintf(stderr, "%s: Can't get information about cell %s.\n",
289                 progname, cell);
290         status = AKLOG_AFS;
291     }
292         if (cellconfig->linkedCell) 
293                 strncpy(linkedcell,cellconfig->linkedCell,MAXCELLCHARS);
294
295     (void) afsconf_Close(configdir);
296
297 #else /* WINDOWS */
298     /*
299      * We'll try to mimic the GetCellInfo call here and fill in as much
300      * of the afsconf_cell structure as we can.
301      */
302     if (cm_GetRootCellName(local_cell)) {
303         fprintf(stderr, "%s: can't get local cellname\n", progname);
304         exit(AKLOG_AFS);
305     }
306
307     if ((cell == NULL) || (cell[0] == 0))
308         cell = local_cell;
309
310     strcpy(cellconfig->name, cell);
311
312     /* No way of figuring this out as far as I can tell */
313     linkedcell[0] = '\0';
314
315     /* Initialize server info */
316     cellconfig->numServers = 0;
317     cellconfig->hostName[0][0] = "\0";
318
319     /*
320      * Get servers of cell. cm_SearchCellFile_CallBack() gets call with
321      * each server.
322      */
323     status = (int) cm_SearchCellFile(cell, NULL, &cm_SearchCellFile_CallBack,
324                                      cellconfig /* rock */);
325
326     switch(status) {
327     case 0:
328         break;
329
330     case -1:
331         fprintf(stderr, "%s: GetWindowsDirectory() failed.\n", progname);
332         break;
333
334     case -2:
335         fprintf(stderr, "%s: Couldn't open afsdcells.ini for reading\n",
336                 progname);
337         break;
338
339     case -3:
340         fprintf(stderr, "%s: Couldn't find any servers for cell %s\n",
341                 progname, cell);
342         break;
343
344     case -4:
345         fprintf(stderr, "%s: Badly formatted line in afsdcells.ini (does not begin with a \">\" or contain \"#\"\n",
346                 progname);
347         break;
348
349     default:
350         fprintf(stderr, "%s cm_SearchCellFile returned unknown error %d\n",
351                 status);
352     }
353
354     if (status) {
355         exit(AKLOG_AFS);
356     }
357
358     status = AKLOG_SUCCESS;
359
360     
361 #endif /* WINDOWS */
362
363     return(status);
364 }
365
366
367 #ifdef WINDOWS
368 /*
369  * Callback function for cm_SearchCellFile() in get_cellconfig() above.
370  * This function gets called once for each server that is found for the cell.
371  */
372 static long
373 cm_SearchCellFile_CallBack(void *rock /* cellconfig */,
374                            struct sockaddr_in *addr, /* Not used */
375                            char *server)
376 {
377     struct afsconf_cell *cellconfig = rock;
378
379
380     /*
381      * Save server name and increment count of servers
382      */
383     strcpy(cellconfig->hostName[cellconfig->numServers++], server);
384     
385     return (long) 0;
386 }
387
388     
389 #endif /* WINDOWS */
390
391
392 /* 
393  * Log to a cell.  If the cell has already been logged to, return without
394  * doing anything.  Otherwise, log to it and mark that it has been logged
395  * to.
396  */
397 static int auth_to_cell(krb5_context context, char *cell, char *realm)
398 {
399     int status = AKLOG_SUCCESS;
400     char username[BUFSIZ];      /* To hold client username structure */
401     afs_int32 viceId;           /* AFS uid of user */
402
403     char name[ANAME_SZ];        /* Name of afs key */
404     char primary_instance[INST_SZ];     /* Instance of afs key */
405     char secondary_instance[INST_SZ];   /* Backup instance to try */
406     int try_secondary = 0;              /* Flag to indicate if we try second */
407     char realm_of_user[REALM_SZ]; /* Kerberos realm of user */
408     char realm_of_cell[REALM_SZ]; /* Kerberos realm of cell */
409     char local_cell[MAXCELLCHARS+1];
410     char cell_to_use[MAXCELLCHARS+1]; /* Cell to authenticate to */
411     static char lastcell[MAXCELLCHARS+1] = { 0 };
412 #ifndef WINDOWS
413     static char confname[512] = { 0 };
414 #endif
415     krb5_creds *v5cred = NULL;
416     struct ktc_principal aserver;
417     struct ktc_principal aclient;
418     struct ktc_token atoken, btoken;
419
420 #ifdef ALLOW_REGISTER
421     afs_int32 id;
422 #endif /* ALLOW_REGISTER */
423
424     memset(name, 0, sizeof(name));
425     memset(primary_instance, 0, sizeof(primary_instance));
426     memset(secondary_instance, 0, sizeof(secondary_instance));
427     memset(realm_of_user, 0, sizeof(realm_of_user));
428     memset(realm_of_cell, 0, sizeof(realm_of_cell));
429
430 #ifndef WINDOWS
431     if (confname[0] == '\0') {
432         strncpy(confname, AFSDIR_CLIENT_ETC_DIRPATH, sizeof(confname));
433         confname[sizeof(confname) - 2] = '\0';
434     }
435 #endif /* WINDOWS */
436
437     /* NULL or empty cell returns information on local cell */
438     if ((status = get_cellconfig(cell, &ak_cellconfig,
439                          local_cell, linkedcell)))
440         return(status);
441
442     strncpy(cell_to_use, ak_cellconfig.name, MAXCELLCHARS);
443     cell_to_use[MAXCELLCHARS] = 0;
444
445     if (ll_string(&authedcells, ll_s_check, cell_to_use)) {
446         if (dflag) {
447             printf("Already authenticated to %s (or tried to)\n", 
448                    cell_to_use);
449         }
450         return(AKLOG_SUCCESS);
451     }
452
453     /* 
454      * Record that we have attempted to log to this cell.  We do this
455      * before we try rather than after so that we will not try
456      * and fail repeatedly for one cell.
457      */
458     (void)ll_string(&authedcells, ll_s_add, cell_to_use);
459
460     /* 
461      * Record this cell in the list of zephyr subscriptions.  We may
462      * want zephyr subscriptions even if authentication fails.
463      * If this is done after we attempt to get tokens, aklog -zsubs
464      * can return something different depending on whether or not we
465      * are in -noauth mode.
466      */
467     if (ll_string(&zsublist, ll_s_add, cell_to_use) == LL_FAILURE) {
468         fprintf(stderr, 
469                 "%s: failure adding cell %s to zephyr subscriptions list.\n",
470                 progname, cell_to_use);
471         exit(AKLOG_MISC);
472     }
473     if (ll_string(&zsublist, ll_s_add, local_cell) == LL_FAILURE) {
474         fprintf(stderr, 
475                 "%s: failure adding cell %s to zephyr subscriptions list.\n",
476                 progname, local_cell);
477         exit(AKLOG_MISC);
478     }
479
480     if (!noauth) {
481         if (dflag) {
482             printf("Authenticating to cell %s (server %s).\n",
483                    cell_to_use, ak_cellconfig.hostName[0]);
484         }
485
486         /*
487          * Find out which realm we're supposed to authenticate to.  If one
488          * is not included, use the kerberos realm found in the credentials
489          * cache.
490          */
491
492         if (realm && realm[0]) {
493             strcpy(realm_of_cell, realm);
494             if (dflag) {
495                 printf("We were told to authenticate to realm %s.\n", realm);
496             }
497         }
498         else {
499             char *realm = afs_realm_of_cell(context, &ak_cellconfig);
500
501             if (!realm) {
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             strcpy(realm_of_cell, realm);
509
510             if (dflag) {
511                 printf("We've deduced that we need to authenticate to"
512                        " realm %s.\n", realm_of_cell);
513             }
514         }
515
516         /* We use the afs.<cellname> convention here... 
517          *
518          * Doug Engert's original code had principals of the form:
519          *
520          * "afsx/cell@realm"
521          *
522          * in the KDC, so the name wouldn't conflict with DFS.  Since we're
523          * not using DFS, I changed it just to look for the following
524          * principals:
525          *
526          * afs/<cell>@<realm>
527          * afs@<realm>
528          *
529          * Because people are transitioning from afs@realm to afs/cell,
530          * we configure things so that if the first one isn't found, we
531          * try the second one.  You can select which one you prefer with
532          * a configure option.
533          */
534
535         strcpy(name, AFSKEY);
536
537         if (AFS_TRY_FULL_PRINC || strcasecmp(cell_to_use, realm_of_cell) != 0) {
538             strncpy(primary_instance, cell_to_use, sizeof(primary_instance));
539             primary_instance[sizeof(primary_instance)-1] = '\0';
540             if (strcasecmp(cell_to_use, realm_of_cell) == 0) {
541                 try_secondary = 1;
542                 secondary_instance[0] = '\0';
543             }
544         } else {
545             primary_instance[0] = '\0';
546             try_secondary = 1;
547             strncpy(secondary_instance, cell_to_use,
548                     sizeof(secondary_instance));
549             secondary_instance[sizeof(secondary_instance)-1] = '\0';
550         }
551
552         /* 
553          * Extract the session key from the ticket file and hand-frob an
554          * afs style authenticator.
555          */
556
557         /*
558          * Try to obtain AFS tickets.  Because there are two valid service
559          * names, we will try both, but trying the more specific first.
560          *
561          *      afs/<cell>@<realm> i.e. allow for single name with "."
562          *      afs@<realm>
563          */
564
565         if (dflag) {
566             printf("Getting tickets: %s/%s@%s\n", name,
567                    primary_instance, realm_of_cell);
568         }
569
570         status = get_credv5(context, name, primary_instance, realm_of_cell,
571                             &v5cred);
572
573         if (status == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN) {
574             if (try_secondary) {
575                 if (dflag) {
576                     printf("Principal not found, trying alternate "
577                            "service name: %s/%s@%s\n", name,
578                             secondary_instance, realm_of_cell);
579                 }
580                 status = get_credv5(context, name, secondary_instance,
581                                     realm_of_cell, &v5cred);
582             }
583         }
584
585         if (status) {
586             if (dflag) {
587                 printf("Kerberos error code returned by get_cred: %d\n",
588                         status);
589             }
590             fprintf(stderr, "%s: Couldn't get %s AFS tickets:\n",
591                     progname, cell_to_use);
592                 com_err(progname, status, "while getting AFS tickets");
593             return(AKLOG_KERBEROS);
594         }
595
596         strncpy(aserver.name, AFSKEY, MAXKTCNAMELEN - 1);
597         strncpy(aserver.instance, AFSINST, MAXKTCNAMELEN - 1);
598         strncpy(aserver.cell, cell_to_use, MAXKTCREALMLEN - 1);
599
600         /*
601          * The default is to use rxkad2b, which means we put in a full
602          * V5 ticket.  If the user specifies -524, we talk to the
603          * 524 ticket converter.
604          */
605
606         if (! do524) {
607             char *p;
608             int len;
609
610             if (dflag)
611                 printf("Using Kerberos V5 ticket natively\n");
612
613             len = min(get_princ_len(context, v5cred->client, 0),
614                       second_comp(context, v5cred->client) ?
615                                         MAXKTCNAMELEN - 2 : MAXKTCNAMELEN - 1);
616             strncpy(username, get_princ_str(context, v5cred->client, 0), len);
617             username[len] = '\0';
618
619             if (second_comp(context, v5cred->client)) {
620                 strcat(username, ".");
621                 p = username + strlen(username);
622                 len = min(get_princ_len(context, v5cred->client, 1),
623                           MAXKTCNAMELEN - strlen(username) - 1);
624                 strncpy(p, get_princ_str(context, v5cred->client, 1), len);
625                 p[len] = '\0';
626             }
627
628             memset(&atoken, 0, sizeof(atoken));
629             atoken.kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
630             atoken.startTime = v5cred->times.starttime;;
631             atoken.endTime = v5cred->times.endtime;
632             memcpy(&atoken.sessionKey, get_cred_keydata(v5cred),
633                    get_cred_keylen(v5cred));
634             atoken.ticketLen = v5cred->ticket.length;
635             memcpy(atoken.ticket, v5cred->ticket.data, atoken.ticketLen);
636         } else {
637             CREDENTIALS cred;
638
639             if (dflag)
640                 printf("Using Kerberos 524 translator service\n");
641
642             status = krb5_524_convert_creds(context, v5cred, &cred);
643
644             if (status) {
645                 com_err(progname, status, "while converting tickets "
646                         "to Kerberos V4 format");
647                 return(AKLOG_KERBEROS);
648             }
649
650             strcpy (username, cred.pname);
651             if (cred.pinst[0]) {
652                 strcat (username, ".");
653                 strcat (username, cred.pinst);
654             }
655
656             atoken.kvno = cred.kvno;
657             atoken.startTime = cred.issue_date;
658             /*
659              * It seems silly to go through a bunch of contortions to
660              * extract the expiration time, when the v5 credentials already
661              * has the exact time!  Let's use that instead.
662              *
663              * Note that this isn't a security hole, as the expiration time
664              * is also contained in the encrypted token
665              */
666             atoken.endTime = v5cred->times.endtime;
667             memcpy(&atoken.sessionKey, cred.session, 8);
668             atoken.ticketLen = cred.ticket_st.length;
669             memcpy(atoken.ticket, cred.ticket_st.dat, atoken.ticketLen);
670         }
671         
672         if (!force &&
673             !ktc_GetToken(&aserver, &btoken, sizeof(btoken), &aclient) &&
674             atoken.kvno == btoken.kvno &&
675             atoken.ticketLen == btoken.ticketLen &&
676             !memcmp(&atoken.sessionKey, &btoken.sessionKey, sizeof(atoken.sessionKey)) &&
677             !memcmp(atoken.ticket, btoken.ticket, atoken.ticketLen)) {
678
679             if (dflag) {
680                 printf("Identical tokens already exist; skipping.\n");
681             }
682             return 0;
683         }
684
685 #ifdef FORCE_NOPRDB
686         noprdb = 1;
687 #endif
688
689 #ifndef WINDOWS
690         if (noprdb) {
691 #endif
692             if (dflag) {
693                 printf("Not resolving name %s to id (-noprdb set)\n",
694                         username);
695             }
696 #ifndef WINDOWS
697         }
698         else {
699             if ((status = get_user_realm(context, realm_of_user))) {
700                 fprintf(stderr, "%s: Couldn't determine realm of user:)",
701                         progname);
702                 com_err(progname, status, " while getting realm");
703                 return(AKLOG_KERBEROS);
704             }
705             if (strcmp(realm_of_user, realm_of_cell)) {
706                 strcat(username, "@");
707                 strcat(username, realm_of_user);
708             }
709
710             if (dflag) {
711                 printf("About to resolve name %s to id in cell %s.\n", 
712                         username, aserver.cell);
713             }
714
715             strcpy(lastcell, aserver.cell);
716
717             if (!pr_Initialize (0, confname, aserver.cell))
718                     status = pr_SNameToId (username, &viceId);
719             
720             if (dflag) {
721                 if (status) 
722                     printf("Error %d\n", status);
723                 else
724                     printf("Id %d\n", (int) viceId);
725             }
726             
727                 /*
728                  * This is a crock, but it is Transarc's crock, so
729                  * we have to play along in order to get the
730                  * functionality.  The way the afs id is stored is
731                  * as a string in the username field of the token.
732                  * Contrary to what you may think by looking at
733                  * the code for tokens, this hack (AFS ID %d) will
734                  * not work if you change %d to something else.
735                  */
736
737                 /*
738                  * This code is taken from cklog -- it lets people
739                  * automatically register with the ptserver in foreign cells
740                  */
741
742 #ifdef ALLOW_REGISTER
743         if (status == 0) {
744             if (viceId != ANONYMOUSID) {
745 #else /* ALLOW_REGISTER */
746             if ((status == 0) && (viceId != ANONYMOUSID))
747 #endif /* ALLOW_REGISTER */
748                 sprintf (username, "AFS ID %d", (int) viceId);
749 #ifdef ALLOW_REGISTER
750             } else if (strcmp(realm_of_user, realm_of_cell) != 0) {
751                 if (dflag) {
752                     printf("doing first-time registration of %s "
753                             "at %s\n", username, cell_to_use);
754                 }
755                 id = 0;
756                 strncpy(aclient.name, username, MAXKTCNAMELEN - 1);
757                 strcpy(aclient.instance, "");
758                 strncpy(aclient.cell, realm_of_user, MAXKTCREALMLEN - 1);
759                 if ((status = ktc_SetToken(&aserver, &atoken, &aclient, 0))) {
760                     fprintf(stderr, "%s: unable to obtain tokens for cell %s "
761                             "(status: %d).\n", progname, cell_to_use, status);
762                     status = AKLOG_TOKEN;
763                 }
764
765                 /*
766                  * In case you're wondering, we don't need to change the
767                  * filename here because we're still connecting to the
768                  * same cell -- we're just using a different authentication
769                  * level
770                  */
771
772                 if ((status = pr_Initialize(1L, confname, aserver.cell))) {
773                     printf("Error %d\n", status);
774                 }
775
776                 if ((status = pr_CreateUser(username, &id))) {
777                     fprintf(stderr, "%s: %s so unable to create remote PTS "
778                             "user %s in cell %s (status: %d).\n", progname,
779                             error_message(status), username, cell_to_use,
780                             status);
781                 } else {
782                     printf("created cross-cell entry for %s at %s\n",
783                            username, cell_to_use);
784                     sprintf(username, "AFS ID %d", (int) id);
785                 }
786             }
787         }
788 #endif /* ALLOW_REGISTER */
789
790         }
791 #endif /* !WINDOWS */
792
793         if (dflag) {
794             fprintf(stdout, "Set username to %s\n", username);
795         }
796
797         /* Reset the "aclient" structure before we call ktc_SetToken.
798          * This structure was first set by the ktc_GetToken call when
799          * we were comparing whether identical tokens already existed.
800          */
801         strncpy(aclient.name, username, MAXKTCNAMELEN - 1);
802         strcpy(aclient.instance, "");
803         strncpy(aclient.cell, realm_of_user, MAXKTCREALMLEN - 1);
804
805         if (dflag) {
806             printf("Setting tokens. %s / %s @ %s \n",
807                     aclient.name, aclient.instance, aclient.cell );
808         }
809         /* on AIX 4.1.4 with AFS 3.4a+ if a write is not done before 
810          * this routine, it will not add the token. It is not clear what 
811          * is going on here! So we will do the following operation
812          */
813         write(2,"",0); /* dummy write */
814 #ifndef WINDOWS
815         if ((status = ktc_SetToken(&aserver, &atoken, &aclient, afssetpag))) {
816             fprintf(stderr, 
817                     "%s: unable to obtain tokens for cell %s (status: %d).\n",
818                     progname, cell_to_use, status);
819             status = AKLOG_TOKEN;
820         }
821 #else /* WINDOWS */
822         /* Note switched 2nd and 3rd args */
823         if ((status = ktc_SetToken(&aserver, &atoken, &aclient, afssetpag))) {
824             switch(status) {
825             case KTC_INVAL:
826                 fprintf(stderr, "%s: Bad ticket length", progname);
827                 break;
828             case KTC_PIOCTLFAIL:
829                 fprintf(stderr, "%s: Unknown error contacting AFS service",
830                         progname);
831                 break;
832             case KTC_NOCELL:
833                 fprintf(stderr, "%s: Cell name (%s) not recognized by AFS service",
834                         progname, realm_of_cell);
835                 break;
836             case KTC_NOCM:
837                 fprintf(stderr, "%s: AFS service is unavailable", progname);
838                 break;
839             default:
840                 fprintf(stderr, "%s: Undocumented error (%d) contacting AFS service", progname, status);
841                 break;  
842             }
843             status = AKLOG_TOKEN;           
844         }
845 #endif /* !WINDOWS */
846     }
847     else
848         if (dflag) {
849             printf("Noauth mode; not authenticating.\n");
850         }
851         
852     return(status);
853 }
854
855 #ifndef WINDOWS /* struct ViceIoctl missing */
856
857 static int get_afs_mountpoint(char *file, char *mountpoint, int size)
858 {
859 #ifdef AFS_SUN_ENV
860         char V ='V'; /* AFS has problem on Sun with pioctl */
861 #endif
862     char our_file[MAXPATHLEN + 1];
863     char *parent_dir;
864     char *last_component;
865     struct ViceIoctl vio;
866     char cellname[BUFSIZ];
867
868     memset(our_file, 0, sizeof(our_file));
869     strcpy(our_file, file);
870
871     if ((last_component = strrchr(our_file, DIR))) {
872         *last_component++ = 0;
873         parent_dir = our_file;
874     }
875     else {
876         last_component = our_file;
877         parent_dir = ".";
878     }    
879     
880     memset(cellname, 0, sizeof(cellname));
881
882     vio.in = last_component;
883     vio.in_size = strlen(last_component)+1;
884     vio.out_size = size;
885     vio.out = mountpoint;
886
887     if (!pioctl(parent_dir, VIOC_AFS_STAT_MT_PT, &vio, 0)) {
888         if (strchr(mountpoint, VOLMARKER) == NULL) {
889             vio.in = file;
890             vio.in_size = strlen(file) + 1;
891             vio.out_size = sizeof(cellname);
892             vio.out = cellname;
893             
894             if (!pioctl(file, VIOC_FILE_CELL_NAME, &vio, 1)) {
895                 strcat(cellname, VOLMARKERSTRING);
896                 strcat(cellname, mountpoint + 1);
897                 memset(mountpoint + 1, 0, size - 1);
898                 strcpy(mountpoint + 1, cellname);
899             }
900         }
901         return(TRUE);
902     }
903     else
904         return(FALSE);
905 }
906
907 /* 
908  * This routine each time it is called returns the next directory 
909  * down a pathname.  It resolves all symbolic links.  The first time
910  * it is called, it should be called with the name of the path
911  * to be descended.  After that, it should be called with the arguemnt
912  * NULL.
913  */
914 static char *next_path(char *origpath)
915 {
916     static char path[MAXPATHLEN + 1];
917     static char pathtocheck[MAXPATHLEN + 1];
918
919     int link = FALSE;           /* Is this a symbolic link? */
920     char linkbuf[MAXPATHLEN + 1];
921     char tmpbuf[MAXPATHLEN + 1];
922
923     static char *last_comp;     /* last component of directory name */
924     static char *elast_comp;    /* End of last component */
925     char *t;
926     int len;
927     
928     static int symlinkcount = 0; /* We can't exceed MAXSYMLINKS */
929     
930     /* If we are given something for origpath, we are initializing only. */
931     if (origpath) {
932         memset(path, 0, sizeof(path));
933         memset(pathtocheck, 0, sizeof(pathtocheck));
934         strcpy(path, origpath);
935         last_comp = path;
936         symlinkcount = 0;
937         return(NULL);
938     }
939
940     /* We were not given origpath; find then next path to check */
941     
942     /* If we've gotten all the way through already, return NULL */
943     if (last_comp == NULL)
944         return(NULL);
945
946     do {
947         while (*last_comp == DIR)
948             strncat(pathtocheck, last_comp++, 1);
949         len = (elast_comp = strchr(last_comp, DIR)) 
950             ? elast_comp - last_comp : strlen(last_comp);
951         strncat(pathtocheck, last_comp, len);
952         memset(linkbuf, 0, sizeof(linkbuf));
953         if (link = (readlink(pathtocheck, linkbuf, 
954                                     sizeof(linkbuf)) > 0)) {
955             if (++symlinkcount > MAXSYMLINKS) {
956                 fprintf(stderr, "%s: %s\n", progname, strerror(ELOOP));
957                 exit(AKLOG_BADPATH);
958             }
959             memset(tmpbuf, 0, sizeof(tmpbuf));
960             if (elast_comp)
961                 strcpy(tmpbuf, elast_comp);
962             if (linkbuf[0] == DIR) {
963                 /* 
964                  * If this is a symbolic link to an absolute path, 
965                  * replace what we have by the absolute path.
966                  */
967                 memset(path, 0, strlen(path));
968                 memcpy(path, linkbuf, sizeof(linkbuf));
969                 strcat(path, tmpbuf);
970                 last_comp = path;
971                 elast_comp = NULL;
972                 memset(pathtocheck, 0, sizeof(pathtocheck));
973             }
974             else {
975                 /* 
976                  * If this is a symbolic link to a relative path, 
977                  * replace only the last component with the link name.
978                  */
979                 strncpy(last_comp, linkbuf, strlen(linkbuf) + 1);
980                 strcat(path, tmpbuf);
981                 elast_comp = NULL;
982                 if ((t = strrchr(pathtocheck, DIR))) {
983                     t++;
984                     memset(t, 0, strlen(t));
985                 }
986                 else
987                     memset(pathtocheck, 0, sizeof(pathtocheck));
988             }
989         }
990         else
991             last_comp = elast_comp;
992     }
993     while(link);
994
995     return(pathtocheck);
996 }
997
998 #endif /* WINDOWS */
999
1000 #if 0
1001 /*****************************************/
1002 int dee_gettokens()
1003 {
1004 #ifdef AFS_SUN_ENV
1005         char V = 'V'; /* AFS has problem on SunOS */
1006 #endif
1007    struct ViceIoctl vio;
1008    char outbuf[BUFSIZ];
1009    long ind;
1010    int fd;
1011
1012    memset(outbuf, 0, sizeof(outbuf));
1013
1014    vio.out_size = sizeof(outbuf);
1015    vio.in_size = sizeof(ind);
1016    vio.out = outbuf;
1017    vio.in = &ind;
1018
1019    ind = 0;
1020    fd = open("dee.tok",O_WRONLY);
1021    while(!pioctl(0,VIOCGETTOK,&vio,0)) {
1022         write(fd,&outbuf,sizeof(outbuf)); 
1023        ind++;
1024    }
1025    close(fd);
1026 }
1027 /*****************************************/
1028 #endif
1029
1030 #ifndef WINDOWS /* struct ViceIoctl missing */
1031
1032 static void add_hosts(char *file)
1033 {
1034 #ifdef AFS_SUN_ENV
1035         char V = 'V'; /* AFS has problem on SunOS */
1036 #endif
1037     struct ViceIoctl vio;
1038     char outbuf[BUFSIZ];
1039     long *phosts;
1040     int i;
1041     struct hostent *hp;
1042     struct in_addr in;
1043     
1044     memset(outbuf, 0, sizeof(outbuf));
1045
1046     vio.out_size = sizeof(outbuf);
1047     vio.in_size = 0;
1048     vio.out = outbuf;
1049
1050     if (dflag) {
1051         printf("Getting list of hosts for %s\n", file);
1052     }
1053     /* Don't worry about errors. */
1054     if (!pioctl(file, VIOCWHEREIS, &vio, 1)) {
1055         phosts = (long *) outbuf;
1056
1057         /*
1058          * Lists hosts that we care about.  If ALLHOSTS is defined,
1059          * then all hosts that you ever may possible go through are
1060          * included in this list.  If not, then only hosts that are
1061          * the only ones appear.  That is, if a volume you must use
1062          * is replaced on only one server, that server is included.
1063          * If it is replicated on many servers, then none are included.
1064          * This is not perfect, but the result is that people don't
1065          * get subscribed to a lot of instances of FILSRV that they
1066          * probably won't need which reduces the instances of 
1067          * people getting messages that don't apply to them.
1068          */
1069 #ifndef ALLHOSTS
1070         if (phosts[1] != '\0')
1071             return;
1072 #endif
1073         for (i = 0; phosts[i]; i++) {
1074             if (hosts) {
1075                 in.s_addr = phosts[i];
1076                 if (dflag) {
1077                     printf("Got host %s\n", inet_ntoa(in));
1078                 }
1079                 ll_string(&hostlist, ll_s_add, (char *)inet_ntoa(in));
1080             }
1081             if (zsubs && (hp=gethostbyaddr((char *) &phosts[i],sizeof(long),AF_INET))) {
1082                 if (dflag) {
1083                     printf("Got host %s\n", hp->h_name);
1084                 }
1085                 ll_string(&zsublist, ll_s_add, hp->h_name);
1086             }
1087         }
1088     }
1089 }
1090
1091 #endif /* WINDOWS */
1092
1093 #ifndef WINDOWS /* next_path(), get_afs_mountpoint() */
1094
1095 /*
1096  * This routine descends through a path to a directory, logging to 
1097  * every cell it encounters along the way.
1098  */
1099 static int auth_to_path(krb5_context context, char *path)
1100 {
1101     int status = AKLOG_SUCCESS;
1102     int auth_to_cell_status = AKLOG_SUCCESS;
1103
1104     char *nextpath;
1105     char pathtocheck[MAXPATHLEN + 1];
1106     char mountpoint[MAXPATHLEN + 1];
1107
1108     char *cell;
1109     char *endofcell;
1110
1111     u_char isdirectory;
1112
1113     /* Initialize */
1114     if (path[0] == DIR)
1115         strcpy(pathtocheck, path);
1116     else {
1117         if (getcwd(pathtocheck, sizeof(pathtocheck)) == NULL) {
1118             fprintf(stderr, "Unable to find current working directory:\n");
1119             fprintf(stderr, "%s\n", pathtocheck);
1120             fprintf(stderr, "Try an absolute pathname.\n");
1121             exit(AKLOG_BADPATH);
1122         }
1123         else {
1124             strcat(pathtocheck, DIRSTRING);
1125             strcat(pathtocheck, path);
1126         }
1127     }
1128     next_path(pathtocheck);
1129
1130     /* Go on to the next level down the path */
1131     while ((nextpath = next_path(NULL))) {
1132         strcpy(pathtocheck, nextpath);
1133         if (dflag) {
1134             printf("Checking directory %s\n", pathtocheck);
1135         }
1136         /* 
1137          * If this is an afs mountpoint, determine what cell from 
1138          * the mountpoint name which is of the form 
1139          * #cellname:volumename or %cellname:volumename.
1140          */
1141         if (get_afs_mountpoint(pathtocheck, mountpoint, sizeof(mountpoint))) {
1142             /* skip over the '#' or '%' */
1143             cell = mountpoint + 1;
1144             /* Add this (cell:volumename) to the list of zsubs */
1145             if (zsubs)
1146                 ll_string(&zsublist, ll_s_add, cell);
1147             if (zsubs || hosts)
1148                 add_hosts(pathtocheck);
1149             if ((endofcell = strchr(mountpoint, VOLMARKER))) {
1150                 *endofcell = '\0';
1151                 if ((auth_to_cell_status = auth_to_cell(context, cell, NULL))) {
1152                     if (status == AKLOG_SUCCESS)
1153                         status = auth_to_cell_status;
1154                     else if (status != auth_to_cell_status)
1155                         status = AKLOG_SOMETHINGSWRONG;
1156                 }
1157             }
1158         }
1159         else {
1160             if (isdir(pathtocheck, &isdirectory) < 0) {
1161                 /*
1162                  * If we've logged and still can't stat, there's
1163                  * a problem... 
1164                  */
1165                 fprintf(stderr, "%s: stat(%s): %s\n", progname, 
1166                         pathtocheck, strerror(errno));
1167                 return(AKLOG_BADPATH);
1168             }
1169             else if (! isdirectory) {
1170                 /* Allow only directories */
1171                 fprintf(stderr, "%s: %s: %s\n", progname, pathtocheck,
1172                         strerror(ENOTDIR));
1173                 return(AKLOG_BADPATH);
1174             }
1175         }
1176     }
1177     
1178
1179     return(status);
1180 }
1181
1182 #endif /* WINDOWS */
1183
1184
1185 /* Print usage message and exit */
1186 static void usage(void)
1187 {
1188     fprintf(stderr, "\nUsage: %s %s%s%s\n", progname,
1189             "[-d] [[-cell | -c] cell [-k krb_realm]] ",
1190             "[[-p | -path] pathname]\n",
1191             "    [-zsubs] [-hosts] [-noauth] [-noprdb] [-force] [-setpag] \n"
1192             "    [-linked] [-524]\n");
1193     fprintf(stderr, "    -d gives debugging information.\n");
1194     fprintf(stderr, "    krb_realm is the kerberos realm of a cell.\n");
1195     fprintf(stderr, "    pathname is the name of a directory to which ");
1196     fprintf(stderr, "you wish to authenticate.\n");
1197     fprintf(stderr, "    -zsubs gives zephyr subscription information.\n");
1198     fprintf(stderr, "    -hosts gives host address information.\n");
1199     fprintf(stderr, "    -noauth does not attempt to get tokens.\n");
1200     fprintf(stderr, "    -noprdb means don't try to determine AFS ID.\n");
1201     fprintf(stderr, "    -force means replace identical tickets. \n");
1202     fprintf(stderr, "    -linked means if AFS node is linked, try both. \n");
1203     fprintf(stderr, "    -setpag set the AFS process authentication group.\n");
1204     fprintf(stderr, "    -524 means use the 524 converter instead of V5 directly\n");
1205     fprintf(stderr, "    No commandline arguments means ");
1206     fprintf(stderr, "authenticate to the local cell.\n");
1207     fprintf(stderr, "\n");
1208     exit(AKLOG_USAGE);
1209 }
1210
1211 void aklog(int argc, char *argv[])
1212 {
1213         krb5_context context;
1214     int status = AKLOG_SUCCESS;
1215     int i;
1216     int somethingswrong = FALSE;
1217
1218     cellinfo_t cellinfo;
1219
1220     extern char *progname;      /* Name of this program */
1221
1222     extern int dflag;           /* Debug mode */
1223
1224     int cmode = FALSE;          /* Cellname mode */
1225     int pmode = FALSE;          /* Path name mode */
1226
1227     char realm[REALM_SZ];       /* Kerberos realm of afs server */
1228     char cell[BUFSIZ];          /* Cell to which we are authenticating */
1229     char path[MAXPATHLEN + 1];          /* Path length for path mode */
1230
1231     linked_list cells;          /* List of cells to log to */
1232     linked_list paths;          /* List of paths to log to */
1233     ll_node *cur_node;
1234
1235     memset(&cellinfo, 0, sizeof(cellinfo));
1236
1237     memset(realm, 0, sizeof(realm));
1238     memset(cell, 0, sizeof(cell));
1239     memset(path, 0, sizeof(path));
1240
1241     ll_init(&cells);
1242     ll_init(&paths);
1243
1244     ll_init(&zsublist);
1245     ll_init(&hostlist);
1246
1247     /* Store the program name here for error messages */
1248     if ((progname = strrchr(argv[0], DIR)))
1249         progname++;
1250     else
1251         progname = argv[0];
1252
1253     krb5_init_context(&context);
1254 #ifndef WINDOWS
1255         initialize_ktc_error_table ();
1256 #endif
1257
1258     /* Initialize list of cells to which we have authenticated */
1259     (void)ll_init(&authedcells);
1260
1261     /* Parse commandline arguments and make list of what to do. */
1262     for (i = 1; i < argc; i++) {
1263         if (strcmp(argv[i], "-d") == 0)
1264             dflag++;
1265         else if (strcmp(argv[i], "-noauth") == 0) 
1266             noauth++;
1267         else if (strcmp(argv[i], "-zsubs") == 0)
1268             zsubs++;
1269         else if (strcmp(argv[i], "-hosts") == 0)
1270             hosts++;
1271         else if (strcmp(argv[i], "-noprdb") == 0)
1272             noprdb++;
1273         else if (strcmp(argv[i], "-linked") == 0)
1274                 linked++;
1275         else if (strcmp(argv[i], "-force") == 0)
1276             force++;
1277         else if (strcmp(argv[i], "-524") == 0)
1278             do524++;
1279     else if (strcmp(argv[i], "-setpag") == 0)
1280             afssetpag++;
1281         else if (((strcmp(argv[i], "-cell") == 0) ||
1282                   (strcmp(argv[i], "-c") == 0)) && !pmode)
1283             if (++i < argc) {
1284                 cmode++;
1285                 strcpy(cell, argv[i]);
1286             }
1287             else
1288                 usage();
1289         else if (((strcmp(argv[i], "-path") == 0) ||
1290                   (strcmp(argv[i], "-p") == 0)) && !cmode)
1291 #ifndef WINDOWS
1292             if (++i < argc) {
1293                 pmode++;
1294                 strcpy(path, argv[i]);
1295             }
1296             else
1297                 usage();
1298 #else /* WINDOWS */
1299         {
1300             fprintf(stderr, "%s: path mode not supported.\n", progname);
1301             exit(AKLOG_MISC);
1302         }
1303 #endif /* WINDOWS */
1304             
1305         else if (argv[i][0] == '-')
1306             usage();
1307         else if (!pmode && !cmode) {
1308             if (strchr(argv[i], DIR) || (strcmp(argv[i], ".") == 0) ||
1309                 (strcmp(argv[i], "..") == 0)) {
1310 #ifndef WINDOWS
1311                 pmode++;
1312                 strcpy(path, argv[i]);
1313 #else /* WINDOWS */
1314                 fprintf(stderr, "%s: path mode not supported.\n", progname);
1315                 exit(AKLOG_MISC);
1316 #endif /* WINDOWS */
1317             }
1318             else { 
1319                 cmode++;
1320                 strcpy(cell, argv[i]);
1321             }
1322         }
1323         else
1324             usage();
1325
1326         if (cmode) {
1327             if (((i + 1) < argc) && (strcmp(argv[i + 1], "-k") == 0)) {
1328                 i+=2;
1329                 if (i < argc)
1330                     strcpy(realm, argv[i]);
1331                 else
1332                     usage();
1333             }
1334             /* Add this cell to list of cells */
1335             strcpy(cellinfo.cell, cell);
1336             strcpy(cellinfo.realm, realm);
1337             if ((cur_node = ll_add_node(&cells, ll_tail))) {
1338                 char *new_cellinfo;
1339                 if ((new_cellinfo = copy_cellinfo(&cellinfo)))
1340                     ll_add_data(cur_node, new_cellinfo);
1341                 else {
1342                     fprintf(stderr, 
1343                             "%s: failure copying cellinfo.\n", progname);
1344                     exit(AKLOG_MISC);
1345                 }
1346             }
1347             else {
1348                 fprintf(stderr, "%s: failure adding cell to cells list.\n",
1349                         progname);
1350                 exit(AKLOG_MISC);
1351             }
1352             memset(&cellinfo, 0, sizeof(cellinfo));
1353             cmode = FALSE;
1354             memset(cell, 0, sizeof(cell));
1355             memset(realm, 0, sizeof(realm));
1356         }
1357 #ifndef WINDOWS
1358         else if (pmode) {
1359             /* Add this path to list of paths */
1360             if ((cur_node = ll_add_node(&paths, ll_tail))) {
1361                 char *new_path; 
1362                 if ((new_path = copy_string(path)))
1363                     ll_add_data(cur_node, new_path);
1364                 else {
1365                     fprintf(stderr, "%s: failure copying path name.\n",
1366                             progname);
1367                     exit(AKLOG_MISC);
1368                 }
1369             }
1370             else {
1371                 fprintf(stderr, "%s: failure adding path to paths list.\n",
1372                         progname);
1373                 exit(AKLOG_MISC);
1374             }
1375             pmode = FALSE;
1376             memset(path, 0, sizeof(path));
1377         }
1378 #endif /* WINDOWS */
1379     }
1380
1381     /*
1382      * The code that _used_ to be here called setpag().  When you think
1383      * about this, doing this makes no sense!  setpag() allocates a PAG
1384      * only for the current process, so the token installed would have
1385      * not be usable in the parent!  Since ktc_SetToken() now takes a
1386      * 4th argument to control whether or not we're going to allocate
1387      * a PAG (and since when you do it _that_ way, it modifies the cred
1388      * structure of your parent)), why don't we use that instead?
1389      */
1390
1391 #if 0
1392     if (afssetpag) {
1393            status = setpag();
1394            if (dflag) { 
1395              int i,j;
1396                  int gidsetlen = 50;
1397          int gidset[50];
1398
1399                  printf("setpag %d\n",status);
1400              j = getgroups(gidsetlen,gidset);
1401          printf("Groups(%d):",j);
1402          for (i = 0; i<j; i++) {
1403            printf("%d",gidset[i]);
1404            if((i+1)<j) printf(",");
1405          }
1406          printf("\n");
1407            }
1408         }
1409 #endif
1410     /* If nothing was given, log to the local cell. */
1411     if ((cells.nelements + paths.nelements) == 0) {
1412                 struct passwd *pwd;
1413
1414                 status = auth_to_cell(context, NULL, NULL);
1415         
1416                 /* If this cell is linked to a DCE cell, and user 
1417                  * requested -linked, get tokens for both 
1418                  * This is very usefull when the AFS cell is linked to a DFS 
1419                  * cell and this system does not also have DFS. 
1420                  */
1421
1422                 if (!status && linked && linkedcell[0]) {
1423                                 strncpy(linkedcell2,linkedcell,MAXCELLCHARS);
1424                             if (dflag) {
1425                                 printf("Linked cell: %s\n", linkedcell);
1426                             }
1427                                 status = auth_to_cell(context, linkedcell2, NULL);
1428                 }
1429
1430 #ifndef WINDOWS
1431                 /*
1432                  * Local hack - if the person has a file in their home
1433                  * directory called ".xlog", read that for a list of
1434                  * extra cells to authenticate to
1435                  */
1436
1437                 if ((pwd = getpwuid(getuid())) != NULL) {
1438                     struct stat sbuf;
1439                     FILE *f;
1440                     char fcell[100], xlog_path[512];
1441
1442                     strcpy(xlog_path, pwd->pw_dir);
1443                     strcat(xlog_path, "/.xlog");
1444
1445                     if ((stat(xlog_path, &sbuf) == 0) &&
1446                         ((f = fopen(xlog_path, "r")) != NULL)) {
1447
1448                         if (dflag) {
1449                             printf("Reading %s for cells to "
1450                                     "authenticate to.\n", xlog_path);
1451                         }
1452
1453                         while (fgets(fcell, 100, f) != NULL) {
1454                             int auth_status;
1455
1456                             fcell[strlen(fcell) - 1] = '\0';
1457
1458                             if (dflag) {
1459                                 printf("Found cell %s in %s.\n",
1460                                         fcell, xlog_path);
1461                             }
1462
1463                             auth_status = auth_to_cell(context, fcell, NULL);
1464                             if (status == AKLOG_SUCCESS)
1465                                 status = auth_status;
1466                             else
1467                                 status = AKLOG_SOMETHINGSWRONG;
1468                         }
1469                     }
1470                 }
1471 #endif /* WINDOWS */
1472         }
1473     else {
1474         /* Log to all cells in the cells list first */
1475         for (cur_node = cells.first; cur_node; cur_node = cur_node->next) {
1476             memcpy((char *)&cellinfo, cur_node->data, sizeof(cellinfo));
1477             if ((status = auth_to_cell(context, cellinfo.cell, cellinfo.realm)))
1478                 somethingswrong++;
1479                 else {
1480                         if (linked && linkedcell[0]) {
1481                                 strncpy(linkedcell2,linkedcell,MAXCELLCHARS);
1482                 if (dflag) {
1483                     printf("Linked cell: %s\n",
1484                         linkedcell);
1485                 }
1486                                 if ((status = auth_to_cell(context,linkedcell2,
1487                                                          cellinfo.realm)))
1488                                 somethingswrong++;
1489                         }
1490                 }
1491         }
1492         
1493 #ifndef WINDOWS
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 #endif /* WINDOWS */
1500         
1501         /* 
1502          * If only one thing was logged to, we'll return the status 
1503          * of the single call.  Otherwise, we'll return a generic
1504          * something failed status.
1505          */
1506         if (somethingswrong && ((cells.nelements + paths.nelements) > 1))
1507             status = AKLOG_SOMETHINGSWRONG;
1508     }
1509
1510     /* If we are keeping track of zephyr subscriptions, print them. */
1511     if (zsubs) 
1512         for (cur_node = zsublist.first; cur_node; cur_node = cur_node->next) {
1513             printf("zsub: %s\n", cur_node->data);
1514         }
1515
1516     /* If we are keeping track of host information, print it. */
1517     if (hosts)
1518         for (cur_node = hostlist.first; cur_node; cur_node = cur_node->next) {
1519             printf("host: %s\n", cur_node->data);
1520         }
1521
1522     exit(status);
1523 }
1524
1525 #ifndef HAVE_ADD_TO_ERROR_TABLE
1526
1527 #define error_table error_table_compat
1528 #include <afs/error_table.h>
1529 #undef error_table
1530
1531 #ifndef HAVE_ADD_ERROR_TABLE
1532 void add_error_table (const struct error_table *);
1533 #endif /* !HAVE_ADD_ERROR_TABLE */
1534
1535 void
1536 add_to_error_table(struct et_list *new_table)
1537 {
1538         add_error_table((struct error_table *) new_table->table);
1539 }
1540 #endif /* HAVE_ADD_TO_ERROR_TABLE */
1541
1542 static int isdir(char *path, unsigned char *val)
1543 {
1544     struct stat statbuf;
1545
1546     if (lstat(path, &statbuf) < 0)
1547         return (-1);
1548     else {
1549         if ((statbuf.st_mode & S_IFMT) == S_IFDIR) 
1550             *val = TRUE;
1551         else
1552             *val = FALSE;
1553         return (0);
1554     }  
1555 }
1556
1557 static krb5_error_code get_credv5(krb5_context context, 
1558                         char *name, char *inst, char *realm,
1559                         krb5_creds **creds)
1560 {
1561     krb5_creds increds;
1562     krb5_error_code r;
1563     static krb5_principal client_principal = 0;
1564
1565     memset((char *)&increds, 0, sizeof(increds));
1566 /* ANL - instance may be ptr to a null string. Pass null then */
1567     if ((r = krb5_build_principal(context, &increds.server,
1568                      strlen(realm), realm,
1569                      name,
1570            (inst && strlen(inst)) ? inst : (void *) NULL,
1571                      (void *) NULL))) {
1572         return r;
1573     }
1574
1575     if (!_krb425_ccache) {
1576         r = krb5_cc_default(context, &_krb425_ccache);
1577         if (r)
1578             return r;
1579     }
1580     if (!client_principal) {
1581         r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
1582         if (r)
1583             return r;
1584     }
1585
1586     increds.client = client_principal;
1587     increds.times.endtime = 0;
1588         /* Ask for DES since that is what V4 understands */
1589     get_creds_enctype((&increds)) = ENCTYPE_DES_CBC_CRC;
1590
1591     r = krb5_get_credentials(context, 0, _krb425_ccache, &increds, creds);
1592
1593     return r;
1594 }
1595
1596
1597 static int get_user_realm(krb5_context context, char *realm)
1598 {
1599     static krb5_principal client_principal = 0;
1600     int i;
1601
1602     if (!_krb425_ccache)
1603         krb5_cc_default(context, &_krb425_ccache);
1604     if (!client_principal)
1605         krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
1606
1607     i = realm_len(context, client_principal);
1608     if (i > REALM_SZ-1) i = REALM_SZ-1;
1609     strncpy(realm,realm_data(context, client_principal), i);
1610     realm[i] = 0;
1611
1612     return(0);
1613 }