rx: Use opr queues
[openafs.git] / src / vol / vol-info.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11    System:              VICE-TWO
12    Module:              vol-info.c
13    Institution: The Information Technology Center, Carnegie-Mellon University
14
15    */
16
17 #include <afsconfig.h>
18 #include <afs/param.h>
19
20 #include <roken.h>
21
22 #include <ctype.h>
23
24 #ifdef HAVE_SYS_FILE_H
25 #include <sys/file.h>
26 #endif
27
28 #include <afs/cmd.h>
29 #include <afs/dir.h>
30 #include <afs/afsint.h>
31 #include <afs/errors.h>
32 #include <afs/acl.h>
33 #include <afs/prs_fs.h>
34 #include <rx/rx_queue.h>
35
36 #include "nfs.h"
37 #include "lock.h"
38 #include "ihandle.h"
39 #include "vnode.h"
40 #include "volume.h"
41 #include "partition.h"
42 #include "salvage.h"
43 #include "daemon_com_inline.h"
44 #include "fssync_inline.h"
45
46 #ifndef AFS_NT40_ENV
47 #include "AFS_component_version_number.c"
48 #endif
49
50 static const char *progname = NULL;
51 static const char *PLACEHOLDER = "-";
52
53 /* Command line options */
54 typedef enum {
55     P_CHECKOUT,
56     P_VNODE,
57     P_DATE,
58     P_INODE,
59     P_ITIME,
60     P_PART,
61     P_VOLUMEID,
62     P_HEADER,
63     P_SIZEONLY,
64     P_FIXHEADER,
65     P_SAVEINODES,
66     P_ORPHANED,
67     P_FILENAMES,
68     P_TYPE,
69     P_FIND,
70     P_MASK,
71     P_OUTPUT,
72     P_DELIM,
73     P_NOHEADING,
74     P_NOMAGIC,
75 } volinfo_parm_t;
76
77 /*
78  * volscan output columns
79  */
80 #define VOLSCAN_COLUMNS \
81     c(host) \
82     c(desc) \
83     c(vid) \
84     c(offset) \
85     c(vtype) \
86     c(vname) \
87     c(part) \
88     c(partid) \
89     c(fid) \
90     c(path) \
91     c(target) \
92     c(mount) \
93     c(mtype) \
94     c(mcell) \
95     c(mvol) \
96     c(aid) \
97     c(arights) \
98     c(vntype) \
99     c(cloned) \
100     c(mode) \
101     c(links) \
102     c(length) \
103     c(uniq) \
104     c(dv) \
105     c(inode) \
106     c(namei) \
107     c(modtime) \
108     c(author) \
109     c(owner) \
110     c(parent) \
111     c(magic) \
112     c(lock) \
113     c(smodtime) \
114     c(group)
115
116 /* Numeric column type ids */
117 typedef enum columnType {
118 #define c(x) col_##x,
119     VOLSCAN_COLUMNS
120 #undef c
121     max_column_type
122 } columnType;
123
124 struct columnName {
125     columnType type;
126     const char *name;
127 };
128
129 /* Table of id:name tuples of possible columns. */
130 struct columnName ColumnName[] = {
131 #define c(x) { col_##x, #x },
132     VOLSCAN_COLUMNS
133 #undef c
134     {max_column_type, NULL}
135 };
136
137 /* All columns names as a single string. */
138 #define c(x) #x " "
139 static char *ColumnNames = VOLSCAN_COLUMNS;
140 #undef c
141 #undef VOLSCAN_COLUMNS
142
143
144 /* VnodeDetails union descriminator */
145 typedef enum {
146     VNODE_U_NONE,
147     VNODE_U_MOUNT,
148     VNODE_U_SYMLINK,
149     VNODE_U_POS_ACCESS,
150     VNODE_U_NEG_ACCESS
151 } vnode_details_u_t;
152
153 struct VnodeDetails {
154     Volume *vp;
155     VnodeClass class;
156     VnodeDiskObject *vnode;
157     VnodeId vnodeNumber;
158     afs_foff_t offset;
159     int index;
160     char *path;
161     vnode_details_u_t t;
162     union {
163         struct {
164             char type;
165             char *cell;
166             char *vol;
167         } mnt;
168         char *target;
169         struct acl_accessEntry *access;
170     } u;
171 };
172
173 /* Modes */
174 static int Checkout = 0;            /**< Use FSSYNC to checkout volumes from the fileserver. */
175 static int DumpInfo = 0;            /**< Dump volume information */
176 static int DumpHeader = 0;          /**< Dump volume header files info */
177 static int DumpVnodes = 0;          /**< Dump vnode info */
178 static int DumpInodeNumber = 0;     /**< Dump inode numbers with vnodes */
179 static int DumpDate = 0;            /**< Dump vnode date (server modify date) with vnode */
180 static int InodeTimes = 0;          /**< Dump some of the dates associated with inodes */
181 #if defined(AFS_NAMEI_ENV)
182 static int PrintFileNames = 0;      /**< Dump vnode and special file name filenames */
183 #endif
184 static int ShowOrphaned = 0;        /**< Show "orphaned" vnodes (vnodes with parent of 0) */
185 static int ShowSizes = 0;           /**< Show volume size summary */
186 static int SaveInodes = 0;          /**< Save vnode data to files */
187 static int FixHeader = 0;           /**< Repair header files magic and version fields. */
188 static char Hostname[64] = "";      /**< This hostname, for volscan output. */
189 static int NeedDirIndex = 0;        /**< Large vnode index handle is needed for path lookups. */
190 static char ColumnDelim[16] = " ";  /**< Column delimiter char(s) */
191 static char PrintHeading = 0;       /**< Print column heading */
192 static int CheckMagic = 1;          /**< Check directory vnode magic when looking up paths */
193 static unsigned int ModeMask[64];
194
195 static FdHandle_t *DirIndexFd = NULL; /**< Current large vnode index handle for path lookups. */
196
197 static int NumOutputColumns = 0;
198 static columnType OutputColumn[max_column_type];
199
200 #define SCAN_RW  0x01           /**< scan read-write volumes vnodes */
201 #define SCAN_RO  0x02           /**< scan read-only volume vnodes */
202 #define SCAN_BK  0x04           /**< scan backup volume vnodes */
203 static int ScanVolType = 0;     /**< volume types to scan; zero means do not check */
204
205 #define FIND_FILE       0x01    /**< find regular files */
206 #define FIND_DIR        0x02    /**< find directories */
207 #define FIND_MOUNT      0x04    /**< find afs mount points */
208 #define FIND_SYMLINK    0x08    /**< find symlinks */
209 #define FIND_ACL        0x10    /**< find access entiries */
210 static int FindVnType = 0;      /**< types of objects to find */
211
212 /**
213  * Volume size running totals
214  */
215 struct sizeTotals {
216     afs_uint64 diskused_k;      /**< volume size from disk data file, in kilobytes */
217     afs_uint64 auxsize;         /**< size of header files, in bytes  */
218     afs_uint64 auxsize_k;       /**< size of header files, in kilobytes */
219     afs_uint64 vnodesize;       /**< size of the large and small vnodes, in bytes */
220     afs_uint64 vnodesize_k;     /**< size of the large and small vnodes, in kilobytes */
221     afs_uint64 size_k;          /**< size of headers and vnodes, in kilobytes */
222 };
223
224 static struct sizeTotals volumeTotals = { 0, 0, 0, 0, 0, 0 };
225 static struct sizeTotals partitionTotals = { 0, 0, 0, 0, 0, 0 };
226 static struct sizeTotals serverTotals = { 0, 0, 0, 0, 0, 0 };
227 static int PrintingVolumeSizes = 0;     /*print volume size lines */
228
229 /**
230  * List of procedures to call when scanning vnodes.
231  */
232 struct VnodeScanProc {
233     struct opr_queue link;
234     const char *heading;
235     void (*proc) (struct VnodeDetails * vdp);
236 };
237 static struct opr_queue VnodeScanLists[nVNODECLASSES];
238
239 /* Forward Declarations */
240 void PrintHeader(Volume * vp);
241 void HandleAllPart(void);
242 void HandlePart(struct DiskPartition64 *partP);
243 void HandleVolume(struct DiskPartition64 *partP, char *name);
244 struct DiskPartition64 *FindCurrentPartition(void);
245 Volume *AttachVolume(struct DiskPartition64 *dp, char *volname,
246                      struct VolumeHeader *header);
247 void HandleVnodes(Volume * vp, VnodeClass class);
248 static void AddVnodeToSizeTotals(struct VnodeDetails *vdp);
249 static void SaveInode(struct VnodeDetails *vdp);
250 static void PrintVnode(struct VnodeDetails *vdp);
251 static void PrintVnodeDetails(struct VnodeDetails *vdp);
252 static void ScanAcl(struct VnodeDetails *vdp);
253 static void PrintColumnHeading(void);
254 static void PrintColumns(struct VnodeDetails *vdp, const char *desc);
255
256 /* externs */
257 extern void SetSalvageDirHandle(DirHandle * dir, afs_int32 volume,
258                                 Device device, Inode inode,
259                                 int *volumeChanged);
260 extern void FidZap(DirHandle * file);
261
262 /**
263  * Format time as a timestamp string
264  *
265  * @param[in] date  time value to format
266  *
267  * @return timestamp string in the form YYYY/MM/DD.hh:mm:ss
268  *
269  * @note A static array of 8 strings are stored by this
270  *       function. The array slots are overwritten, so the
271  *       caller must not reference the returned string after
272  *       seven additional calls to this function.
273  */
274 char *
275 date(time_t date)
276 {
277 #define MAX_DATE_RESULT 100
278     static char results[8][MAX_DATE_RESULT];
279     static int next;
280     struct tm *tm = localtime(&date);
281     char buf[32];
282
283     (void)strftime(buf, 32, "%Y/%m/%d.%H:%M:%S", tm);   /* NT does not have %T */
284     snprintf(results[next = (next + 1) & 7], MAX_DATE_RESULT,
285              "%lu (%s)", (unsigned long)date, buf);
286     return results[next];
287 }
288
289 #ifdef AFS_NT40_ENV
290 /**
291  * Format file time as a timestamp string
292  *
293  * @param[in] ft  file time
294  *
295  * @return timestamp string in the form YYYY/MM/DD.hh:mm:ss
296  *
297  * @note A static array of 8 strings are stored by this
298  *       function. The array slots are overwritten, so the
299  *       caller must not reference the returned string after
300  *       seven additional calls to this function.
301  */
302 char *
303 NT_date(FILETIME * ft)
304 {
305     static char result[8][64];
306     static int next = 0;
307     SYSTEMTIME st;
308     FILETIME lft;
309
310     if (!FileTimeToLocalFileTime(ft, &lft)
311         || !FileTimeToSystemTime(&lft, &st)) {
312         fprintf(stderr, "%s: Time conversion failed.\n", progname);
313         exit(1);
314     }
315     sprintf(result[next = ((next + 1) & 7)], "%4d/%02d/%02d.%2d:%2d:%2d",
316             st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
317     return result[next];
318 }
319 #endif
320
321 /**
322  * Add vnode size to the running volume totals.
323  *
324  * @param[in]  vdp   vnode details object
325  *
326  * @return none
327  */
328 static void
329 AddVnodeToSizeTotals(struct VnodeDetails *vdp)
330 {
331     afs_fsize_t fileLength;
332
333     VNDISK_GET_LEN(fileLength, vdp->vnode);
334     if (fileLength > 0) {
335         volumeTotals.vnodesize += fileLength;
336         volumeTotals.vnodesize_k += fileLength / 1024;
337     }
338 }
339
340 /**
341  * Print the volume size table heading line, if needed.
342  *
343  * @return none
344  */
345 static void
346 PrintVolumeSizeHeading(void)
347 {
348     if (!PrintingVolumeSizes) {
349         printf
350             ("Volume-Id\t  Volsize  Auxsize Inodesize  AVolsize SizeDiff                (VolName)\n");
351         PrintingVolumeSizes = 1;
352     }
353 }
354
355 /**
356  * Accumulate totals.
357  *
358  * @return 0
359  */
360 static void
361 AddSizeTotals(struct sizeTotals *a, struct sizeTotals *b)
362 {
363     a->diskused_k += b->diskused_k;
364     a->auxsize += b->auxsize;
365     a->auxsize_k += b->auxsize_k;
366     a->vnodesize += b->vnodesize;
367     a->vnodesize_k += b->vnodesize_k;
368     a->size_k += b->size_k;
369 }
370
371 /**
372  * Print the sizes for a volume.
373  *
374  * @return none
375  */
376 static void
377 PrintVolumeSizes(Volume * vp)
378 {
379     afs_int64 diff_k = volumeTotals.size_k - volumeTotals.diskused_k;
380
381     PrintVolumeSizeHeading();
382     printf("%u\t%9llu%9llu%10llu%10llu%9lld\t%24s\n",
383            V_id(vp),
384            volumeTotals.diskused_k,
385            volumeTotals.auxsize_k, volumeTotals.vnodesize_k,
386            volumeTotals.size_k, diff_k, V_name(vp));
387 }
388
389 /**
390  * Print the size totals for the partition.
391  *
392  * @return none
393  */
394 static void
395 PrintPartitionTotals(afs_uint64 nvols)
396 {
397     afs_int64 diff_k = partitionTotals.size_k - partitionTotals.diskused_k;
398
399     PrintVolumeSizeHeading();
400     printf("\nPart Totals  %12llu%9llu%10llu%10llu%9lld (%llu volumes)\n\n",
401            partitionTotals.diskused_k, partitionTotals.auxsize,
402            partitionTotals.vnodesize, partitionTotals.size_k, diff_k, nvols);
403     PrintingVolumeSizes = 0;
404 }
405
406 /**
407  * Print the size totals for all the partitions.
408  *
409  * @return none
410  */
411 static void
412 PrintServerTotals(void)
413 {
414     afs_int64 diff_k = serverTotals.size_k - serverTotals.diskused_k;
415
416     printf("\nServer Totals%12lld%9lld%10lld%10lld%9lld\n",
417            serverTotals.diskused_k, serverTotals.auxsize,
418            serverTotals.vnodesize, serverTotals.size_k, diff_k);
419 }
420
421 /**
422  * Read a volume header file
423  *
424  * @param[in] ih        ihandle of the header file
425  * @param[in] to        destination
426  * @param[in] size      expected header size
427  * @param[in] magic     expected header magic number
428  * @param[in] version   expected header version number
429  *
430  * @return error code
431  *   @retval 0 success
432  *   @retval -1 failed to read file
433  */
434 int
435 ReadHdr1(IHandle_t * ih, char *to, afs_sfsize_t size, u_int magic, u_int version)
436 {
437     struct versionStamp *vsn;
438     int bad = 0;
439     int code;
440
441     vsn = (struct versionStamp *)to;
442
443     code = IH_IREAD(ih, 0, to, size);
444     if (code != size)
445         return -1;
446
447     if (vsn->magic != magic) {
448         bad++;
449         fprintf(stderr, "%s: Inode %s: Bad magic %x (%x): IGNORED\n",
450                 progname, PrintInode(NULL, ih->ih_ino), vsn->magic, magic);
451     }
452
453     /* Check is conditional, in case caller wants to inspect version himself */
454     if (version && vsn->version != version) {
455         bad++;
456         fprintf(stderr, "%s: Inode %s: Bad version %x (%x): IGNORED\n",
457                 progname,
458                 PrintInode(NULL, ih->ih_ino), vsn->version, version);
459     }
460     if (bad && FixHeader) {
461         vsn->magic = magic;
462         vsn->version = version;
463         printf("Special index inode %s has a bad header. Reconstructing...\n",
464                PrintInode(NULL, ih->ih_ino));
465         code = IH_IWRITE(ih, 0, to, size);
466         if (code != size) {
467             fprintf(stderr,
468                     "%s: Write failed for inode %s; header left in damaged state\n",
469                     progname, PrintInode(NULL, ih->ih_ino));
470         }
471     }
472     if (!bad && DumpInfo) {
473         printf("Inode %s: Good magic %x and version %x\n",
474                PrintInode(NULL, ih->ih_ino), magic, version);
475     }
476     return 0;
477 }
478
479 /**
480  * Simplified attach volume
481  *
482  * param[in] dp       vice disk partition object
483  * param[in] volname  volume header file name
484  * param[in] header   volume header object
485  *
486  * @return volume object or null on error
487  */
488 Volume *
489 AttachVolume(struct DiskPartition64 * dp, char *volname,
490              struct VolumeHeader * header)
491 {
492     Volume *vp;
493     afs_int32 ec = 0;
494
495     if (Checkout) {
496         afs_int32 code;
497         SYNC_response response;
498         VolumeId volid = header->id;
499
500         memset(&response, 0, sizeof(response));
501         code =
502             FSYNC_VolOp(volid, dp->name, FSYNC_VOL_NEEDVOLUME, V_DUMP,
503                         &response);
504         if (code != SYNC_OK) {
505             if (response.hdr.reason == FSYNC_SALVAGE) {
506                 fprintf(stderr,
507                         "%s: file server says volume %lu is salvaging.\n",
508                         progname, afs_printable_uint32_lu(volid));
509                 return NULL;
510             } else {
511                 fprintf(stderr,
512                         "%s: attach of volume %lu denied by file server.\n",
513                         progname, afs_printable_uint32_lu(volid));
514                 return NULL;
515             }
516         }
517     }
518
519     vp = (Volume *) calloc(1, sizeof(Volume));
520     if (!vp) {
521         fprintf(stderr, "%s: Failed to allocate volume object.\n", progname);
522         return NULL;
523     }
524     vp->specialStatus = 0;
525     vp->device = dp->device;
526     vp->partition = dp;
527     IH_INIT(vp->vnodeIndex[vLarge].handle, dp->device, header->parent,
528             header->largeVnodeIndex);
529     IH_INIT(vp->vnodeIndex[vSmall].handle, dp->device, header->parent,
530             header->smallVnodeIndex);
531     IH_INIT(vp->diskDataHandle, dp->device, header->parent,
532             header->volumeInfo);
533     IH_INIT(V_linkHandle(vp), dp->device, header->parent, header->linkTable);
534     vp->cacheCheck = 0;         /* XXXX */
535     vp->shuttingDown = 0;
536     vp->goingOffline = 0;
537     vp->nUsers = 1;
538     vp->header = calloc(1, sizeof(*vp->header));
539     if (!vp->header) {
540         fprintf(stderr, "%s: Failed to allocate volume header.\n", progname);
541         free(vp);
542         return NULL;
543     }
544     ec = ReadHdr1(V_diskDataHandle(vp), (char *)&V_disk(vp),
545                   sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
546     if (!ec) {
547         struct IndexFileHeader iHead;
548         ec = ReadHdr1(vp->vnodeIndex[vSmall].handle, (char *)&iHead,
549                       sizeof(iHead), SMALLINDEXMAGIC, SMALLINDEXVERSION);
550     }
551     if (!ec) {
552         struct IndexFileHeader iHead;
553         ec = ReadHdr1(vp->vnodeIndex[vLarge].handle, (char *)&iHead,
554                       sizeof(iHead), LARGEINDEXMAGIC, LARGEINDEXVERSION);
555     }
556 #ifdef AFS_NAMEI_ENV
557     if (!ec) {
558         struct versionStamp stamp;
559         ec = ReadHdr1(V_linkHandle(vp), (char *)&stamp, sizeof(stamp),
560                       LINKTABLEMAGIC, LINKTABLEVERSION);
561     }
562 #endif
563     if (ec)
564         return (Volume *) 0;
565     return vp;
566 }
567
568 /**
569  * Simplified detach volume
570  *
571  * param[in] vp       volume object from AttachVolume
572  *
573  * @return none
574  */
575 static void
576 DetachVolume(Volume * vp)
577 {
578     if (Checkout) {
579         afs_int32 code;
580         SYNC_response response;
581         memset(&response, 0, sizeof(response));
582
583         code = FSYNC_VolOp(V_id(vp), V_partition(vp)->name,
584                            FSYNC_VOL_ON, FSYNC_WHATEVER, &response);
585         if (code != SYNC_OK) {
586             fprintf(stderr, "%s: FSSYNC error %d (%s)\n", progname, code,
587                     SYNC_res2string(code));
588             fprintf(stderr, "%s:  protocol response code was %d (%s)\n",
589                     progname, response.hdr.response,
590                     SYNC_res2string(response.hdr.response));
591             fprintf(stderr, "%s:  protocol reason code was %d (%s)\n",
592                     progname, response.hdr.reason,
593                     FSYNC_reason2string(response.hdr.reason));
594         }
595     }
596
597     IH_RELEASE(vp->vnodeIndex[vLarge].handle);
598     IH_RELEASE(vp->vnodeIndex[vSmall].handle);
599     IH_RELEASE(vp->diskDataHandle);
600     IH_RELEASE(V_linkHandle(vp));
601     free(vp->header);
602     free(vp);
603 }
604
605 /**
606  * Convert the partition device number into a partition name.
607  *
608  * @param[in]   partId      partition number, 0 to 254
609  * @param[out]  partName    buffer to hold partition name (e.g. /vicepa)
610  * @param[in]   partNameSize    size of partName buffer
611  *
612  * @return status
613  *   @retval 0 success
614  *   @retval -1 error, partId is out of range
615  *   @retval -2 error, partition name exceeds partNameSize
616  */
617 static int
618 GetPartitionName(afs_uint32 partId, char *partName, afs_size_t partNameSize)
619 {
620     const afs_uint32 OLD_NUM_DEVICES = 26;      /* a..z */
621
622     if (partId < OLD_NUM_DEVICES) {
623         if (partNameSize < 8) {
624             return -2;
625         }
626         strlcpy(partName, "/vicep", partNameSize);
627         partName[6] = partId + 'a';
628         partName[7] = '\0';
629         return 0;
630     }
631     if (partId < VOLMAXPARTS) {
632         if (partNameSize < 9) {
633             return -2;
634         }
635         strlcpy(partName, "/vicep", partNameSize);
636         partId -= OLD_NUM_DEVICES;
637         partName[6] = 'a' + (partId / OLD_NUM_DEVICES);
638         partName[7] = 'a' + (partId % OLD_NUM_DEVICES);
639         partName[8] = '\0';
640         return 0;
641     }
642     return -1;
643 }
644
645 /**
646  * Scan the volumes in the partitions
647  *
648  * Scan the specified volume in the specified partition if both
649  * are given. Scan all the volumes in the specified partition if
650  * only the partition is given.  If neither a partition nor volume
651  * is given, scan all the volumes in all the partitions.  If only
652  * the volume is given, attempt to find it in the current working
653  * directory.
654  *
655  * @param[in] partNameOrId   partition name or id to be scannned
656  * @param[in] volumeId       volume id to be scanned
657  *
658  * @return 0 if successful
659  */
660 static int
661 ScanPartitions(char *partNameOrId, afs_uint32 volumeId)
662 {
663     int err = 0;
664     char partName[64] = "";
665     struct DiskPartition64 *partP = NULL;
666
667 #ifndef AFS_NT40_ENV
668     if (geteuid() != 0) {
669         fprintf(stderr, "%s: Must be run as root; sorry\n", progname);
670         return 1;
671     }
672 #endif
673
674     if (Checkout) {
675         if (!FSYNC_clientInit()) {
676             fprintf(stderr, "%s: Failed to connect to fileserver.\n",
677                     progname);
678             return 1;
679         }
680     }
681
682     DInit(1024);
683     VInitVnodes(vLarge, 0);
684     VInitVnodes(vSmall, 0);
685
686     /* Allow user to specify partition by name or id. */
687     if (partNameOrId) {
688         afs_uint32 partId = volutil_GetPartitionID(partNameOrId);
689         if (partId == -1) {
690             fprintf(stderr, "%s: Could not parse '%s' as a partition name.\n",
691                     progname, partNameOrId);
692             err = 1;
693             goto cleanup;
694         }
695         if (GetPartitionName(partId, partName, sizeof(partName))) {
696             fprintf(stderr,
697                     "%s: Could not format '%s' as a partition name.\n",
698                     progname, partNameOrId);
699             err = 1;
700             goto cleanup;
701         }
702     }
703
704     err = VAttachPartitions();
705     if (err) {
706         fprintf(stderr, "%s: %d partitions had errors during attach.\n",
707                 progname, err);
708         err = 1;
709         goto cleanup;
710     }
711
712     if (partName[0]) {
713         partP = VGetPartition(partName, 0);
714         if (!partP) {
715             fprintf(stderr,
716                     "%s: %s is not an AFS partition name on this server.\n",
717                     progname, partName);
718             err = 1;
719             goto cleanup;
720         }
721     }
722
723     if (!volumeId) {
724         if (PrintHeading) {
725             PrintColumnHeading();
726         }
727         if (!partP) {
728             HandleAllPart();
729         } else {
730             HandlePart(partP);
731         }
732     } else {
733         char name1[128];
734
735         if (!partP) {
736             partP = FindCurrentPartition();
737             if (!partP) {
738                 fprintf(stderr,
739                         "%s: Current partition is not a vice partition.\n",
740                         progname);
741                 err = 1;
742                 goto cleanup;
743             }
744         }
745         snprintf(name1, sizeof name1, VFORMAT,
746                  afs_printable_uint32_lu(volumeId));
747         if (PrintHeading) {
748             PrintColumnHeading();
749         }
750         HandleVolume(partP, name1);
751     }
752
753   cleanup:
754     if (Checkout) {
755         FSYNC_clientFinis();
756     }
757     return err;
758 }
759
760 /**
761  * Add a vnode scanning procedure
762  *
763  * @param[in]   class   vnode class for this handler
764  * @param[in]   proc    handler proc to be called by HandleVnodes
765  * @param[in]   heading optional string to pring before scanning vnodes
766  *
767  * @return none
768  */
769 static void
770 AddVnodeHandler(VnodeClass class, void (*proc) (struct VnodeDetails * vdp),
771                 const char *heading)
772 {
773     struct VnodeScanProc *entry = malloc(sizeof(struct VnodeScanProc));
774     entry->proc = proc;
775     entry->heading = heading;
776     opr_queue_Append(&VnodeScanLists[class], (struct opr_queue *)entry);
777 }
778
779 /**
780  * Process command line options and start scanning
781  *
782  * @param[in] as     command syntax object
783  * @param[in] arock  opaque object; not used
784  *
785  * @return error code
786  */
787 static int
788 VolInfo(struct cmd_syndesc *as, void *arock)
789 {
790     struct cmd_item *ti;
791     afs_uint32 volumeId = 0;
792     char *partNameOrId = NULL;
793
794     DumpInfo = 1;               /* volinfo default mode */
795
796     if (as->parms[P_CHECKOUT].items) {
797         Checkout = 1;
798     }
799     if (as->parms[P_VNODE].items) {
800         DumpVnodes = 1;
801     }
802     if (as->parms[P_DATE].items) {
803         DumpDate = 1;
804     }
805     if (as->parms[P_INODE].items) {
806         DumpInodeNumber = 1;
807     }
808     if (as->parms[P_ITIME].items) {
809         InodeTimes = 1;
810     }
811     if ((ti = as->parms[P_PART].items)) {
812         partNameOrId = ti->data;
813     }
814     if ((ti = as->parms[P_VOLUMEID].items)) {
815         volumeId = strtoul(ti->data, NULL, 10);
816     }
817     if (as->parms[P_HEADER].items) {
818         DumpHeader = 1;
819     }
820     if (as->parms[P_SIZEONLY].items) {
821         ShowSizes = 1;
822     }
823     if (as->parms[P_FIXHEADER].items) {
824         FixHeader = 1;
825     }
826     if (as->parms[P_SAVEINODES].items) {
827         SaveInodes = 1;
828     }
829     if (as->parms[P_ORPHANED].items) {
830         ShowOrphaned = 1;
831     }
832 #if defined(AFS_NAMEI_ENV)
833     if (as->parms[P_FILENAMES].items) {
834         PrintFileNames = 1;
835     }
836 #endif
837
838     /* -saveinodes and -sizeOnly override the default mode.
839      * For compatibility with old versions of volinfo, -orphaned
840      * and -filename options imply -vnodes */
841     if (SaveInodes || ShowSizes) {
842         DumpInfo = 0;
843         DumpHeader = 0;
844         DumpVnodes = 0;
845         InodeTimes = 0;
846         ShowOrphaned = 0;
847     } else if (ShowOrphaned) {
848         DumpVnodes = 1;         /* implied */
849 #ifdef AFS_NAMEI_ENV
850     } else if (PrintFileNames) {
851         DumpVnodes = 1;         /* implied */
852 #endif
853     }
854
855     if (SaveInodes) {
856         AddVnodeHandler(vSmall, SaveInode,
857                         "Saving all volume files to current directory ...\n");
858     }
859     if (ShowSizes) {
860         AddVnodeHandler(vLarge, AddVnodeToSizeTotals, NULL);
861         AddVnodeHandler(vSmall, AddVnodeToSizeTotals, NULL);
862     }
863     if (DumpVnodes) {
864         AddVnodeHandler(vLarge, PrintVnode, "\nLarge vnodes (directories)\n");
865         AddVnodeHandler(vSmall, PrintVnode,
866                         "\nSmall vnodes(files, symbolic links)\n");
867     }
868     return ScanPartitions(partNameOrId, volumeId);
869 }
870
871 /**
872  * Add a column type to be displayed.
873  *
874  * @param[in]  name   column type name
875  *
876  * @return error code
877  *   @retval 0 success
878  *   @retval 1 too many columns
879  *   @retval 2 invalid column name
880  */
881 static int
882 AddOutputColumn(char *name)
883 {
884     int i;
885
886     if (NumOutputColumns >= sizeof(OutputColumn) / sizeof(*OutputColumn)) {
887         fprintf(stderr, "%s: Too many output columns (%d).\n", progname,
888                 NumOutputColumns);
889         return 1;
890     }
891     for (i = 0; i < max_column_type; i++) {
892         if (!strcmp(ColumnName[i].name, name)) {
893             columnType t = ColumnName[i].type;
894             OutputColumn[NumOutputColumns++] = t;
895
896             if (t == col_path) {
897                 NeedDirIndex = 1;
898             }
899             return 0;
900         }
901     }
902     return 2;
903 }
904
905 /**
906  * Process command line options and start scanning
907  *
908  * @param[in] as     command syntax object
909  * @param[in] arock  opaque object; not used
910  *
911  * @return error code
912  *    @retval 0 success
913  *    @retvol 1 failure
914  */
915 static int
916 VolScan(struct cmd_syndesc *as, void *arock)
917 {
918     struct cmd_item *ti;
919     afs_uint32 volumeId = 0;
920     char *partNameOrId = NULL;
921     int i;
922
923     if (as->parms[P_CHECKOUT].items) {
924         Checkout = 1;
925     }
926     if ((ti = as->parms[P_PART].items)) {
927         partNameOrId = ti->data;
928     }
929     if ((ti = as->parms[P_VOLUMEID].items)) {
930         volumeId = strtoul(ti->data, NULL, 10);
931     }
932     if (as->parms[P_NOHEADING].items) {
933         PrintHeading = 0;
934     } else {
935         PrintHeading = 1;
936     }
937     if (as->parms[P_NOMAGIC].items) {
938         CheckMagic = 0;
939     }
940     if ((ti = as->parms[P_DELIM].items)) {
941         strncpy(ColumnDelim, ti->data, 15);
942         ColumnDelim[15] = '\0';
943     }
944
945     /* Limit types of volumes to scan. */
946     if (!as->parms[P_TYPE].items) {
947         ScanVolType = (SCAN_RW | SCAN_RO | SCAN_BK);
948     } else {
949         ScanVolType = 0;
950         for (ti = as->parms[P_TYPE].items; ti; ti = ti->next) {
951             if (strcmp(ti->data, "rw") == 0) {
952                 ScanVolType |= SCAN_RW;
953             } else if (strcmp(ti->data, "ro") == 0) {
954                 ScanVolType |= SCAN_RO;
955             } else if (strcmp(ti->data, "bk") == 0) {
956                 ScanVolType |= SCAN_BK;
957             } else {
958                 fprintf(stderr, "%s: Unknown -type value: %s\n", progname,
959                         ti->data);
960                 return 1;
961             }
962         }
963     }
964
965     /* Limit types of vnodes to find (plus access entries) */
966     if (!as->parms[P_FIND].items) {
967         FindVnType = (FIND_FILE | FIND_DIR | FIND_MOUNT | FIND_SYMLINK);
968     } else {
969         FindVnType = 0;
970         for (ti = as->parms[P_FIND].items; ti; ti = ti->next) {
971             if (strcmp(ti->data, "file") == 0) {
972                 FindVnType |= FIND_FILE;
973             } else if (strcmp(ti->data, "dir") == 0) {
974                 FindVnType |= FIND_DIR;
975             } else if (strcmp(ti->data, "mount") == 0) {
976                 FindVnType |= FIND_MOUNT;
977             } else if (strcmp(ti->data, "symlink") == 0) {
978                 FindVnType |= FIND_SYMLINK;
979             } else if (strcmp(ti->data, "acl") == 0) {
980                 FindVnType |= FIND_ACL;
981             } else {
982                 fprintf(stderr, "%s: Unknown -find value: %s\n", progname,
983                         ti->data);
984                 return 1;
985             }
986         }
987     }
988
989     /* Show vnodes matching one of the mode masks */
990     for (i = 0, ti = as->parms[P_MASK].items; ti; i++, ti = ti->next) {
991         if (i >= (sizeof(ModeMask) / sizeof(*ModeMask))) {
992             fprintf(stderr, "Too many -mask values\n");
993             return -1;
994         }
995         ModeMask[i] = strtol(ti->data, NULL, 8);
996         if (!ModeMask[i]) {
997             fprintf(stderr, "Invalid -mask value: %s\n", ti->data);
998             return 1;
999         }
1000     }
1001
1002     /* Set which columns to be printed. */
1003     if (!as->parms[P_OUTPUT].items) {
1004         AddOutputColumn("host");
1005         AddOutputColumn("desc");
1006         AddOutputColumn("fid");
1007         AddOutputColumn("dv");
1008         if (FindVnType & FIND_ACL) {
1009             AddOutputColumn("aid");
1010             AddOutputColumn("arights");
1011         }
1012         AddOutputColumn("path");
1013     } else {
1014         for (ti = as->parms[P_OUTPUT].items; ti; ti = ti->next) {
1015             if (AddOutputColumn(ti->data) != 0) {;
1016                 fprintf(stderr, "%s: Unknown -output value: %s\n", progname,
1017                         ti->data);
1018                 return 1;
1019             }
1020         }
1021     }
1022
1023     if (FindVnType & FIND_DIR) {
1024         AddVnodeHandler(vLarge, PrintVnodeDetails, NULL);
1025     }
1026     if (FindVnType & (FIND_FILE | FIND_MOUNT | FIND_SYMLINK)) {
1027         AddVnodeHandler(vSmall, PrintVnodeDetails, NULL);
1028     }
1029     if (FindVnType & FIND_ACL) {
1030         AddVnodeHandler(vLarge, ScanAcl, NULL);
1031     }
1032
1033     return ScanPartitions(partNameOrId, volumeId);
1034 }
1035
1036 /**
1037  * Determine if the current directory is a vice partition
1038  *
1039  * @return disk partition object
1040  */
1041 #ifdef AFS_NT40_ENV
1042 #include <direct.h>
1043 struct DiskPartition64 *
1044 FindCurrentPartition(void)
1045 {
1046     int dr = _getdrive();
1047     struct DiskPartition64 *dp;
1048
1049     dr--;
1050     for (dp = DiskPartitionList; dp; dp = dp->next) {
1051         if (*dp->devName - 'A' == dr)
1052             break;
1053     }
1054     if (!dp) {
1055         fprintf(stderr, "%s: Current drive is not a valid vice partition.\n",
1056                 progname);
1057     }
1058     return dp;
1059 }
1060 #else
1061 struct DiskPartition64 *
1062 FindCurrentPartition(void)
1063 {
1064     char partName[1024];
1065     char tmp = '\0';
1066     char *p;
1067     struct DiskPartition64 *dp;
1068
1069     if (!getcwd(partName, 1023)) {
1070         fprintf(stderr, "%s: Failed to get current working directory: ",
1071                 progname);
1072         perror("pwd");
1073         return NULL;
1074     }
1075     p = strchr(&partName[1], OS_DIRSEPC);
1076     if (p) {
1077         tmp = *p;
1078         *p = '\0';
1079     }
1080     if (!(dp = VGetPartition(partName, 0))) {
1081         if (tmp)
1082             *p = tmp;
1083         fprintf(stderr, "%s: %s is not a valid vice partition.\n", progname,
1084                 partName);
1085         return NULL;
1086     }
1087     return dp;
1088 }
1089 #endif
1090
1091 /**
1092  * Scan and handle all the partitions detected on this server
1093  *
1094  * @return none
1095  */
1096 void
1097 HandleAllPart(void)
1098 {
1099     struct DiskPartition64 *partP;
1100
1101
1102     for (partP = DiskPartitionList; partP; partP = partP->next) {
1103         if (DumpInfo || SaveInodes || ShowSizes) {
1104             printf("Processing Partition %s:\n", partP->name);
1105         }
1106         HandlePart(partP);
1107         if (ShowSizes) {
1108             AddSizeTotals(&serverTotals, &partitionTotals);
1109         }
1110     }
1111
1112     if (ShowSizes) {
1113         PrintServerTotals();
1114     }
1115 }
1116
1117 /**
1118  * Scan the partition and handle volumes
1119  *
1120  * @param[in] partP  disk partition to scan
1121  *
1122  * @return none
1123  */
1124 void
1125 HandlePart(struct DiskPartition64 *partP)
1126 {
1127     afs_int64 nvols = 0;
1128     DIR *dirp;
1129     struct dirent *dp;
1130 #ifdef AFS_NT40_ENV
1131     char pname[64];
1132     char *p = pname;
1133     (void)sprintf(pname, "%s\\", VPartitionPath(partP));
1134 #else
1135     char *p = VPartitionPath(partP);
1136 #endif
1137
1138     if ((dirp = opendir(p)) == NULL) {
1139         fprintf(stderr, "%s: Can't read directory %s; giving up\n", progname,
1140                 p);
1141         return;
1142     }
1143     while ((dp = readdir(dirp))) {
1144         p = (char *)strrchr(dp->d_name, '.');
1145         if (p != NULL && strcmp(p, VHDREXT) == 0) {
1146             HandleVolume(partP, dp->d_name);
1147             if (ShowSizes) {
1148                 nvols++;
1149                 AddSizeTotals(&partitionTotals, &volumeTotals);
1150             }
1151         }
1152     }
1153     closedir(dirp);
1154     if (ShowSizes) {
1155         PrintPartitionTotals(nvols);
1156     }
1157 }
1158
1159 /**
1160  * Inspect a volume header special file.
1161  *
1162  * @param[in]  name       descriptive name of the type of header special file
1163  * @param[in]  dp         partition object for this volume
1164  * @param[in]  header     header object for this volume
1165  * @param[in]  inode      fileserver inode number for this header special file
1166  * @param[out] psize      total of the header special file
1167  *
1168  * @return none
1169  */
1170 void
1171 HandleSpecialFile(const char *name, struct DiskPartition64 *dp,
1172                   struct VolumeHeader *header, Inode inode,
1173                   afs_sfsize_t * psize)
1174 {
1175     afs_sfsize_t size = -1;
1176     IHandle_t *ih = NULL;
1177     FdHandle_t *fdP = NULL;
1178 #ifdef AFS_NAMEI_ENV
1179     namei_t filename;
1180 #endif /* AFS_NAMEI_ENV */
1181
1182     IH_INIT(ih, dp->device, header->parent, inode);
1183     fdP = IH_OPEN(ih);
1184     if (fdP == NULL) {
1185         fprintf(stderr,
1186                 "%s: Error opening header file '%s' for volume %u\n", progname,
1187                 name, header->id);
1188         perror("open");
1189         goto error;
1190     }
1191     size = FDH_SIZE(fdP);
1192     if (size == -1) {
1193         fprintf(stderr,
1194                 "%s: Error getting size of header file '%s' for volume %u\n",
1195                 progname, name, header->id);
1196         perror("fstat");
1197         goto error;
1198     }
1199     *psize += size;
1200
1201   error:
1202     if (DumpInfo) {
1203         printf("\t%s inode\t= %s (size = ", name, PrintInode(NULL, inode));
1204         if (size != -1) {
1205             printf("%lld)\n", size);
1206         } else {
1207             printf("unknown)\n");
1208         }
1209 #ifdef AFS_NAMEI_ENV
1210         namei_HandleToName(&filename, ih);
1211         printf("\t%s namei\t= %s\n", name, filename.n_path);
1212 #endif /* AFS_NAMEI_ENV */
1213     }
1214
1215     if (fdP != NULL) {
1216         FDH_REALLYCLOSE(fdP);
1217     }
1218     if (ih != NULL) {
1219         IH_RELEASE(ih);
1220     }
1221 }
1222
1223 /**
1224  * Inspect this volume header files.
1225  *
1226  * @param[in]  dp         partition object for this volume
1227  * @param[in]  header_fd  volume header file descriptor
1228  * @param[in]  header     volume header object
1229  * @param[out] psize      total of the header special file
1230  *
1231  * @return none
1232  */
1233 void
1234 HandleHeaderFiles(struct DiskPartition64 *dp, FD_t header_fd,
1235                   struct VolumeHeader *header)
1236 {
1237     afs_sfsize_t size = 0;
1238
1239     if (DumpInfo) {
1240         size = OS_SIZE(header_fd);
1241         printf("Volume header (size = %lld):\n", size);
1242         printf("\tstamp\t= 0x%x\n", header->stamp.version);
1243         printf("\tVolId\t= %u\n", header->id);
1244         printf("\tparent\t= %u\n", header->parent);
1245     }
1246
1247     HandleSpecialFile("Info", dp, header, header->volumeInfo, &size);
1248     HandleSpecialFile("Small", dp, header, header->smallVnodeIndex,
1249                       &size);
1250     HandleSpecialFile("Large", dp, header, header->largeVnodeIndex,
1251                       &size);
1252 #ifdef AFS_NAMEI_ENV
1253     HandleSpecialFile("Link", dp, header, header->linkTable, &size);
1254 #endif /* AFS_NAMEI_ENV */
1255
1256     if (DumpInfo) {
1257         printf("Total aux volume size = %lld\n\n", size);
1258     }
1259
1260     if (ShowSizes) {
1261         volumeTotals.auxsize = size;
1262         volumeTotals.auxsize_k = size / 1024;
1263     }
1264 }
1265
1266 /**
1267  * Determine if the vnodes of this volume should be scanned.
1268  *
1269  * @param[in]  vp   volume object
1270  *
1271  * @return true if vnodes should be scanned
1272  */
1273 static int
1274 IsScannable(Volume * vp)
1275 {
1276     if (opr_queue_IsEmpty(&VnodeScanLists[vLarge]) &&
1277         opr_queue_IsEmpty(&VnodeScanLists[vSmall])) {
1278         return 0;
1279     }
1280     if (!ScanVolType) {
1281         return 1;               /* filtering disabled; do not check vol type */
1282     }
1283     switch (V_type(vp)) {
1284     case RWVOL:
1285         return ScanVolType & SCAN_RW;
1286     case ROVOL:
1287         return ScanVolType & SCAN_RO;
1288     case BACKVOL:
1289         return ScanVolType & SCAN_BK;
1290     default:
1291         fprintf(stderr, "%s: Volume %u; Unknown volume type %d\n", progname,
1292                 V_id(vp), V_type(vp));
1293         break;
1294     }
1295     return 0;
1296 }
1297
1298 /**
1299  * Attach and scan the volume and handle the header and vnodes
1300  *
1301  * Print the volume header and vnode information, depending on the
1302  * current modes.
1303  *
1304  * @param[in] dp    vice partition object for this volume
1305  * @param[in] name  volume header file name
1306  *
1307  * @return none
1308  */
1309 void
1310 HandleVolume(struct DiskPartition64 *dp, char *name)
1311 {
1312     struct VolumeHeader header;
1313     struct VolumeDiskHeader diskHeader;
1314     FD_t fd = INVALID_FD;
1315     Volume *vp = NULL;
1316     char headerName[1024];
1317     afs_sfsize_t n;
1318
1319     snprintf(headerName, sizeof headerName, "%s" OS_DIRSEP "%s",
1320              VPartitionPath(dp), name);
1321     if ((fd = OS_OPEN(headerName, O_RDONLY, 0666)) == INVALID_FD) {
1322         fprintf(stderr, "%s: Cannot open volume header %s\n", progname, name);
1323         goto cleanup;
1324     }
1325     if (OS_SIZE(fd) < 0) {
1326         fprintf(stderr, "%s: Cannot read volume header %s\n", progname, name);
1327         goto cleanup;
1328     }
1329     n = OS_READ(fd, &diskHeader, sizeof(diskHeader));
1330     if (n != sizeof(diskHeader)
1331         || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
1332         fprintf(stderr, "%s: Error reading volume header %s\n", progname,
1333                 name);
1334         goto cleanup;
1335     }
1336     if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
1337         fprintf(stderr,
1338                 "%s: Volume %s, version number is incorrect; volume needs to be salvaged\n",
1339                 progname, name);
1340         goto cleanup;
1341     }
1342
1343     DiskToVolumeHeader(&header, &diskHeader);
1344     if (DumpHeader || ShowSizes) {
1345         HandleHeaderFiles(dp, fd, &header);
1346     }
1347
1348     vp = AttachVolume(dp, name, &header);
1349     if (!vp) {
1350         fprintf(stderr, "%s: Error attaching volume header %s\n",
1351                 progname, name);
1352         goto cleanup;
1353     }
1354
1355     if (DumpInfo) {
1356         PrintHeader(vp);
1357     }
1358     if (IsScannable(vp)) {
1359         if (NeedDirIndex) {
1360             IHandle_t *ih = vp->vnodeIndex[vLarge].handle;
1361             DirIndexFd = IH_OPEN(ih);
1362             if (DirIndexFd == NULL) {
1363                 fprintf(stderr, "%s: Failed to open index for directories.",
1364                         progname);
1365             }
1366         }
1367
1368         HandleVnodes(vp, vLarge);
1369         HandleVnodes(vp, vSmall);
1370
1371         if (DirIndexFd) {
1372             FDH_CLOSE(DirIndexFd);
1373             DirIndexFd = NULL;
1374         }
1375     }
1376     if (ShowSizes) {
1377         volumeTotals.diskused_k = V_diskused(vp);
1378         volumeTotals.size_k =
1379             volumeTotals.auxsize_k + volumeTotals.vnodesize_k;
1380         if (SaveInodes) {
1381             PrintingVolumeSizes = 0;    /* print heading again */
1382         }
1383         PrintVolumeSizes(vp);
1384     }
1385
1386   cleanup:
1387     if (fd != INVALID_FD) {
1388         OS_CLOSE(fd);
1389     }
1390     if (vp) {
1391         DetachVolume(vp);
1392     }
1393 }
1394
1395 /**
1396  * Declare volinfo command line syntax
1397  *
1398  * @returns none
1399  */
1400 static void
1401 VolInfoSyntax(void)
1402 {
1403     struct cmd_syndesc *ts;
1404
1405     ts = cmd_CreateSyntax(NULL, VolInfo, NULL,
1406                           "Dump volume's internal state");
1407     cmd_AddParmAtOffset(ts, P_CHECKOUT, "-checkout", CMD_FLAG, CMD_OPTIONAL,
1408                         "Checkout volumes from running fileserver");
1409     cmd_AddParmAtOffset(ts, P_VNODE, "-vnode", CMD_FLAG, CMD_OPTIONAL,
1410                         "Dump vnode info");
1411     cmd_AddParmAtOffset(ts, P_DATE, "-date", CMD_FLAG, CMD_OPTIONAL,
1412                         "Also dump vnode's mod date");
1413     cmd_AddParmAtOffset(ts, P_INODE, "-inode", CMD_FLAG, CMD_OPTIONAL,
1414                         "Also dump vnode's inode number");
1415     cmd_AddParmAtOffset(ts, P_ITIME, "-itime", CMD_FLAG, CMD_OPTIONAL,
1416                         "Dump special inode's mod times");
1417     cmd_AddParmAtOffset(ts, P_PART, "-part", CMD_LIST, CMD_OPTIONAL,
1418                         "AFS partition name or id (default current partition)");
1419     cmd_AddParmAtOffset(ts, P_VOLUMEID, "-volumeid", CMD_LIST, CMD_OPTIONAL,
1420                         "Volume id");
1421     cmd_AddParmAtOffset(ts, P_HEADER, "-header", CMD_FLAG, CMD_OPTIONAL,
1422                         "Dump volume's header info");
1423     cmd_AddParmAtOffset(ts, P_SIZEONLY, "-sizeonly", CMD_FLAG, CMD_OPTIONAL,
1424                         "Dump volume's size");
1425     cmd_AddParmAtOffset(ts, P_FIXHEADER, "-fixheader", CMD_FLAG,
1426                         CMD_OPTIONAL, "Try to fix header");
1427     cmd_AddParmAtOffset(ts, P_SAVEINODES, "-saveinodes", CMD_FLAG,
1428                         CMD_OPTIONAL, "Try to save all inodes");
1429     cmd_AddParmAtOffset(ts, P_ORPHANED, "-orphaned", CMD_FLAG, CMD_OPTIONAL,
1430                         "List all dir/files without a parent");
1431 #if defined(AFS_NAMEI_ENV)
1432     cmd_AddParmAtOffset(ts, P_FILENAMES, "-filenames", CMD_FLAG,
1433                         CMD_OPTIONAL, "Also dump vnode's namei filename");
1434 #endif
1435
1436     /* For compatibility with older versions. */
1437     cmd_AddParmAlias(ts, P_SIZEONLY, "-sizeOnly");
1438 }
1439
1440 /**
1441  * Declare volscan command line syntax
1442  *
1443  * @returns none
1444  */
1445 static void
1446 VolScanSyntax(void)
1447 {
1448     struct cmd_syndesc *ts;
1449
1450     ts = cmd_CreateSyntax(NULL, VolScan, NULL,
1451                           "Print volume vnode information");
1452
1453     cmd_AddParmAtOffset(ts, P_CHECKOUT, "-checkout", CMD_FLAG, CMD_OPTIONAL,
1454                         "Checkout volumes from running fileserver");
1455     cmd_AddParmAtOffset(ts, P_PART, "-partition", CMD_SINGLE, CMD_OPTIONAL,
1456                         "AFS partition name or id (default current partition)");
1457     cmd_AddParmAtOffset(ts, P_VOLUMEID, "-volumeid", CMD_SINGLE, CMD_OPTIONAL,
1458                         "Volume id (-partition required)");
1459     cmd_AddParmAtOffset(ts, P_TYPE, "-type", CMD_LIST, CMD_OPTIONAL,
1460                         "Volume types: rw, ro, bk");
1461     cmd_AddParmAtOffset(ts, P_FIND, "-find", CMD_LIST, CMD_OPTIONAL,
1462                         "Objects to find: file, dir, mount, symlink, acl");
1463     cmd_AddParmAtOffset(ts, P_MASK, "-mask", CMD_LIST, CMD_OPTIONAL,
1464                         "Unix mode mask (example: 06000)");
1465     cmd_AddParmAtOffset(ts, P_OUTPUT, "-output", CMD_LIST, CMD_OPTIONAL,
1466                         ColumnNames);
1467     cmd_AddParmAtOffset(ts, P_DELIM, "-delim", CMD_SINGLE, CMD_OPTIONAL,
1468                         "Output field delimiter");
1469     cmd_AddParmAtOffset(ts, P_NOHEADING, "-noheading", CMD_FLAG, CMD_OPTIONAL,
1470                         "Do not print the heading line");
1471     cmd_AddParmAtOffset(ts, P_NOMAGIC, "-ignore-magic", CMD_FLAG, CMD_OPTIONAL,
1472                         "Skip directory vnode magic checks when looking up paths.");
1473 }
1474
1475 /**
1476  * volinfo/volscan program entry
1477  */
1478 int
1479 main(int argc, char **argv)
1480 {
1481     afs_int32 code;
1482     char *base;
1483
1484     opr_queue_Init(&VnodeScanLists[vLarge]);
1485     opr_queue_Init(&VnodeScanLists[vSmall]);
1486     memset(ModeMask, 0, sizeof(ModeMask) / sizeof(*ModeMask));
1487     gethostname(Hostname, sizeof(Hostname));
1488
1489     base = strrchr(argv[0], '/');
1490 #ifdef AFS_NT40_ENV
1491     if (!base) {
1492         base = strrchr(argv[0], '\\');
1493     }
1494 #endif /* AFS_NT40_ENV */
1495     if (!base) {
1496         base = argv[0];
1497     }
1498 #ifdef AFS_NT40_ENV
1499     if ((base[0] == '/' || base[0] == '\\') && base[1] != '\0') {
1500 #else /* AFS_NT40_ENV */
1501     if (base[0] == '/' && base[1] != '\0') {
1502 #endif /* AFS_NT40_ENV */
1503         base++;
1504     }
1505     progname = base;
1506
1507 #ifdef AFS_NT40_ENV
1508     if (stricmp(progname, "volscan") == 0
1509         || stricmp(progname, "volscan.exe") == 0) {
1510 #else /* AFS_NT40_ENV */
1511     if (strcmp(progname, "volscan") == 0) {
1512 #endif /* AFS_NT40_ENV */
1513         VolScanSyntax();
1514     } else {
1515         VolInfoSyntax();
1516     }
1517
1518     code = cmd_Dispatch(argc, argv);
1519     return code;
1520 }
1521
1522 /**
1523  * Return a display string for the volume type.
1524  *
1525  * @param[in]  type  volume type
1526  *
1527  * @return volume type description string
1528  */
1529 static_inline char *
1530 volumeTypeString(int type)
1531 {
1532     return
1533         (type == RWVOL ? "read/write" :
1534          (type == ROVOL ? "readonly" :
1535           (type == BACKVOL ? "backup" : "unknown")));
1536 }
1537
1538 /**
1539  * Return a short display string for the volume type.
1540  *
1541  * @param[in]  type  volume type
1542  *
1543  * @return volume type short description string
1544  */
1545 static_inline char *
1546 volumeTypeShortString(int type)
1547 {
1548     return
1549         (type == RWVOL ? "RW" :
1550          (type == ROVOL ? "RO" : (type == BACKVOL ? "BK" : "??")));
1551 }
1552
1553 /**
1554  * Print the volume header information
1555  *
1556  * @param[in]  volume object
1557  *
1558  * @return none
1559  */
1560 void
1561 PrintHeader(Volume * vp)
1562 {
1563     printf("Volume header for volume %u (%s)\n", V_id(vp), V_name(vp));
1564     printf("stamp.magic = %x, stamp.version = %u\n", V_stamp(vp).magic,
1565            V_stamp(vp).version);
1566     printf
1567         ("inUse = %d, inService = %d, blessed = %d, needsSalvaged = %d, dontSalvage = %d\n",
1568          V_inUse(vp), V_inService(vp), V_blessed(vp), V_needsSalvaged(vp),
1569          V_dontSalvage(vp));
1570     printf
1571         ("type = %d (%s), uniquifier = %u, needsCallback = %d, destroyMe = %x\n",
1572          V_type(vp), volumeTypeString(V_type(vp)), V_uniquifier(vp),
1573          V_needsCallback(vp), V_destroyMe(vp));
1574     printf
1575         ("id = %u, parentId = %u, cloneId = %u, backupId = %u, restoredFromId = %u\n",
1576          V_id(vp), V_parentId(vp), V_cloneId(vp), V_backupId(vp),
1577          V_restoredFromId(vp));
1578     printf
1579         ("maxquota = %d, minquota = %d, maxfiles = %d, filecount = %d, diskused = %d\n",
1580          V_maxquota(vp), V_minquota(vp), V_maxfiles(vp), V_filecount(vp),
1581          V_diskused(vp));
1582     printf("creationDate = %s, copyDate = %s\n", date(V_creationDate(vp)),
1583            date(V_copyDate(vp)));
1584     printf("backupDate = %s, expirationDate = %s\n", date(V_backupDate(vp)),
1585            date(V_expirationDate(vp)));
1586     printf("accessDate = %s, updateDate = %s\n", date(V_accessDate(vp)),
1587            date(V_updateDate(vp)));
1588     printf("owner = %u, accountNumber = %u\n", V_owner(vp),
1589            V_accountNumber(vp));
1590     printf
1591         ("dayUse = %u; week = (%u, %u, %u, %u, %u, %u, %u), dayUseDate = %s\n",
1592          V_dayUse(vp), V_weekUse(vp)[0], V_weekUse(vp)[1], V_weekUse(vp)[2],
1593          V_weekUse(vp)[3], V_weekUse(vp)[4], V_weekUse(vp)[5],
1594          V_weekUse(vp)[6], date(V_dayUseDate(vp)));
1595     printf("volUpdateCounter = %u\n", V_volUpCounter(vp));
1596 }
1597
1598 /**
1599  * Get the size and times of a file
1600  *
1601  * @param[in]  fd     file descriptor of file to stat
1602  * @param[out] size   size of the file
1603  * @param[out] ctime  ctime of file as a formatted string
1604  * @param[out] mtime  mtime of file as a formatted string
1605  * @param[out] atime  atime of file as a formatted string
1606  *
1607  * @return error code
1608  *   @retval 0 success
1609  *   @retval -1 failed to retrieve file information
1610  */
1611 static int
1612 GetFileInfo(FD_t fd, afs_sfsize_t * size, char **ctime, char **mtime,
1613             char **atime)
1614 {
1615 #ifdef AFS_NT40_ENV
1616     BY_HANDLE_FILE_INFORMATION fi;
1617     LARGE_INTEGER fsize;
1618     if (!GetFileInformationByHandle(fd, &fi)) {
1619         fprintf(stderr, "%s: GetFileInformationByHandle failed\n", progname);
1620         return -1;
1621     }
1622     if (!GetFileSizeEx(fd, &fsize)) {
1623         fprintf(stderr, "%s: GetFileSizeEx failed\n", progname);
1624         return -1;
1625     }
1626     *size = fsize.QuadPart;
1627     *ctime = "N/A";
1628     *mtime = NT_date(&fi.ftLastWriteTime);
1629     *atime = NT_date(&fi.ftLastAccessTime);
1630 #else
1631     struct afs_stat_st status;
1632     if (afs_fstat(fd, &status) == -1) {
1633         fprintf(stderr, "%s: fstat failed %d\n", progname, errno);
1634         return -1;
1635     }
1636     *size = status.st_size;
1637     *ctime = date(status.st_ctime);
1638     *mtime = date(status.st_mtime);
1639     *atime = date(status.st_atime);
1640 #endif
1641     return 0;
1642 }
1643
1644 /**
1645  * Copy the inode data to a file in the current directory.
1646  *
1647  * @param[in] vdp     vnode details object
1648  *
1649  * @return none
1650  */
1651 static void
1652 SaveInode(struct VnodeDetails *vdp)
1653 {
1654     IHandle_t *ih;
1655     FdHandle_t *fdP;
1656     char nfile[50], buffer[256];
1657     int ofd = 0;
1658     afs_foff_t total;
1659     ssize_t len;
1660     Inode ino = VNDISK_GET_INO(vdp->vnode);
1661
1662     if (!VALID_INO(ino)) {
1663         return;
1664     }
1665
1666     IH_INIT(ih, V_device(vdp->vp), V_parentId(vdp->vp), ino);
1667     fdP = IH_OPEN(ih);
1668     if (fdP == NULL) {
1669         fprintf(stderr,
1670                 "%s: Can't open inode %s error %d (ignored)\n",
1671                 progname, PrintInode(NULL, ino), errno);
1672         return;
1673     }
1674     snprintf(nfile, sizeof nfile, "TmpInode.%s", PrintInode(NULL, ino));
1675     ofd = afs_open(nfile, O_CREAT | O_RDWR | O_TRUNC, 0600);
1676     if (ofd < 0) {
1677         fprintf(stderr,
1678                 "%s: Can't create file %s; error %d (ignored)\n",
1679                 progname, nfile, errno);
1680
1681         FDH_REALLYCLOSE(fdP);
1682         IH_RELEASE(ih);
1683         return;
1684     }
1685     total = 0;
1686     while (1) {
1687         ssize_t nBytes;
1688         len = FDH_PREAD(fdP, buffer, sizeof(buffer), total);
1689         if (len < 0) {
1690             FDH_REALLYCLOSE(fdP);
1691             IH_RELEASE(ih);
1692             close(ofd);
1693             unlink(nfile);
1694             fprintf(stderr,
1695                     "%s: Error while reading from inode %s (%d)\n",
1696                     progname, PrintInode(NULL, ino), errno);
1697             return;
1698         }
1699         if (len == 0)
1700             break;              /* No more input */
1701         nBytes = write(ofd, buffer, (size_t)len);
1702         if (nBytes != len) {
1703             FDH_REALLYCLOSE(fdP);
1704             IH_RELEASE(ih);
1705             close(ofd);
1706             unlink(nfile);
1707             fprintf(stderr,
1708                     "%s: Error while writing to \"%s\" (%d - ignored)\n",
1709                     progname, nfile, errno);
1710             return;
1711         }
1712         total += len;
1713     }
1714
1715     FDH_REALLYCLOSE(fdP);
1716     IH_RELEASE(ih);
1717     close(ofd);
1718     printf("... Copied inode %s to file %s (%lu bytes)\n",
1719            PrintInode(NULL, ino), nfile, (unsigned long)total);
1720 }
1721
1722 /**
1723  * get the VnodeDiskObject for a directory given its vnode id.
1724  *
1725  * @param[in]   vp       volume object
1726  * @param[in]   parent   vnode id to read
1727  * @param[out]  pvn      vnode disk object to populate
1728  *
1729  * @post pvn contains copy of disk object for parent id
1730  *
1731  * @return operation status
1732  *   @retval 0   success
1733  *   @retval -1  failure
1734  */
1735 int
1736 GetDirVnode(Volume * vp, VnodeId parent, VnodeDiskObject * pvn)
1737 {
1738     afs_int32 code;
1739     afs_foff_t offset;
1740
1741     if (!DirIndexFd) {
1742         return -1;              /* previously failed to open the large vnode index. */
1743     }
1744     if (parent % 2 == 0) {
1745         fprintf(stderr, "%s: Invalid parent vnode id %lu in volume %lu\n",
1746                 progname,
1747                 afs_printable_uint32_lu(parent),
1748                 afs_printable_uint32_lu(V_id(vp)));
1749     }
1750     offset = vnodeIndexOffset(&VnodeClassInfo[vLarge], parent);
1751     code = FDH_SEEK(DirIndexFd, offset, 0);
1752     if (code == -1) {
1753         fprintf(stderr,
1754                 "%s: GetDirVnode: seek failed for %lu.%lu to offset %llu\n",
1755                 progname, afs_printable_uint32_lu(V_id(vp)),
1756                 afs_printable_uint32_lu(parent), (long long unsigned)offset);
1757         return -1;
1758     }
1759     code = FDH_READ(DirIndexFd, pvn, SIZEOF_LARGEDISKVNODE);
1760     if (code != SIZEOF_LARGEDISKVNODE) {
1761         fprintf(stderr,
1762                 "%s: GetDirVnode: read failed for %lu.%lu at offset %llu\n",
1763                 progname, afs_printable_uint32_lu(V_id(vp)),
1764                 afs_printable_uint32_lu(parent), (long long unsigned)offset);
1765         return -1;
1766     }
1767     if (CheckMagic && (pvn->vnodeMagic != LARGEVNODEMAGIC)) {
1768         fprintf(stderr, "%s: GetDirVnode: bad vnode magic for %lu.%lu at offset %llu\n",
1769                 progname, afs_printable_uint32_lu(V_id(vp)),
1770                 afs_printable_uint32_lu(parent), (long long unsigned)offset);
1771         return -1;
1772     }
1773     if (!pvn->dataVersion) {
1774         fprintf(stderr, "%s: GetDirVnode: dv is zero for %lu.%lu at offset %llu\n",
1775                 progname, afs_printable_uint32_lu(V_id(vp)),
1776                 afs_printable_uint32_lu(parent), (long long unsigned)offset);
1777         return -1;
1778     }
1779     return 0;
1780 }
1781
1782 /**
1783  * Perform inverse lookup on a vice directory object to map a fid onto a dirent string.
1784  *
1785  * @param[in]   vp          volume object
1786  * @param[in]   pvnode      parent directory vnode object
1787  * @param[in]   cvnid       child vnode id to inverse lookup
1788  * @param[in]   cuniq       child uniquifier to inverse lookup
1789  * @param[out]  dirent      buffer in which to store dirent string
1790  * @param[out]  dirent_len  length of dirent buffer
1791  *
1792  * @post dirent contains string for the (cvnid, cuniq) entry
1793  *
1794  * @return operation status
1795  *    @retval 0 success
1796  */
1797 static int
1798 GetDirEntry(Volume * vp, VnodeDiskObject * pvnode, VnodeId cvnid,
1799             afs_uint32 cuniq, char *dirent, size_t dirent_len)
1800 {
1801     DirHandle dir;
1802     Inode ino;
1803     int volumeChanged;
1804     afs_int32 code;
1805
1806     ino = VNDISK_GET_INO(pvnode);
1807     if (!VALID_INO(ino)) {
1808         fprintf(stderr, "%s: GetDirEntry invalid parent ino\n", progname);
1809         return -1;
1810     }
1811     SetSalvageDirHandle(&dir, V_parentId(vp), V_device(vp), ino,
1812                         &volumeChanged);
1813     code = afs_dir_InverseLookup(&dir, cvnid, cuniq, dirent, dirent_len);
1814     if (code) {
1815         fprintf(stderr, "%s: afs_dir_InverseLookup failed with code %d\n",
1816                 progname, code);
1817     }
1818     FidZap(&dir);
1819     return code;
1820 }
1821
1822 /**
1823  * Lookup the path of this vnode, relative to the root of the volume.
1824  *
1825  * @param[in] vdp    vnode details
1826  *
1827  * @return status
1828  *   @retval 0 success
1829  *   @retval -1 error
1830  */
1831 int
1832 LookupPath(struct VnodeDetails *vdp)
1833 {
1834 #define MAX_PATH_LEN 1023
1835     static char path_buffer[MAX_PATH_LEN + 1];
1836     static char dirent[MAX_PATH_LEN + 1];
1837     char vnode_buffer[SIZEOF_LARGEDISKVNODE];
1838     struct VnodeDiskObject *pvn = (struct VnodeDiskObject *)vnode_buffer;
1839     int code = 0;
1840     int space;
1841     char *cursor;
1842     Volume *vp = vdp->vp;
1843     VnodeId parent = vdp->vnode->parent;
1844     VnodeId cvnid = vdp->vnodeNumber;
1845     afs_uint32 cuniq = vdp->vnode->uniquifier;
1846
1847     if (!parent) {
1848         vdp->path = "/";        /* this is root */
1849         return 0;
1850     }
1851
1852     space = sizeof(path_buffer) - 1;
1853     cursor = &path_buffer[space];
1854     *cursor = '\0';
1855
1856     while (parent) {
1857         int len;
1858
1859         code = GetDirVnode(vp, parent, pvn);
1860         if (code) {
1861             cursor = NULL;
1862             break;
1863         }
1864         code = GetDirEntry(vp, pvn, cvnid, cuniq, dirent, MAX_PATH_LEN);
1865         if (code) {
1866             cursor = NULL;
1867             break;
1868         }
1869
1870         len = strlen(dirent);
1871         if (len == 0) {
1872             fprintf(stderr,
1873                     "%s: Failed to lookup path for fid %lu.%lu.%lu: empty dir entry\n",
1874                     progname, afs_printable_uint32_lu(V_id(vdp->vp)),
1875                     afs_printable_uint32_lu(vdp->vnodeNumber),
1876                     afs_printable_uint32_lu(vdp->vnode->uniquifier));
1877             cursor = NULL;
1878             code = -1;
1879             break;
1880         }
1881
1882         if (space < (len + 1)) {
1883             fprintf(stderr,
1884                     "%s: Failed to lookup path for fid %lu.%lu.%lu: path exceeds max length (%u).\n",
1885                     progname, afs_printable_uint32_lu(V_id(vdp->vp)),
1886                     afs_printable_uint32_lu(vdp->vnodeNumber),
1887                     afs_printable_uint32_lu(vdp->vnode->uniquifier),
1888                     MAX_PATH_LEN);
1889             cursor = NULL;
1890             code = -1;
1891             break;
1892         }
1893
1894         /* prepend path component */
1895         cursor -= len;
1896         memcpy(cursor, dirent, len);
1897         *--cursor = '/';
1898         space -= (len + 1);
1899
1900         /* next parent */
1901         cvnid = parent;
1902         cuniq = pvn->uniquifier;
1903         parent = pvn->parent;
1904     }
1905
1906     if (cursor) {
1907         vdp->path = cursor;
1908     }
1909     return code;
1910 }
1911
1912 /**
1913  * Read the symlink target and determine if this vnode is a mount point.
1914  *
1915  * @param[inout]   vdp    vnode details object
1916  *
1917  * @return error code
1918  *   @retval 0 success
1919  *   @retval -1 failure
1920  */
1921 static int
1922 ReadSymlinkTarget(struct VnodeDetails *vdp)
1923 {
1924 #define MAX_SYMLINK_LEN 1023
1925     static char buffer[MAX_SYMLINK_LEN + 1];
1926     int code;
1927     Volume *vp = vdp->vp;
1928     VnodeDiskObject *vnode = vdp->vnode;
1929     VnodeId vnodeNumber = vdp->vnodeNumber;
1930     IHandle_t *ihP = NULL;
1931     FdHandle_t *fdP = NULL;
1932     afs_fsize_t fileLength;
1933     int readLength;
1934     Inode ino;
1935
1936     ino = VNDISK_GET_INO(vnode);
1937     VNDISK_GET_LEN(fileLength, vnode);
1938
1939     if (fileLength > MAX_SYMLINK_LEN) {
1940         fprintf(stderr,
1941                 "%s: Symlink contents for fid (%lu.%lu.%lu.%lu) exceeds "
1942                 "%u, file length is %llu)!\n", progname,
1943                 afs_printable_uint32_lu(V_id(vp)),
1944                 afs_printable_uint32_lu(vnodeNumber),
1945                 afs_printable_uint32_lu(vnode->uniquifier),
1946                 afs_printable_uint32_lu(vnode->dataVersion),
1947                 MAX_SYMLINK_LEN,
1948                 fileLength);
1949         return -1;
1950     }
1951     if (fileLength == 0) {
1952         fprintf(stderr,
1953                 "%s: Symlink contents for fid (%lu.%lu.%lu.%lu) is empty.\n",
1954                 progname,
1955                 afs_printable_uint32_lu(V_id(vp)),
1956                 afs_printable_uint32_lu(vnodeNumber),
1957                 afs_printable_uint32_lu(vnode->uniquifier),
1958                 afs_printable_uint32_lu(vnode->dataVersion));
1959         return -1;
1960     }
1961
1962     IH_INIT(ihP, V_device(vp), V_parentId(vp), ino);
1963     fdP = IH_OPEN(ihP);
1964     if (fdP == NULL) {
1965         code = -1;
1966         goto cleanup;
1967     }
1968     if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1969         code = -1;
1970         goto cleanup;
1971     }
1972     readLength = FDH_READ(fdP, buffer, fileLength);
1973     if (readLength < 0) {
1974         fprintf(stderr,
1975                 "%s: Error reading symlink contents for fid (%lu.%lu.%lu.%lu); "
1976                 "errno %d\n",
1977                 progname,
1978                 afs_printable_uint32_lu(V_id(vp)),
1979                 afs_printable_uint32_lu(vnodeNumber),
1980                 afs_printable_uint32_lu(vnode->uniquifier),
1981                 afs_printable_uint32_lu(vnode->dataVersion), errno);
1982         code = -1;
1983         goto cleanup;
1984     } else if (readLength != fileLength) {
1985         fprintf(stderr,
1986                 "%s: Symlink contents for fid (%lu.%lu.%lu.%lu) don't match "
1987                 "vnode file length metadata (len=%llu, actual=%lld)!\n",
1988                 progname,
1989                 afs_printable_uint32_lu(V_id(vp)),
1990                 afs_printable_uint32_lu(vnodeNumber),
1991                 afs_printable_uint32_lu(vnode->uniquifier),
1992                 afs_printable_uint32_lu(vnode->dataVersion), fileLength,
1993                 (long long)readLength);
1994         code = -1;
1995         goto cleanup;
1996     }
1997     code = 0;
1998
1999     if (readLength > 1 && (buffer[0] == '#' || buffer[0] == '%')
2000         && buffer[readLength - 1] == '.') {
2001         char *sep;
2002         buffer[readLength - 1] = '\0';  /* stringify; clobbers trailing dot */
2003         sep = strchr(buffer, ':');
2004         vdp->t = VNODE_U_MOUNT;
2005         vdp->u.mnt.type = buffer[0];
2006         if (!sep) {
2007             vdp->u.mnt.cell = NULL;
2008             vdp->u.mnt.vol = buffer + 1;
2009         } else {
2010             *sep = '\0';
2011             vdp->u.mnt.cell = buffer + 1;
2012             vdp->u.mnt.vol = sep + 1;
2013         }
2014     } else {
2015         buffer[readLength] = '\0';
2016         vdp->t = VNODE_U_SYMLINK;
2017         vdp->u.target = buffer;
2018     }
2019
2020   cleanup:
2021     if (fdP) {
2022         FDH_CLOSE(fdP);
2023     }
2024     if (ihP) {
2025         IH_RELEASE(ihP);
2026     }
2027     return code;
2028 }
2029
2030 /**
2031  * Print vnode details line
2032  *
2033  * @param[inout]  vdp   vnode details object
2034  *
2035  * @return none
2036  */
2037 static void
2038 PrintVnodeDetails(struct VnodeDetails *vdp)
2039 {
2040     switch (vdp->vnode->type) {
2041     case vNull:
2042         break;
2043     case vFile:
2044         if (FindVnType & FIND_FILE) {
2045             PrintColumns(vdp, "file");
2046         }
2047         break;
2048     case vDirectory:
2049         if (FindVnType & FIND_DIR) {
2050             PrintColumns(vdp, "dir");
2051         }
2052         break;
2053     case vSymlink:
2054         if (FindVnType & (FIND_MOUNT | FIND_SYMLINK)) {
2055             ReadSymlinkTarget(vdp);
2056             if ((FindVnType & FIND_MOUNT) && (vdp->t == VNODE_U_MOUNT)) {
2057                 PrintColumns(vdp, "mount");
2058             }
2059             if ((FindVnType & FIND_SYMLINK) && (vdp->t == VNODE_U_SYMLINK)) {
2060                 PrintColumns(vdp, "symlink");
2061             }
2062         }
2063         break;
2064     default:
2065         fprintf(stderr,
2066                 "%s: Warning: unexpected vnode type %u on fid %lu.%lu.%lu",
2067                 progname, vdp->vnode->type,
2068                 afs_printable_uint32_lu(V_id(vdp->vp)),
2069                 afs_printable_uint32_lu(vdp->vnodeNumber),
2070                 afs_printable_uint32_lu(vdp->vnode->uniquifier));
2071     }
2072 }
2073
2074 /**
2075  * Print each access entry of a vnode
2076  *
2077  * @param[in]  vdp   vnode details object
2078  *
2079  * @return none
2080  */
2081 static void
2082 ScanAcl(struct VnodeDetails *vdp)
2083 {
2084     int i;
2085     struct acl_accessList *acl;
2086     VnodeDiskObject *vnode = vdp->vnode;
2087
2088     if (vnode->type == vNull) {
2089         return;
2090     }
2091
2092     acl = VVnodeDiskACL(vnode);
2093     for (i = 0; i < acl->positive; i++) {
2094         vdp->t = VNODE_U_POS_ACCESS;
2095         vdp->u.access = &(acl->entries[i]);
2096         PrintColumns(vdp, "acl");
2097     }
2098     for (i = (acl->total - 1); i >= (acl->total - acl->negative); i--) {
2099         vdp->t = VNODE_U_NEG_ACCESS;
2100         vdp->u.access = &(acl->entries[i]);
2101         PrintColumns(vdp, "acl");
2102     }
2103 }
2104
2105 /**
2106  * Determine if the mode matches all the given masks.
2107  *
2108  * Returns true if the mode bits match all the given masks. A mask matches if at
2109  * least one bit in the mask is present in the mode bits.  An empty mode mask
2110  * list matches all modes (even if all the mode bits are zero.)
2111  *
2112  * param[in]  modeBits  unix mode bits of a vnode
2113  *
2114  */
2115 static int
2116 ModeMaskMatch(unsigned int modeBits)
2117 {
2118     int i;
2119
2120     for (i = 0; ModeMask[i] && i <= sizeof(ModeMask) / sizeof(*ModeMask); i++) {
2121         if ((ModeMask[i] & modeBits) == 0) {
2122             return 0;           /* at least one mode bit is not present */
2123         }
2124     }
2125     return 1;
2126 }
2127
2128 /**
2129  * Scan a volume index and handle each vnode
2130  *
2131  * @param[in] vp      volume object
2132  * @param[in] class   which index to scan
2133  *
2134  * @return none
2135  */
2136 void
2137 HandleVnodes(Volume * vp, VnodeClass class)
2138 {
2139     afs_int32 diskSize =
2140         (class == vSmall ? SIZEOF_SMALLDISKVNODE : SIZEOF_LARGEDISKVNODE);
2141     char buf[SIZEOF_LARGEDISKVNODE];
2142     struct VnodeDiskObject *vnode = (struct VnodeDiskObject *)buf;
2143     StreamHandle_t *file = NULL;
2144     int vnodeIndex;
2145     afs_sfsize_t nVnodes;
2146     afs_foff_t offset = 0;
2147     IHandle_t *ih = vp->vnodeIndex[class].handle;
2148     FdHandle_t *fdP = NULL;
2149     afs_sfsize_t size;
2150     char *ctime, *atime, *mtime;
2151     struct opr_queue *scanList = &VnodeScanLists[class];
2152     struct opr_queue *cursor;
2153
2154     if (opr_queue_IsEmpty(scanList)) {
2155         return;
2156     }
2157
2158     for (opr_queue_Scan(scanList, cursor)) {
2159         struct VnodeScanProc *entry = (struct VnodeScanProc *)cursor;
2160         if (entry->heading) {
2161             printf("%s", entry->heading);
2162         }
2163     }
2164
2165     fdP = IH_OPEN(ih);
2166     if (fdP == NULL) {
2167         fprintf(stderr, "%s: open failed: ", progname);
2168         goto error;
2169     }
2170
2171     file = FDH_FDOPEN(fdP, "r");
2172     if (!file) {
2173         fprintf(stderr, "%s: fdopen failed\n", progname);
2174         goto error;
2175     }
2176
2177     if (GetFileInfo(fdP->fd_fd, &size, &ctime, &atime, &mtime) != 0) {
2178         goto error;
2179     }
2180     if (InodeTimes) {
2181         printf("ichanged : %s\nimodified: %s\niaccessed: %s\n\n", ctime,
2182                mtime, atime);
2183     }
2184
2185     nVnodes = (size / diskSize) - 1;
2186     if (nVnodes > 0) {
2187         STREAM_ASEEK(file, diskSize);
2188     } else
2189         nVnodes = 0;
2190
2191     for (vnodeIndex = 0;
2192          nVnodes && STREAM_READ(vnode, diskSize, 1, file) == 1;
2193          nVnodes--, vnodeIndex++, offset += diskSize) {
2194
2195         struct VnodeDetails vnodeDetails;
2196
2197         if (!ModeMaskMatch(vnode->modeBits)) {
2198             continue;
2199         }
2200
2201         memset(&vnodeDetails, 0, sizeof(struct VnodeDetails));
2202         vnodeDetails.vp = vp;
2203         vnodeDetails.class = class;
2204         vnodeDetails.vnode = vnode;
2205         vnodeDetails.vnodeNumber = bitNumberToVnodeNumber(vnodeIndex, class);
2206         vnodeDetails.offset = offset;
2207         vnodeDetails.index = vnodeIndex;
2208
2209         for (opr_queue_Scan(scanList, cursor)) {
2210             struct VnodeScanProc *entry = (struct VnodeScanProc *)cursor;
2211             if (entry->proc) {
2212                 (*entry->proc) (&vnodeDetails);
2213             }
2214         }
2215     }
2216
2217   error:
2218     if (file) {
2219         STREAM_CLOSE(file);
2220     }
2221     if (fdP) {
2222         FDH_CLOSE(fdP);
2223     }
2224 }
2225
2226 /**
2227  * Print vnode information
2228  *
2229  * @param[in] vdp          vnode details object
2230  *
2231  * @return none
2232  */
2233 void
2234 PrintVnode(struct VnodeDetails *vdp)
2235 {
2236 #if defined(AFS_NAMEI_ENV)
2237     IHandle_t *ihtmpp;
2238     namei_t filename;
2239 #endif
2240     afs_foff_t offset = vdp->offset;
2241     VnodeDiskObject *vnode = vdp->vnode;
2242     afs_fsize_t fileLength;
2243     Inode ino;
2244
2245     ino = VNDISK_GET_INO(vnode);
2246     VNDISK_GET_LEN(fileLength, vnode);
2247
2248     /* The check for orphaned vnodes is currently limited to non-empty
2249      * vnodes with a parent of zero (and which are not the first entry
2250      * in the index). */
2251     if (ShowOrphaned && (fileLength == 0 || vnode->parent || !offset))
2252         return;
2253
2254     printf
2255         ("%10lld Vnode %u.%u.%u cloned: %u, length: %llu linkCount: %d parent: %u",
2256          (long long)offset, vdp->vnodeNumber, vnode->uniquifier,
2257          vnode->dataVersion, vnode->cloned, (afs_uintmax_t) fileLength,
2258          vnode->linkCount, vnode->parent);
2259     if (DumpInodeNumber)
2260         printf(" inode: %s", PrintInode(NULL, ino));
2261     if (DumpDate)
2262         printf(" ServerModTime: %s", date(vnode->serverModifyTime));
2263 #if defined(AFS_NAMEI_ENV)
2264     if (PrintFileNames) {
2265         IH_INIT(ihtmpp, V_device(vdp->vp), V_parentId(vdp->vp), ino);
2266         namei_HandleToName(&filename, ihtmpp);
2267 #if !defined(AFS_NT40_ENV)
2268         printf(" UFS-Filename: %s", filename.n_path);
2269 #else
2270         printf(" NTFS-Filename: %s", filename.n_path);
2271 #endif
2272     }
2273 #endif
2274     printf("\n");
2275 }
2276
2277 /**
2278  * Print the volume partition id
2279  *
2280  * @param[in]  vp  volume object
2281  *
2282  * @return none
2283  */
2284 static void
2285 PrintPartitionId(Volume * vp)
2286 {
2287     char *partition = VPartitionPath(V_partition(vp));
2288
2289     if (!strncmp(partition, "/vicep", 6)) {
2290         printf("%s", partition + 6);
2291     } else if (!strncmp(partition, "vicep", 5)) {
2292         printf("%s", partition + 5);
2293     } else {
2294         fprintf(stderr, "Invalid partition for volume id %lu\n",
2295                 afs_printable_uint32_lu(V_id(vp)));
2296         printf("%s", PLACEHOLDER);
2297     }
2298 }
2299
2300 /**
2301  * Print the vnode type description string
2302  *
2303  * @param[in]  type  vnode type
2304  *
2305  * @return none
2306  */
2307 static void
2308 PrintVnodeType(int type)
2309 {
2310     switch (type) {
2311     case vNull:
2312         printf("null");
2313         break;
2314     case vFile:
2315         printf("file");
2316         break;
2317     case vDirectory:
2318         printf("dir");
2319         break;
2320     case vSymlink:
2321         printf("symlink");
2322         break;
2323     default:
2324         printf("unknown");
2325     }
2326 }
2327
2328 /**
2329  * Print right bits as string.
2330  *
2331  * param[in] rights  rights bitmap
2332  */
2333 static void
2334 PrintRights(int rights)
2335 {
2336     if (rights & PRSFS_READ) {
2337         printf("r");
2338     }
2339     if (rights & PRSFS_LOOKUP) {
2340         printf("l");
2341     }
2342     if (rights & PRSFS_INSERT) {
2343         printf("i");
2344     }
2345     if (rights & PRSFS_DELETE) {
2346         printf("d");
2347     }
2348     if (rights & PRSFS_WRITE) {
2349         printf("w");
2350     }
2351     if (rights & PRSFS_LOCK) {
2352         printf("k");
2353     }
2354     if (rights & PRSFS_ADMINISTER) {
2355         printf("a");
2356     }
2357     if (rights & PRSFS_USR0) {
2358         printf("A");
2359     }
2360     if (rights & PRSFS_USR1) {
2361         printf("B");
2362     }
2363     if (rights & PRSFS_USR2) {
2364         printf("C");
2365     }
2366     if (rights & PRSFS_USR3) {
2367         printf("D");
2368     }
2369     if (rights & PRSFS_USR4) {
2370         printf("E");
2371     }
2372     if (rights & PRSFS_USR5) {
2373         printf("F");
2374     }
2375     if (rights & PRSFS_USR6) {
2376         printf("G");
2377     }
2378     if (rights & PRSFS_USR7) {
2379         printf("H");
2380     }
2381 }
2382
2383 /**
2384  * Print the path to the namei file.
2385  */
2386 static void
2387 PrintNamei(Volume * vp, VnodeDiskObject * vnode)
2388 {
2389 #ifdef AFS_NAMEI_ENV
2390     namei_t name;
2391     IHandle_t *ihP = NULL;
2392     Inode ino;
2393     ino = VNDISK_GET_INO(vnode);
2394     IH_INIT(ihP, V_device(vp), V_parentId(vp), ino);
2395     namei_HandleToName(&name, ihP);
2396     printf("%s", name.n_path);
2397     IH_RELEASE(ihP);
2398 #else
2399     printf("%s", PLACEHOLDER);
2400 #endif
2401 }
2402
2403 /**
2404  * Print the column heading line.
2405  */
2406 static void
2407 PrintColumnHeading(void)
2408 {
2409     int i;
2410     const char *name;
2411
2412     for (i = 0; i < NumOutputColumns; i++) {
2413         if (i > 0) {
2414             printf("%s", ColumnDelim);
2415         }
2416         name = ColumnName[OutputColumn[i]].name;
2417         while (*name) {
2418             putchar(toupper(*name++));
2419         }
2420     }
2421     printf("\n");
2422 }
2423
2424 /**
2425  * Print output columns for the vnode/acess entry.
2426  *
2427  * @param[in]  vdp   vnode details object
2428  * @param[in]  desc  type of line to be printed
2429  *
2430  * @return none
2431  */
2432 static void
2433 PrintColumns(struct VnodeDetails *vdp, const char *desc)
2434 {
2435     int i;
2436     afs_fsize_t length;
2437
2438     for (i = 0; i < NumOutputColumns; i++) {
2439         if (i > 0) {
2440             printf("%s", ColumnDelim);
2441         }
2442         switch (OutputColumn[i]) {
2443         case col_host:
2444             printf("%s", Hostname);
2445             break;
2446         case col_desc:
2447             printf("%s", desc);
2448             break;
2449         case col_vid:
2450             printf("%lu", afs_printable_uint32_lu(V_id(vdp->vp)));
2451             break;
2452         case col_offset:
2453             printf("%llu", vdp->offset);
2454             break;
2455         case col_vtype:
2456             printf("%s", volumeTypeShortString(V_type(vdp->vp)));
2457             break;
2458         case col_vname:
2459             printf("%s", V_name(vdp->vp));
2460             break;
2461         case col_part:
2462             printf("%s", VPartitionPath(V_partition(vdp->vp)));
2463             break;
2464         case col_partid:
2465             PrintPartitionId(vdp->vp);
2466             break;
2467         case col_fid:
2468             printf("%lu.%lu.%lu",
2469                    afs_printable_uint32_lu(V_id(vdp->vp)),
2470                    afs_printable_uint32_lu(vdp->vnodeNumber),
2471                    afs_printable_uint32_lu(vdp->vnode->uniquifier));
2472             break;
2473         case col_path:
2474             if (!vdp->path) {
2475                 LookupPath(vdp);
2476             }
2477             printf("%s", vdp->path ? vdp->path : PLACEHOLDER);
2478             break;
2479         case col_target:
2480             printf("%s",
2481                    (vdp->t == VNODE_U_SYMLINK ? vdp->u.target : PLACEHOLDER));
2482             break;
2483         case col_mount:
2484             if (vdp->t != VNODE_U_MOUNT) {
2485                 printf("%s", PLACEHOLDER);
2486             } else {
2487                 printf("%c", vdp->u.mnt.type);
2488                 if (vdp->u.mnt.cell) {
2489                     printf("%s:", vdp->u.mnt.cell);
2490                 }
2491                 printf("%s.", vdp->u.mnt.vol);
2492             }
2493             break;
2494         case col_mtype:
2495             printf("%c", (vdp->t == VNODE_U_MOUNT ? vdp->u.mnt.type : '-'));
2496             break;
2497         case col_mcell:
2498             printf("%s",
2499                    (vdp->t == VNODE_U_MOUNT ? vdp->u.mnt.cell : PLACEHOLDER));
2500             break;
2501         case col_mvol:
2502             printf("%s",
2503                    (vdp->t == VNODE_U_MOUNT ? vdp->u.mnt.vol : PLACEHOLDER));
2504             break;
2505         case col_aid:
2506             if (vdp->t == VNODE_U_POS_ACCESS || vdp->t == VNODE_U_NEG_ACCESS) {
2507                 printf("%d", vdp->u.access->id);
2508             } else {
2509                 printf("%s", PLACEHOLDER);
2510             }
2511             break;
2512         case col_arights:
2513             if (vdp->t == VNODE_U_POS_ACCESS) {
2514                 printf("+");
2515                 PrintRights(vdp->u.access->rights);
2516             } else if (vdp->t == VNODE_U_NEG_ACCESS) {
2517                 printf("-");
2518                 PrintRights(vdp->u.access->rights);
2519             }
2520             break;
2521         case col_vntype:
2522             PrintVnodeType(vdp->vnode->type);
2523             break;
2524         case col_cloned:
2525             printf("%c", vdp->vnode->cloned ? 'y' : 'n');
2526             break;
2527         case col_mode:
2528             printf("0%o", vdp->vnode->modeBits);
2529             break;
2530         case col_links:
2531             printf("%lu", afs_printable_uint32_lu(vdp->vnode->linkCount));
2532             break;
2533         case col_length:
2534             VNDISK_GET_LEN(length, vdp->vnode);
2535             printf("%llu", length);
2536             break;
2537         case col_uniq:
2538             printf("%lu", afs_printable_uint32_lu(vdp->vnode->uniquifier));
2539             break;
2540         case col_dv:
2541             printf("%lu", afs_printable_uint32_lu(vdp->vnode->dataVersion));
2542             break;
2543         case col_inode:
2544             printf("%" AFS_UINT64_FMT, VNDISK_GET_INO(vdp->vnode));
2545             break;
2546         case col_namei:
2547             PrintNamei(vdp->vp, vdp->vnode);
2548             break;
2549         case col_modtime:
2550             printf("%lu",
2551                    afs_printable_uint32_lu(vdp->vnode->unixModifyTime));
2552             break;
2553         case col_author:
2554             printf("%lu", afs_printable_uint32_lu(vdp->vnode->author));
2555             break;
2556         case col_owner:
2557             printf("%lu", afs_printable_uint32_lu(vdp->vnode->owner));
2558             break;
2559         case col_parent:
2560             printf("%lu", afs_printable_uint32_lu(vdp->vnode->parent));
2561             break;
2562         case col_magic:
2563             printf("0x%08X", vdp->vnode->vnodeMagic);
2564             break;
2565         case col_lock:
2566             printf("%lu.%lu",
2567                    afs_printable_uint32_lu(vdp->vnode->lock.lockCount),
2568                    afs_printable_uint32_lu(vdp->vnode->lock.lockTime));
2569             break;
2570         case col_smodtime:
2571             printf("%lu",
2572                    afs_printable_uint32_lu(vdp->vnode->serverModifyTime));
2573             break;
2574         case col_group:
2575             printf("%lu", afs_printable_uint32_lu(vdp->vnode->group));
2576             break;
2577         default:
2578             fprintf(stderr, "%s: Unknown column type: %d (%d)\n", progname,
2579                     OutputColumn[i], i);
2580             break;
2581         }
2582     }
2583     printf("\n");
2584 }