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