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